diff --git a/contrib/bc/LICENSE.md b/contrib/bc/LICENSE.md index 8ab2e606988..c8f6758e6d4 100644 --- a/contrib/bc/LICENSE.md +++ b/contrib/bc/LICENSE.md @@ -1,6 +1,6 @@ # License -Copyright (c) 2018-2021 Gavin D. Howard +Copyright (c) 2018-2024 Gavin D. Howard Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -31,7 +31,7 @@ copyrights and license: Copyright (c) 2010-2014, Salvatore Sanfilippo
Copyright (c) 2010-2013, Pieter Noordhuis
Copyright (c) 2018 rain-1
-Copyright (c) 2018-2021, Gavin D. Howard +Copyright (c) 2018-2023, Gavin D. Howard Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -59,8 +59,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The files `src/rand.c` and `include/rand.h` are under the following copyrights and license: -Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors -Copyright (c) 2018-2021 Gavin D. Howard +Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors
+Copyright (c) 2018-2024 Gavin D. Howard Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/contrib/bc/MEMORY_BUGS.md b/contrib/bc/MEMORY_BUGS.md new file mode 100644 index 00000000000..2e41ad3d75c --- /dev/null +++ b/contrib/bc/MEMORY_BUGS.md @@ -0,0 +1,65 @@ +# Memory Bugs + +This is a list of all of the memory bugs that were found in *released* versions +of `bc`, `dc`, or `bcl`. (Non-released commits with memory bugs do not count.) + +I made this list for two reasons: first, so users can know what versions of +`bc`, `dc`, and `bcl` have vulnerabilities, and two, I once had a perfect record +and then found a couple, but forgot and claimed I still had a perfect record +right after, which was embarrassing. + +This list is sorted by the first version a bug exists in, not the last it +existed in. + +* In versions `1.1.0` until `6.2.0` (inclusive) of `bc` and `dc`, there is a + out of bounds read and write in history when pressing ctrl+r (or any other + unused letter) then inserting two characters. + + The first version without this bug is `6.2.1`. + +* In versions `3.0.0` until `6.0.1` (inclusive) of `bc` and `dc`, there is a + double-free on `SIGINT` when using command-line expressions with `-e` and + `-f`. This was caused by not properly ending a jump series. + + The first version without this bug is `6.0.2`. + +* In versions `3.0.0` until `6.7.5` (inclusive) of `bc` and `dc`, there is a + possible out-of-bounds read when there is an error flushing `stdout` on exit + because such an error would cause `bc` and `dc` to attempt to use a `jmp_buf` + when none exists. + + The first version without this bug is `6.7.6`. + +* In versions `5.0.0` until `6.0.4` (inclusive) of `bc`, there is an + out-of-bounds access if a non-local (non-`auto`) variable is set to a string + with `asciify()`, then the function is redefined with a use of the same + non-local variable. + + This happened because strings were stored per-function, and the non-local + variable now had a reference to the string in the old function, which could be + at a higher index than exists in the new function. Strings are stored globally + now, and they are *not* freed once not used. + + The first version without this bug is `6.1.0`. + +* In versions `5.0.0` until `6.0.4` (inclusive) of `bc`, there is another + out-of-bounds access if an array is passed to the `asciify()` built-in + function as the only argument. This happened because arrays are allowed as + function arguments, which allowed them to be used as arguments to `asciify()`, + but they should not have been allowed. However, since they were, the + `asciify()` code tried to access an argument that was not there. + + The first version without this bug is `6.1.0`. + +* In version `6.0.0` of `bcl`, there are several uses of initialized data that + have the same root cause: I forgot to call `memset()` on the per-thread global + data. This is because the data used to be *actually* global, which meant that + it was initialized to zero by the system. This happened because I thought I + had properly hooked Valgrind into my `bcl` tests, but I had not. + + The first version without this bug is `6.0.1`. + +* In version `6.0.0` until `6.2.4` (inclusive) of `bcl`, there is a possible + use-after-free if `bcl_init()` fails. + + The first version without this bug is `6.2.5`. diff --git a/contrib/bc/Makefile.in b/contrib/bc/Makefile.in index 3d6780d6ac9..c63dc242e79 100644 --- a/contrib/bc/Makefile.in +++ b/contrib/bc/Makefile.in @@ -1,7 +1,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -29,6 +29,15 @@ # .POSIX: +ROOTDIR = %%ROOTDIR%% +INCDIR = $(ROOTDIR)/include +SRCDIR = $(ROOTDIR)/src +TESTSDIR = $(ROOTDIR)/tests +SCRIPTSDIR = $(ROOTDIR)/scripts +GENDIR = $(ROOTDIR)/gen + +BUILDDIR = %%BUILDDIR%% + SRC = %%SRC%% OBJ = %%OBJ%% GCDA = %%GCDA%% @@ -39,46 +48,45 @@ 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 +HEADERS = $(INCDIR)/args.h $(INCDIR)/file.h $(INCDIR)/lang.h $(INCDIR)/lex.h $(INCDIR)/num.h $(INCDIR)/opt.h $(INCDIR)/parse.h $(INCDIR)/program.h $(INCDIR)/read.h $(INCDIR)/status.h $(INCDIR)/vector.h $(INCDIR)/vm.h +BC_HEADERS = $(INCDIR)/bc.h +DC_HEADERS = $(INCDIR)/dc.h +HISTORY_HEADERS = $(INCDIR)/history.h +EXTRA_MATH_HEADERS = $(INCDIR)/rand.h +LIBRARY_HEADERS = $(INCDIR)/bcl.h $(INCDIR)/library.h -GEN_DIR = gen +GEN_DIR = %%GEN_DIR%% GEN = %%GEN%% GEN_EXEC = $(GEN_DIR)/$(GEN) -GEN_C = $(GEN_DIR)/$(GEN).c +GEN_C = $(GENDIR)/$(GEN).c GEN_EMU = %%GEN_EMU%% -BC_LIB = $(GEN_DIR)/lib.bc +BC_LIB = $(GENDIR)/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 = $(GENDIR)/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 = $(GENDIR)/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 = $(GENDIR)/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%% @@ -86,6 +94,10 @@ BC = bc DC = dc BC_EXEC = $(BIN)/$(EXEC_PREFIX)$(BC) DC_EXEC = $(BIN)/$(EXEC_PREFIX)$(DC) +BC_FUZZER = $(BIN)/$(BC)_fuzzer_c +BC_FUZZER_C = $(BIN)/$(BC)_fuzzer_C +DC_FUZZER = $(BIN)/$(DC)_fuzzer_c +DC_FUZZER_C = $(BIN)/$(DC)_fuzzer_C BC_TEST_OUTPUTS = tests/bc_outputs BC_FUZZ_OUTPUTS = tests/fuzzing/bc_outputs1 tests/fuzzing/bc_outputs2 tests/fuzzing/bc_outputs3 @@ -97,7 +109,7 @@ LIB_NAME = $(LIB).a LIBBC = $(BIN)/$(LIB_NAME) BCL = bcl BCL_TEST = $(BIN)/$(BCL) -BCL_TEST_C = tests/$(BCL).c +BCL_TEST_C = $(TESTSDIR)/$(BCL).c MANUALS = manuals BC_MANPAGE_NAME = $(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX).1 @@ -112,9 +124,13 @@ BCL_MD = $(BCL_MANPAGE).md MANPAGE_INSTALL_ARGS = -Dm644 BINARY_INSTALL_ARGS = -Dm755 +PC_INSTALL_ARGS = $(MANPAGE_INSTALL_ARGS) + +BCL_PC = $(BCL).pc +PC_PATH = %%PC_PATH%% BCL_HEADER_NAME = bcl.h -BCL_HEADER = include/$(BCL_HEADER_NAME) +BCL_HEADER = $(INCDIR)/$(BCL_HEADER_NAME) %%DESTDIR%% BINDIR = %%BINDIR%% @@ -134,11 +150,14 @@ 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_EXCLUDE_EXTRA_MATH = %%EXCLUDE_EXTRA_MATH%% BC_ENABLE_AFL = %%FUZZ%% +BC_ENABLE_OSSFUZZ = %%OSSFUZZ%% BC_ENABLE_MEMCHECK = %%MEMCHECK%% +LIB_FUZZING_ENGINE = %%LIB_FUZZING_ENGINE%% + BC_DEFAULT_BANNER = %%BC_DEFAULT_BANNER%% BC_DEFAULT_SIGINT_RESET = %%BC_DEFAULT_SIGINT_RESET%% DC_DEFAULT_SIGINT_RESET = %%DC_DEFAULT_SIGINT_RESET%% @@ -146,6 +165,10 @@ 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%% +BC_DEFAULT_EXPR_EXIT = %%BC_DEFAULT_EXPR_EXIT%% +DC_DEFAULT_EXPR_EXIT = %%DC_DEFAULT_EXPR_EXIT%% +BC_DEFAULT_DIGIT_CLAMP = %%BC_DEFAULT_DIGIT_CLAMP%% +DC_DEFAULT_DIGIT_CLAMP = %%DC_DEFAULT_DIGIT_CLAMP%% RM = rm MKDIR = mkdir @@ -158,13 +181,13 @@ 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 +INSTALL = $(SCRIPTSDIR)/exec-install.sh +SAFE_INSTALL = $(SCRIPTSDIR)/safe-install.sh +LINK = $(SCRIPTSDIR)/link.sh +MANPAGE = $(SCRIPTSDIR)/manpage.sh +KARATSUBA = $(SCRIPTSDIR)/karatsuba.py +LOCALE_INSTALL = $(SCRIPTSDIR)/locale_install.sh +LOCALE_UNINSTALL = $(SCRIPTSDIR)/locale_uninstall.sh VALGRIND_ARGS = --error-exitcode=100 --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all @@ -176,21 +199,26 @@ 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) +BC_DEFS4 = -DBC_DEFAULT_EXPR_EXIT=$(BC_DEFAULT_EXPR_EXIT) +BC_DEFS5 = -DBC_DEFAULT_DIGIT_CLAMP=$(BC_DEFAULT_DIGIT_CLAMP) +BC_DEFS = $(BC_DEFS0) $(BC_DEFS1) $(BC_DEFS2) $(BC_DEFS3) $(BC_DEFS4) $(BC_DEFS5) 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) +DC_DEFS4 = -DDC_DEFAULT_EXPR_EXIT=$(DC_DEFAULT_EXPR_EXIT) +DC_DEFS5 = -DDC_DEFAULT_DIGIT_CLAMP=$(DC_DEFAULT_DIGIT_CLAMP) +DC_DEFS = $(DC_DEFS1) $(DC_DEFS2) $(DC_DEFS3) $(DC_DEFS4) $(DC_DEFS5) 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%% +CPPFLAGS2 = $(CPPFLAGS1) -I$(INCDIR)/ -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%% +CPPFLAGS4 = $(CPPFLAGS3) %%BSD%% %%APPLE%% 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) +CPPFLAGS9 = $(CPPFLAGS8) -DBC_ENABLE_MEMCHECK=$(BC_ENABLE_MEMCHECK) -DBC_ENABLE_AFL=$(BC_ENABLE_AFL) +CPPFLAGS = $(CPPFLAGS9) -DBC_ENABLE_OSSFUZZ=$(BC_ENABLE_OSSFUZZ) CFLAGS = $(CPPFLAGS) $(BC_DEFS) $(DC_DEFS) %%CPPFLAGS%% %%CFLAGS%% LDFLAGS = %%LDFLAGS%% @@ -212,29 +240,32 @@ all: %%DEFAULT_TARGET%% %%SECOND_TARGET%%: %%SECOND_TARGET_PREREQS%% %%SECOND_TARGET_CMD%% -$(GEN_EXEC): +$(GEN_DIR): + mkdir -p $(GEN_DIR) + +$(GEN_EXEC): $(GEN_DIR) %%GEN_EXEC_TARGET%% $(BC_LIB_C): $(GEN_EXEC) $(BC_LIB) - $(GEN_EMU) $(GEN_EXEC) $(BC_LIB) $(BC_LIB_C) $(BC_LIB_C_ARGS) + $(GEN_EMU) $(GEN_EXEC) $(BC_LIB) $(BC_LIB_C) $(BC_EXCLUDE_EXTRA_MATH) $(BC_LIB_C_ARGS) "" "" 1 $(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) + $(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_EXCLUDE_EXTRA_MATH) $(BC_LIB2_C_ARGS) "" "" 1 $(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) + $(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) $(BC_EXCLUDE_EXTRA_MATH) bc_help "" $(BC_ENABLED_NAME) 0 $(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) + $(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) $(BC_EXCLUDE_EXTRA_MATH) dc_help "" $(DC_ENABLED_NAME) 0 $(DC_HELP_O): $(DC_HELP_C) $(CC) $(CFLAGS) -o $@ -c $< @@ -242,13 +273,18 @@ $(DC_HELP_O): $(DC_HELP_C) $(BIN): $(MKDIR) -p $(BIN) +src: + $(MKDIR) -p src + headers: %%HEADERS%% $(MINISTAT): - $(HOSTCC) $(HOSTCFLAGS) -lm -o $(MINISTAT_EXEC) scripts/ministat.c + mkdir -p $(SCRIPTS) + $(HOSTCC) $(HOSTCFLAGS) -lm -o $(MINISTAT_EXEC) $(ROOTDIR)/scripts/ministat.c $(BITFUNCGEN): - $(HOSTCC) $(HOSTCFLAGS) -lm -o $(BITFUNCGEN_EXEC) scripts/bitfuncgen.c + mkdir -p $(SCRIPTS) + $(HOSTCC) $(HOSTCFLAGS) -lm -o $(BITFUNCGEN_EXEC) $(ROOTDIR)/scripts/bitfuncgen.c help: @printf 'available targets:\n' @@ -274,11 +310,6 @@ help: @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 @@ -314,18 +345,18 @@ test_bc_tests:%%BC_TESTS%% test_bc_scripts:%%BC_SCRIPT_TESTS%% test_bc_stdin: - @sh tests/stdin.sh bc %%BC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/stdin.sh bc %%BC_TEST_EXEC%% test_bc_read: - @sh tests/read.sh bc %%BC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/read.sh bc %%BC_TEST_EXEC%% test_bc_errors: test_bc_error_lines%%BC_ERROR_TESTS%% test_bc_error_lines: - @sh tests/errors.sh bc %%BC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/errors.sh bc %%BC_TEST_EXEC%% test_bc_other: - @sh tests/other.sh bc $(BC_ENABLE_EXTRA_MATH) %%BC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/other.sh bc $(BC_ENABLE_EXTRA_MATH) %%BC_TEST_EXEC%% test_bc_header: @printf '$(TEST_STARS)\n\nRunning bc tests...\n\n' @@ -338,18 +369,18 @@ test_dc_tests:%%DC_TESTS%% test_dc_scripts:%%DC_SCRIPT_TESTS%% test_dc_stdin: - @sh tests/stdin.sh dc %%DC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/stdin.sh dc %%DC_TEST_EXEC%% test_dc_read: - @sh tests/read.sh dc %%DC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/read.sh dc %%DC_TEST_EXEC%% test_dc_errors: test_dc_error_lines%%DC_ERROR_TESTS%% test_dc_error_lines: - @sh tests/errors.sh dc %%DC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/errors.sh dc %%DC_TEST_EXEC%% test_dc_other: - @sh tests/other.sh dc $(BC_ENABLE_EXTRA_MATH) %%DC_TEST_EXEC%% + @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/other.sh dc $(BC_ENABLE_EXTRA_MATH) %%DC_TEST_EXEC%% test_dc_header: @printf '$(TEST_STARS)\n\nRunning dc tests...\n\n' @@ -368,116 +399,119 @@ test_bc_history_skip: @printf 'No bc history tests to run\n' test_bc_history0: - @sh tests/history.sh bc 0 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 0 %%BC_TEST_EXEC%% test_bc_history1: - @sh tests/history.sh bc 1 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 1 %%BC_TEST_EXEC%% test_bc_history2: - @sh tests/history.sh bc 2 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 2 %%BC_TEST_EXEC%% test_bc_history3: - @sh tests/history.sh bc 3 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 3 %%BC_TEST_EXEC%% test_bc_history4: - @sh tests/history.sh bc 4 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 4 %%BC_TEST_EXEC%% test_bc_history5: - @sh tests/history.sh bc 5 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 5 %%BC_TEST_EXEC%% test_bc_history6: - @sh tests/history.sh bc 6 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 6 %%BC_TEST_EXEC%% test_bc_history7: - @sh tests/history.sh bc 7 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 7 %%BC_TEST_EXEC%% test_bc_history8: - @sh tests/history.sh bc 8 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 8 %%BC_TEST_EXEC%% test_bc_history9: - @sh tests/history.sh bc 9 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 9 %%BC_TEST_EXEC%% test_bc_history10: - @sh tests/history.sh bc 10 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 10 %%BC_TEST_EXEC%% test_bc_history11: - @sh tests/history.sh bc 11 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 11 %%BC_TEST_EXEC%% test_bc_history12: - @sh tests/history.sh bc 12 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 12 %%BC_TEST_EXEC%% test_bc_history13: - @sh tests/history.sh bc 13 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 13 %%BC_TEST_EXEC%% test_bc_history14: - @sh tests/history.sh bc 14 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 14 %%BC_TEST_EXEC%% test_bc_history15: - @sh tests/history.sh bc 15 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 15 %%BC_TEST_EXEC%% test_bc_history16: - @sh tests/history.sh bc 16 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 16 %%BC_TEST_EXEC%% test_bc_history17: - @sh tests/history.sh bc 17 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 17 %%BC_TEST_EXEC%% test_bc_history18: - @sh tests/history.sh bc 18 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 18 %%BC_TEST_EXEC%% test_bc_history19: - @sh tests/history.sh bc 19 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 19 %%BC_TEST_EXEC%% test_bc_history20: - @sh tests/history.sh bc 20 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh bc 20 %%BC_TEST_EXEC%% test_bc_history21: - @sh tests/history.sh bc 21 %%BC_TEST_EXEC%% + @sh $(TESTSDIR)/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_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_history10 test_dc_history_skip: @printf 'No dc history tests to run\n' test_dc_history0: - @sh tests/history.sh dc 0 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 0 %%DC_TEST_EXEC%% test_dc_history1: - @sh tests/history.sh dc 1 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 1 %%DC_TEST_EXEC%% test_dc_history2: - @sh tests/history.sh dc 2 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 2 %%DC_TEST_EXEC%% test_dc_history3: - @sh tests/history.sh dc 3 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 3 %%DC_TEST_EXEC%% test_dc_history4: - @sh tests/history.sh dc 4 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 4 %%DC_TEST_EXEC%% test_dc_history5: - @sh tests/history.sh dc 5 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 5 %%DC_TEST_EXEC%% test_dc_history6: - @sh tests/history.sh dc 6 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 6 %%DC_TEST_EXEC%% test_dc_history7: - @sh tests/history.sh dc 7 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 7 %%DC_TEST_EXEC%% test_dc_history8: - @sh tests/history.sh dc 8 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 8 %%DC_TEST_EXEC%% test_dc_history9: - @sh tests/history.sh dc 9 %%DC_TEST_EXEC%% + @sh $(TESTSDIR)/history.sh dc 9 %%DC_TEST_EXEC%% + +test_dc_history10: + @sh $(TESTSDIR)/history.sh dc 10 %%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) + $(CC) $(CFLAGS) -lpthread $(BCL_TEST_C) $(LIBBC) -o $(BCL_TEST) test_library: library_test - $(BCL_TEST) + %%BCL_TEST_EXEC%% karatsuba: %%KARATSUBA%% @@ -505,29 +539,30 @@ clean:%%CLEAN_PREREQS%% @$(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/ + @$(RM) -fr vs/bin/ vs/lib/ clean_benchmarks: @printf 'Cleaning benchmarks...\n' @$(RM) -f $(MINISTAT_EXEC) - @$(RM) -f benchmarks/bc/*.txt - @$(RM) -f benchmarks/dc/*.txt + @$(RM) -f $(ROOTDIR)/benchmarks/bc/*.txt + @$(RM) -f $(ROOTDIR)/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) + @$(RM) -f compile_commands.json + @$(RM) -f $(BCL_PC) clean_coverage: @printf 'Cleaning coverage files...\n' @$(RM) -f *.gcov - @$(RM) -f *.html + @$(RM) -f *.html *.css @$(RM) -f *.gcda *.gcno @$(RM) -f *.profraw @$(RM) -f $(GCDA) $(GCNO) @@ -544,19 +579,19 @@ 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 $(TESTSDIR)/bc/parse.txt $(TESTSDIR)/bc/parse_results.txt + @$(RM) -f $(TESTSDIR)/bc/print.txt $(TESTSDIR)/bc/print_results.txt + @$(RM) -f $(TESTSDIR)/bc/bessel.txt $(TESTSDIR)/bc/bessel_results.txt + @$(RM) -f $(TESTSDIR)/bc/strings2.txt $(TESTSDIR)/bc/strings2_results.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/bessel.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/parse.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/print.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/add.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/divide.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/multiply.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/subtract.txt + @$(RM) -f $(TESTSDIR)/bc/scripts/strings2.txt + @$(RM) -f $(TESTSDIR)/dc/scripts/prime.txt @$(RM) -f .log_*.txt @$(RM) -f .math.txt .results.txt .ops.txt @$(RM) -f .test.txt @@ -581,10 +616,11 @@ install_bcl_header: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_HEADER) $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME) install_execs: - $(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)" + $(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)" "$(BUILDDIR)/bin" -install_library: +install_library: install_bcl_header $(SAFE_INSTALL) $(BINARY_INSTALL_ARGS) $(LIBBC) $(DESTDIR)$(LIBDIR)/$(LIB_NAME) + %%PKG_CONFIG_INSTALL%% install:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_MAN_PREREQS%%%%INSTALL_PREREQS%% @@ -603,8 +639,9 @@ uninstall_dc_manpage: uninstall_dc: $(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX) -uninstall_library: +uninstall_library: uninstall_bcl_header $(RM) -f $(DESTDIR)$(LIBDIR)/$(LIB_NAME) + %%PKG_CONFIG_UNINSTALL%% uninstall_bcl_header: $(RM) -f $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME) diff --git a/contrib/bc/NEWS.md b/contrib/bc/NEWS.md index 5251096d9f2..dc2425a532a 100644 --- a/contrib/bc/NEWS.md +++ b/contrib/bc/NEWS.md @@ -1,5 +1,390 @@ # News +## 7.0.3 + +This is a production release that fixes build warnings on the musl libc. + +Other users do ***NOT*** need to upgrade. + +## 7.0.2 + +This is a production release that fixes `Ctrl+d` on FreeBSD and Linux when using +`editline`. + +This bug was caused by the macOS fix in `7.0.0`. Unfortunately, this means that +macOS does not respond properly to `Ctrl+d`. + +## 7.0.1 + +This is a production release that fixes a warning using GCC on FreeBSD. + +Other users do ***NOT*** need to upgrade. + +## 7.0.0 + +This is a production release to fix three bugs. + +The first bug is that `bc`/`dc` will exit on macOS when the terminal is resized. + +The second bug is that an array, which should only be a function parameter, was +accepted as part of larger expressions. + +The third bug is that value stack for `dc` was cleared on any error. However, +this is not how other `dc` behave. To bring `dc` more in line with other +implementations, this behavior was changed. This change is why this version is a +new major version. + +## 6.7.6 + +This is a production release to fix one bug. + +The bug was that `bc` attempted to jump out when flushing `stdout` on exit, but +there is no jump buf at that point. + +## 6.7.5 + +This is a production release to fix one small bug. + +The bug is that sometimes numbers are printed to incorrect line lengths. The +number is always correct; the line is just longer than the limit. + +Users who do not care do not need to update. + +## 6.7.4 + +This is a production release to fix problems in the `bc` manual. + +Users only need to update if desired. + +## 6.7.3 + +This is a production release to fix the library build on Mac OSX. + +Users on other platforms do *not* need to update. + +## 6.7.2 + +This is a production release to remove some debugging code that I accidentally +committed. + +## 6.7.1 + +This is a production release with a bug fix for `SIGINT` only being handled +once. + +## 6.7.0 + +This is a production release with three new functions in the [extended math +library][16]: `min()`, `max()`, and `i2rand()`. + +## 6.6.1 + +This is a production release with an improved `p()` function in the [extended +math library][16]. + +Users who don't care do not need to upgrade. + +## 6.6.0 + +This is a production release with two bug fixes and one change. + +The first bug fix is to fix the build on Mac OSX. + +The second bug was to remove printing a leading zero in scientific or +engineering output modes. + +The change was that the implementation of `irand()` was improved to call the +PRNG less. + +## 6.5.0 + +This is a production release that fixes an infinite loop bug in `root()` and +`cbrt()`, fixes a bug with `BC_LINE_LENGTH=0`, and adds the `fib()` function to +the extended math library to calculate Fibonacci numbers. + +## 6.4.0 + +This is a production release that fixes a `read()`/`?` bug and adds features to +`bcl`. + +The bug was that multiple read calls could repeat old data. + +The new features in `bcl` are functions to preserve `BclNumber` arguments and +not free them. + +***WARNING for `bcl` Users***: The `bcl_rand_seedWithNum()` function used to not +consume its arguments. Now it does. This change could have made this version +`7.0.0`, but I'm 99.9% confident that there are no `bcl` users, or if there are, +they probably don't use the PRNG. So I took a risk and didn't update the major +version. + +`bcl` now includes more capacity to check for invalid numbers when built to run +under Valgrind. + +## 6.3.1 + +This is a production release that fixes a `bc` dependency loop for minimal +environments and Linux from Scratch. + +## 6.3.0 + +This is a production release with a couple of fixes for manuals and a new +feature for `dc`: there is now a command to query whether extended registers are +enabled or not. + +Users who don't care do not need to upgrade. + +## 6.2.6 + +This is a production release that fixes an install bug that affected locale +installation of all locales when using `mksh`. Users do ***NOT*** need to +upgrade if they don't use `mksh` and/or don't need to install all locales. + +## 6.2.5 + +This is a production release that fixes a test bug that affected Android and +`mksh`. Users do ***NOT*** need to upgrade unless they use `mksh` or another +affected shell and need to run the test suite. + +## 6.2.4 + +This is a production release that fixes a test failure that happens when +`tests/bc/scripts/timeconst.bc` doesn't exist. This should only affect +packagers. + +This bug happened because I forgot something I added in the previous release: +better error checking in tests to help packagers. Unfortunately, I was too +zealous with the error checking. + +## 6.2.3 + +This is a production release that moves `bc` to . + +That's all it does: update links. Users do ***NOT*** need to upgrade; there are +redirects that will stay in place indefinitely. This release is only for new +users. + +## 6.2.2 + +This is a production release that fixes a bug. + +The bug was that if an array element was used as a parameter, and then a later +parameter had the same name as the array whose element was used, `bc` would grab +the element from the new array parameter, not the actual element from before the +function call. + +## 6.2.1 + +This is a production release with one bug fix for a memory bug in history. + +## 6.2.0 + +This is a production release with a new feature and a few bug fixes. + +The bug fixes include: + +* A crash when `bc` and `dc` are built using editline, but history is not + activated. +* A missing local in the `uint*()` family of functions in the extended math + library. +* A failure to clear the tail call list in `dc` on error. +* A crash when attempting to swap characters in command-line history when no + characters exist. +* `SIGWINCH` was activated even when history was not. + +The new feature is that stack traces are now given for runtime errors. In debug +mode, the C source file and line of errors are given as well. + +## 6.1.1 + +This is a production release that fixes a build issue with predefined builds and +generated tests. + +## 6.1.0 + +This is a production release that fixes a discrepancy from the `bc` standard, +a couple of memory bugs, and adds new features. + +The discrepancy from the `bc` standard was with regards to the behavior of the +`quit` command. This `bc` used to quit whenever it encountered `quit` during +parsing, even if it was parsing a full file. Now, `bc` only quits when +encountering `quit` *after* it has executed all executable statements up to that +point. + +This behavior is slightly different from GNU `bc`, but users will only notice +the difference if they put `quit` on the same line as other statements. + +The first memory bug could be reproduced by assigning a string to a non-local +variable in a function, then redefining the function with use of the same +non-local variable, which would still refer to a string in the previous version +of the function. + +The second memory bug was caused by passing an array argument to the `asciify()` +built-in function. In certain cases, that was wrongly allowed, and the +interpreter just assumed everything was correct and accessed memory. Now that +arrays are allowed as arguments (see below), this is not an issue. + +The first feature was the addition of the `is_number()` built-in function (`u` +in `dc`) that returns 1 if the runtime argument is a number and 0 otherwise. + +The second feature was the addition of the `is_string()` built-in function (`t` +in `dc`) that returns 1 if the runtime argument is a string and 0 otherwise. + +These features were added because I realized that type-checking is necessary now +that strings can be assigned to variables in `bc` and because they've always +been assignable to variables in `dc`. + +The last added feature is the ability of the `asciify()` built-in function in +`bc` to convert a full array of numbers into a string. This means that +character-by-character printing will not be necessary, and more strings than +just single-character ones will be able to be created. + +## 6.0.4 + +This is a production release that most users will not need to upgrade to. + +This fixes a build bug for `bcl` only on OpenBSD. Users that do not need `bcl` +or have not run into build errors with `bcl` do ***NOT*** need to upgrade. + +## 6.0.3 + +This is a production release that fixes a build bug for cross-compilation. + +Users that do not need cross-compilation do ***NOT*** need to upgrade. + +## 6.0.2 + +This is a production release that fixes two bugs: + +* The `-l` option overrode the `-S` option. +* A double-free and crash when sending a `SIGINT` while executing expressions + given on the command-line. + +## 6.0.1 + +This is a production release that fixes memory bugs and memory leaks in `bcl`. + +Users that do not use `bcl` (use only `bc` and/or `dc`) do ***NOT*** need to +upgrade. + +These happened because I was unaware that the `bcl` test was not hooked into the +Valgrind test infrastructure. Then, when I ran the release script, which tests +everything under Valgrind (or so I thought), it caught nothing, and I thought it +was safe. + +But it was not. + +Nevertheless, I have now run it under Valgrind and fixed all of the memory bugs +(caused by not using `memset()` where I should have but previously didn't have +to) and memory leaks. + +## 6.0.0 + +This is a production release that fixes an oversight in the `bc` parser (that +sometimes caused the wrong error message) and adds a feature for compatibility +with the BSD `bc` and `dc`: turning off digit clamping when parsing numbers. + +The default for clamping can be set during the build (see the [build +manual][13]), it can be set with the `BC_DIGIT_CLAMP` and `DC_DIGIT_CLAMP` +environment variables, and it can be set with the `-c` and `-C` command-line +options. + +Turning off clamping was also added to the `bcl` library. + +In addition, signal handling was removed from the `bcl` library in order to add +the capability for multi-threading. This required a major version bump. I +apologize to all library users (I don't know of any), but signals and threads do +not play well together. + +To help with building, a convenience option (`-p`) to `configure.sh` was added +to build a `bc` and `dc` that is by default compatible with either the BSD `bc` +and `dc` or the GNU `bc` and `dc`. + +## 5.3.3 + +This is a production release that fixes a build problem in the FreeBSD base +system. + +All other users do **NOT** need to upgrade. + +## 5.3.2 + +This is a production release that fixes prompt bugs with editline and readline +where the `BC_PROMPT` environment variable was not being respected. + +This also fixes editline and readline output on `EOF`. + +## 5.3.1 + +This is a production release that fixes a build problem in the FreeBSD base +system, as well as a problem in the `en_US` locale. If you don't have problems +with either, you do not need to upgrade. + +## 5.3.0 + +This is a production release that adds features and has a few bug fixes. + +First, support for editline and readline history has been added. To use +editline, pass `-e` to `configure.sh`, and to use readline, pass `-r`. + +Second, history support for Windows has been fixed and re-enabled. + +Third, command-line options to set `scale`, `ibase`, `obase`, and `seed` were +added. This was requested long ago, and I originally disagreed with the idea. + +Fourth, the manuals had typos and were missing information. That has been fixed. + +Fifth, the manuals received different formatting to be more readable as +manpages. + +## 5.2.5 + +This is a production release that fixes this `bc`'s behavior on `^D` to match +GNU `bc`. + +## 5.2.4 + +This is a production release that fixes two bugs in history: + +* Without prompt, the cursor could not be placed on the first character in a + line. +* Home and End key handling in `tmux` was fixed. + +Any users that do not care about these improvements do not need to upgrade. + +## 5.2.3 + +This is a production release that fixes one bug, a parse error when passing a +file to `bc` using `-f` if that file had a multiline comment or string in it. + +## 5.2.2 + +This is a production release that fixes one bug, a segmentation fault if +`argv[0]` equals `NULL`. + +This is not a critical bug; there will be no vulnerability as far as I can tell. +There is no need to update if you do not wish to. + +## 5.2.1 + +This is a production release that fixes two parse bugs when in POSIX standard +mode. One of these bugs was due to a quirk of the POSIX grammar, and the other +was because `bc` was too strict. + +## 5.2.0 + +This is a production release that adds a new feature, fixes some bugs, and adds +out-of-source builds and a `pkg-config` file for `bcl`. + +The new feature is the ability to turn off exiting on expressions. It is also +possible to set the default using `configure.sh`. This behavior used to exist +with the `BC_EXPR_EXIT` environment variable, which is now used again. + +Bugs fixed include: + +* Some possible race conditions with error handling. +* Install and uninstall targets for `bcl` did not work. + ## 5.1.1 This is a production release that completes a bug fix from `5.1.0`. The bug @@ -450,7 +835,7 @@ 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 +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. diff --git a/contrib/bc/NOTICE.md b/contrib/bc/NOTICE.md index 56d2935ab4b..35536b2c27d 100644 --- a/contrib/bc/NOTICE.md +++ b/contrib/bc/NOTICE.md @@ -1,6 +1,6 @@ # Notice -Copyright 2018-2021 Gavin D. Howard and contributors. +Copyright 2018-2024 Gavin D. Howard and contributors. ## Contributors diff --git a/contrib/bc/README.md b/contrib/bc/README.md index c46d66b7e3e..3b17577945f 100644 --- a/contrib/bc/README.md +++ b/contrib/bc/README.md @@ -1,7 +1,12 @@ # `bc` -***WARNING: This project has moved to [https://git.yzena.com/][20] for [these -reasons][21], though GitHub will remain a mirror.*** +***WARNING: New user registration for is disabled +because of spam. If you need to report a bug with `bc`, email gavin at this site +minus the `git.` part for an account, and I will create one for you. Or you can +report an issue at [GitHub][29].*** + +***WARNING: This project has moved to [https://git.gavinhoward.com/][20] for +[these reasons][21], though GitHub will remain a mirror.*** This is an implementation of the [POSIX `bc` calculator][12] that implements [GNU `bc`][1] extensions, as well as the period (`.`) extension for the BSD @@ -43,7 +48,7 @@ POSIX-compatible systems that are known to work: * FreeBSD * OpenBSD * NetBSD -* Mac OSX +* macOS * Solaris* (as long as the Solaris version supports POSIX 2008) * AIX * HP-UX* (except for history) @@ -58,8 +63,8 @@ system. This `bc` should build unmodified on any POSIX-compliant system or on Windows starting with Windows 10 (though earlier versions may work). -For more complex build requirements than the ones below, see the -[build manual][5]. +For more complex build requirements than the ones below, see the [build +manual][5]. ### Windows @@ -71,43 +76,50 @@ Also, if building with MSBuild, the MSBuild bundled with Visual Studio is required. **Note**: Unlike the POSIX-compatible platforms, only one build configuration is -supported on Windows: extra math and prompt enabled, history and NLS (locale -support) disabled, with both calculators built. +supported on Windows: extra math and history enabled, NLS (locale support) +disabled, with both calculators built. #### `bc` -To build `bc`, you can open the `bc.sln` file in Visual Studio, select the +To build `bc`, you can open the `vs/bc.sln` file in Visual Studio, select the configuration, and build. You can also build using MSBuild with the following from the root directory: ``` -msbuild -property:Configuration= bc.sln +msbuild -property:Configuration= vs/bc.sln ``` where `` is either one of `Debug` or `Release`. +On Windows, the calculators are built as `vs/bin///bc.exe` and +`vs/bin///dc.exe`, where `` can be either `Win32` or +`x64`, and `` can be `Debug` or `Release`. + +**Note**: On Windows, `dc.exe` is just copied from `bc.exe`; it is not linked. +Patches are welcome for a way to do that. + #### `bcl` (Library) -To build the library, you can open the `bcl.sln` file in Visual Studio, select -the configuration, and build. +To build the library, you can open the `vs/bcl.sln` file in Visual Studio, +select the configuration, and build. You can also build using MSBuild with the following from the root directory: ``` -msbuild -property:Configuration= bcl.sln +msbuild -property:Configuration= vs/bcl.sln ``` -where `` is either one of `Debug` or `Release`. +where `` is either one of `Debug`, `ReleaseMD`, or `ReleaseMT`. + +On Windows, the library is built as `vs/lib///bcl.lib`, where +`` can be either `Win32` or `x64`, and `` can be `Debug`, +`ReleaseMD`, or `ReleaseMT`. ### POSIX-Compatible Systems On POSIX-compatible systems, `bc` is built as `bin/bc` and `dc` is built as -`bin/dc` by default. On Windows, they are built as `Release/bc/bc.exe` and -`Release/bc/dc.exe`. - -**Note**: On Windows, `dc.exe` is just copied from `bc.exe`; it is not linked. -Patches are welcome for a way to do that. +`bin/dc` by default. #### Default @@ -159,8 +171,8 @@ other locations, use the `PREFIX` environment variable when running #### Library -This `bc` does provide a way to build a math library with C bindings. This is -done by the `-a` or `--library` options to `configure.sh`: +To build the math library, pass the `-a` or `--library` options to +`configure.sh`: ``` ./configure.sh -a @@ -172,11 +184,26 @@ see the [build manual][5]. The library API can be found in [`manuals/bcl.3.md`][26] or `man bcl` once the library is installed. -The library is built as `bin/libbcl.a` on POSIX-compatible systems or as -`Release/bcl/bcl.lib` on Windows. - #### Package and Distro Maintainers +This section is for package and distro maintainers. + +##### Out-of-Source Builds + +Out-of-source builds are supported; just call `configure.sh` from the directory +where the actual build will happen. + +For example, if the source is in `bc`, the build should happen in `build`, then +call `configure.sh` and `make` like so: + +``` +../bc/configure.sh +make +``` + +***WARNING***: The path to `configure.sh` from the build directory must not have +spaces because `make` does not support target names with spaces. + ##### Recommended Compiler When I ran benchmarks with my `bc` compiled under `clang`, it performed much @@ -264,8 +291,7 @@ with POSIX `bc`. The math has been tested with 40+ million random problems, so it is as correct as I can make it. This `bc` can be used as a drop-in replacement for any existing `bc`. This `bc` -is also compatible with MinGW toolchains, though history is not supported on -Windows. +is also compatible with MinGW toolchains. In addition, this `bc` is considered complete; i.e., there will be no more releases with additional features. However, it *is* actively maintained, so if @@ -292,7 +318,8 @@ may prove useful to any serious users. This `bc` compares favorably to GNU `bc`. * This `bc` builds natively on Windows. -* It has more extensions, which make this `bc` more useful for scripting. +* It has more extensions, which make this `bc` more useful for scripting. (See + [Extensions](#extensions).) * This `bc` is a bit more POSIX compliant. * It has a much less buggy parser. The GNU `bc` will give parse errors for what is actually valid `bc` code, or should be. For example, putting an `else` on @@ -315,6 +342,60 @@ There is one instance where this `bc` is slower: if scripts are light on math. This is because this `bc`'s intepreter is slightly slower than GNU `bc`, but that is because it is more robust. See the [benchmarks][19]. +### Extensions + +Below is a non-comprehensive list of extensions that this `bc` and `dc` have +that all others do not. + +* **The `!` operator has higher precedence than the `!` operator in other `bc` + implementations.** +* An extended math library. (See [here][30] for more information.) +* A command-line prompt. +* Turning on and off digit clamping. (Digit clamping is about how to treat + "invalid" digits for a particular base. GNU `bc` uses it, and the BSD `bc` + does not. Mine does both.) +* A pseudo-random number generator. This includes the ability to set the seed + and get reproducible streams of random numbers. +* The ability to use stacks for the globals `scale`, `ibase`, and `obase` + instead of needing to restore them in *every* function. +* The ability to *not* use non-standard keywords. For example, `abs` is a + keyword (a built-in function), but if some script actually defines a function + called that, it's possible to tell my `bc` to not treat it as a keyword, which + will make the script parses correctly. +* The ability to turn on and off printing leading zeroes on numbers greater than + `-1` and less than `1`. +* Outputting in scientific and engineering notation. +* Accepting input in scientific and engineering notation. +* Passing strings and arrays to the `length()` built-in function. (In `dc`, the + `Y` command will do this for arrays, and the `Z` command will do this for both + numbers and strings.) +* The `abs()` built-in function. (This is the `b` command in `dc`.) +* The `is_number()` and `is_string()` built-in functions. (These tell whether a + variable is holding a string or a number, for runtime type checking. The + commands are `u` and `t` in `dc`.) +* For `bc` only, the `divmod()` built-in function for computing a quotient and + remainder at the same time. +* For `bc` only, the `asciify()` built-in function for converting an array to a + string. +* The `$` truncation operator. (It's the same in `bc` and `dc`.) +* The `@` "set scale" operator. (It's the same in `bc` and `dc`.) +* The decimal shift operators. (`<<` and `>>` in `bc`, `H` and `h` in `dc`.) +* Built-in functions or commands to get the max of `scale`, `ibase`, and + `obase`. +* The ability to put strings into variables in `bc`. (This always existed in + `dc`.) +* The `'` command in `dc` for the depth of the execution stack. +* The `y` command in `dc` for the depth of register stacks. +* Built-in functions or commands to get the value of certain environment + variables that might affect execution. +* The `stream` keyword to do the same thing as the `P` command in `dc`. +* Defined order of evaluation. +* Defined exit statuses. +* All environment variables other than `POSIXLY_CORRECT`, `BC_ENV_ARGS`, and + `BC_LINE_LENGTH`. +* The ability for users to define their own defaults for various options during + build. (See [here][31] for more information.) + ## Algorithms To see what algorithms this `bc` uses, see the [algorithms manual][7]. @@ -343,13 +424,25 @@ Other projects based on this bc are: * [busybox `bc`][8]. The busybox maintainers have made their own changes, so any bugs in the busybox `bc` should be reported to them. - * [toybox `bc`][9]. The maintainer has also made his own changes, so bugs in the toybox `bc` should be reported there. - * [FreeBSD `bc`][23]. While the `bc` in FreeBSD is kept up-to-date, it is better to [report bugs there][24], as well as [submit patches][25], and the maintainers of the package will contact me if necessary. +* [macOS `bc`][35]. Any bugs in that `bc` should be reported to me, but do + expect bugs because the version is old. +* [Android Open Source `bc`][32]. Any bugs in that `bc` can be reported here. +* [A Fedora package][36]. If this package does not have any patches, you can + report bugs to me. + +This is a non-comprehensive list of Linux distros that use this `bc` as the +system `bc`: + +* [Gentoo][33]; it is a first-class alternative to GNU `bc`, but not exclusive. +* [Linux from Scratch][34]. + +Other Linux distros package it as a second-class alternative, usually as `bc-gh` +or `howard-bc`. ## Language @@ -364,6 +457,10 @@ This `bc` uses the commit message guidelines laid out in [this blog post][10]. This `bc` uses [semantic versioning][11]. +## AI-Free + +This repository is 100% AI-Free code. + ## Contents Items labeled with `(maintainer use only)` are not included in release source @@ -373,28 +470,25 @@ Files: .gitignore The git ignore file (maintainer use only). .gitattributes The git attributes file (maintainer use only). - bc.sln The Visual Studio solution file for bc. - bc.vcxproj The Visual Studio project file for bc. - bc.vcxproj.filters The Visual Studio filters file for bc. - bcl.sln The Visual Studio solution file for bcl. - bcl.vcxproj The Visual Studio project file for bcl. - bcl.vcxproj.filters The Visual Studio filters file for bcl. + bcl.pc.in A template pkg-config file for bcl. configure A symlink to configure.sh to make packaging easier. configure.sh The configure script. LICENSE.md A Markdown form of the BSD 2-clause License. Makefile.in The Makefile template. + NEWS.md The changelog. NOTICE.md List of contributors and copyright owners. - RELEASE.md A checklist for making a release (maintainer use only). Folders: - gen The bc math library, help texts, and code to generate C source. - include All header files. - locales Locale files, in .msg format. Patches welcome for translations. - manuals Manuals for both programs. - src All source code. - scripts A bunch of shell scripts to help with development and building. - tests All tests. + benchmarks A folder of benchmarks for various aspects of bc performance. + gen The bc math library, help texts, and code to generate C source. + include All header files. + locales Locale files, in .msg format. Patches welcome for translations. + manuals Manuals for both programs. + src All source code. + scripts A bunch of shell scripts to help with development and building. + tests All tests. + vs Files needed for the build on Windows. [1]: https://www.gnu.org/software/bc/ [4]: ./LICENSE.md @@ -405,10 +499,10 @@ Folders: [10]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html [11]: http://semver.org/ [12]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html -[17]: https://git.yzena.com/gavin/vim-bc -[18]: https://git.yzena.com/gavin/bc_libs +[17]: https://git.gavinhoward.com/gavin/vim-bc +[18]: https://git.gavinhoward.com/gavin/bc_libs [19]: ./manuals/benchmarks.md -[20]: https://git.yzena.com/gavin/bc +[20]: https://git.gavinhoward.com/gavin/bc [21]: https://gavinhoward.com/2020/04/i-am-moving-away-from-github/ [22]: https://www.deepl.com/translator [23]: https://cgit.freebsd.org/src/tree/contrib/bc @@ -417,3 +511,11 @@ Folders: [26]: ./manuals/bcl.3.md [27]: https://en.wikipedia.org/wiki/Bus_factor [28]: ./manuals/development.md +[29]: https://github.com/gavinhoward/bc +[30]: ./manuals/bc/A.1.md#extended-library +[31]: ./manuals/build.md#settings +[32]: https://android.googlesource.com/platform/external/bc/ +[33]: https://github.com/gentoo/gentoo/blob/master/app-alternatives/bc/bc-0.ebuild#L8 +[34]: https://www.linuxfromscratch.org/lfs/view/stable/chapter08/bc.html +[35]: https://github.com/apple-oss-distributions/bc/tree/main/bc +[36]: https://copr.fedorainfracloud.org/coprs/tkbcopr/bc-gh/ diff --git a/contrib/bc/bcl.pc.in b/contrib/bc/bcl.pc.in new file mode 100644 index 00000000000..f440eeca950 --- /dev/null +++ b/contrib/bc/bcl.pc.in @@ -0,0 +1,8 @@ +includedir=%%INCLUDEDIR%% +libdir=%%LIBDIR%% + +Name: bcl +Description: Implemention of arbitrary-precision math from the bc calculator. +Version: %%VERSION%% +Cflags: -I${includedir} +Libs: -L${libdir} -lbcl diff --git a/contrib/bc/compile_flags.txt b/contrib/bc/compile_flags.txt new file mode 100644 index 00000000000..3324798013c --- /dev/null +++ b/contrib/bc/compile_flags.txt @@ -0,0 +1,16 @@ +-Weverything +-pedantic +-Wno-unsafe-buffer-usage +-D_POSIX_C_SOURCE=200809L +-D_XOPEN_SOURCE=700 +-D_BSD_SOURCE +-D_GNU_SOURCE +-D_DEFAULT_SOURCE +-Iinclude/ +-DBC_DEBUG=1 +-DBC_ENABLED=1 +-DDC_ENABLED=1 +-DBC_ENABLE_EXTRA_MATH=1 +-DBC_ENABLE_HISTORY=1 +-DBC_ENABLE_NLS=1 +-DBC_ENABLE_OSSFUZZ=0 diff --git a/contrib/bc/configure.sh b/contrib/bc/configure.sh index de133978007..442165d1569 100755 --- a/contrib/bc/configure.sh +++ b/contrib/bc/configure.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -31,19 +31,19 @@ script="$0" scriptdir=$(dirname "$script") script=$(basename "$script") -. "$scriptdir/scripts/functions.sh" +builddir=$(pwd) -cd "$scriptdir" +. "$scriptdir/scripts/functions.sh" # Simply prints the help message and quits based on the argument. -# @param val The value to pass to exit. Must be an integer. +# @param msg The help message to print. usage() { if [ $# -gt 0 ]; then _usage_val=1 - printf "%s\n\n" "$1" + printf '%s\n\n' "$1" else _usage_val=0 @@ -52,15 +52,25 @@ usage() { 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 [-a|-bD|-dB|-c] [-CeEfgGHilmMNPrtTvz] [-O OPT_LEVEL] [-k KARATSUBA_LEN]\\\n' "$script" + printf ' [-s SETTING] [-S SETTING] [-p TYPE]\n' 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 ' [--enable-editline] [--enable-readline] [--enable-internal-history] \\\n' + printf ' [--disable-problematic-tests] [--install-all-locales] \\\n' + printf ' [--opt=OPT_LEVEL] [--karatsuba-len=KARATSUBA_LEN] \\\n' + printf ' [--set-default-on=SETTING] [--set-default-off=SETTING] \\\n' + printf ' [--predefined-build-type=TYPE] \\\n' printf ' [--prefix=PREFIX] [--bindir=BINDIR] [--datarootdir=DATAROOTDIR] \\\n' printf ' [--datadir=DATADIR] [--mandir=MANDIR] [--man1dir=MAN1DIR] \\\n' + printf ' [--man3dir=MAN3DIR]\n' + + if [ "$_usage_val" -ne 0 ]; then + exit "$_usage_val" + fi + printf '\n' printf ' -a, --library\n' printf ' Build the libbcl instead of the programs. This is meant to be used with\n' @@ -85,6 +95,11 @@ usage() { 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, --enable-editline\n' + printf ' Enable the use of libedit/editline. This is meant for those users that\n' + printf ' want vi-like or Emacs-like behavior in history. This option is ignored\n' + printf ' if history is disabled. If the -r or -i options are given with this\n' + printf ' option, the last occurrence of all of the three is used.\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' @@ -93,7 +108,7 @@ usage() { 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 ' are not failing invisibly. (Development only.)\n' 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' @@ -106,8 +121,13 @@ usage() { printf ' Print this help message and exit.\n' printf ' -H, --disable-history\n' printf ' Disable history.\n' + printf ' -i, --enable-internal-history\n' + printf ' Enable the internal history implementation and do not depend on either\n' + printf ' editline or readline. This option is ignored if history is disabled.\n' + printf ' If this option is given along with -e and -r, the last occurrence of\n' + printf ' all of the three is used.\n' printf ' -k KARATSUBA_LEN, --karatsuba-len KARATSUBA_LEN\n' - printf ' Set the karatsuba length to KARATSUBA_LEN (default is 64).\n' + printf ' Set the karatsuba length to KARATSUBA_LEN (default is 32).\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' @@ -119,10 +139,31 @@ usage() { printf ' Disable installing manpages.\n' printf ' -N, --disable-nls\n' printf ' Disable POSIX locale (NLS) support.\n' + printf ' ***WARNING***: Locales ignore the prefix because they *must* be\n' + printf ' installed at a fixed location to work at all. If you do not want that\n' + printf ' to happen, you must disable locales (NLS) completely.\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 ' -p TYPE, --predefined-build-type=TYPE\n' + printf ' Sets a given predefined build type with specific defaults. This is for\n' + printf ' easy setting of predefined builds. For example, to get a build that\n' + printf ' acts like the GNU bc by default, TYPE should be "GNU" (without the\n' + printf ' quotes) This option *must* come before any others that might change the\n' + printf ' build options. Currently supported values for TYPE include: "BSD" (for\n' + printf ' matching the BSD bc and BSD dc), "GNU" (for matching the GNU bc and\n' + printf ' dc), "GDH" (for the preferred build of the author, Gavin D. Howard),\n' + printf ' and "DBG" (for the preferred debug build of the author). This will\n' + printf ' also automatically enable a release build (except for "DBG").\n' + printf ' -P, --disable-problematic-tests\n' + printf ' Disables problematic tests. These tests usually include tests that\n' + printf ' can cause a SIGKILL because of too much memory usage.\n' + printf ' -r, --enable-readline\n' + printf ' Enable the use of libreadline/readline. This is meant for those users\n' + printf ' that want vi-like or Emacs-like behavior in history. This option is\n' + printf ' ignored if history is disabled. If this option is given along with -e\n' + printf ' and -i, the last occurrence of all of the three is used.\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' @@ -140,10 +181,15 @@ usage() { 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 ' -Z, --enable-ossfuzz-mode\n' + printf ' Enable fuzzing mode for OSS-Fuzz. 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 ' ***WARNING***: Locales ignore the prefix because they *must* be\n' + printf ' installed at a fixed location to work at all. If you do not want that to\n' + printf ' happen, you must disable locales (NLS) completely.\n' printf ' --bindir BINDIR\n' printf ' The directory to install binaries in. Overrides "$BINDIR" if it exists.\n' printf ' Default is "$PREFIX/bin".\n' @@ -189,6 +235,9 @@ usage() { 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 ' ***WARNING***: Locales ignore the prefix because they *must* be\n' + printf ' installed at a fixed location to work at all. If you do not\n' + printf ' want that to happen, you must disable locales (NLS) completely.\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' @@ -205,6 +254,9 @@ usage() { 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 ' PC_PATH The location to install pkg-config files to. Must be an\n' + printf ' path or contain one. Default is the first path given by the\n' + printf ' output of `pkg-config --variable=pc_path pkg-config`.\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' @@ -228,11 +280,10 @@ usage() { 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 ' `gen/lib2.bc` is over 4095 characters, the max supported length\n' + printf ' of a string literal in C99, and `gen/strgen.sh` generates a\n' + printf ' string literal instead of an array, as `gen/strgen.c` does. For\n' + printf ' most 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' @@ -290,6 +341,32 @@ usage() { printf '| | for dc should be on | | |\n' printf '| | in tty mode. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' + printf '| bc.expr_exit | Whether to exit bc | 1 | BC_EXPR_EXIT |\n' + printf '| | if an expression or | | |\n' + printf '| | expression file is | | |\n' + printf '| | given with the -e or | | |\n' + printf '| | -f options. | | |\n' + printf '| --------------- | -------------------- | ------------ | -------------------- |\n' + printf '| dc.expr_exit | Whether to exit dc | 1 | DC_EXPR_EXIT |\n' + printf '| | if an expression or | | |\n' + printf '| | expression file is | | |\n' + printf '| | given with the -e or | | |\n' + printf '| | -f options. | | |\n' + printf '| --------------- | -------------------- | ------------ | -------------------- |\n' + printf '| bc.digit_clamp | Whether to have bc | 0 | BC_DIGIT_CLAMP |\n' + printf '| | clamp digits that | | |\n' + printf '| | are greater than or | | |\n' + printf '| | equal to the current | | |\n' + printf '| | ibase when parsing | | |\n' + printf '| | numbers. | | |\n' + printf '| --------------- | -------------------- | ------------ | -------------------- |\n' + printf '| dc.digit_clamp | Whether to have dc | 0 | DC_DIGIT_CLAMP |\n' + printf '| | clamp digits that | | |\n' + printf '| | are greater than or | | |\n' + printf '| | equal to the current | | |\n' + printf '| | ibase when parsing | | |\n' + printf '| | numbers. | | |\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' @@ -374,19 +451,34 @@ replace() { # the arguments are all assumed to be source files that should *not* be built. find_src_files() { + _find_src_files_args="" + 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}" + _find_src_files_args=$(printf '%s\n%s/src/%s\n' "$_find_src_files_args" "$scriptdir" "${_find_src_files_a}") done - else - _find_src_files_args="-print" fi - printf '%s\n' $(find src/ -depth -name "*.c" $_find_src_files_args) + _find_src_files_files=$(find "$scriptdir/src" -depth -name "*.c" -print | LC_ALL=C sort) + + _find_src_files_result="" + + for _find_src_files_f in $_find_src_files_files; do + + # If this is true, the file is part of args, and therefore, unneeded. + if [ "${_find_src_files_args##*$_find_src_files_f}" != "${_find_src_files_args}" ]; then + continue + fi + + _find_src_files_result=$(printf '%s\n%s\n' "$_find_src_files_result" "$_find_src_files_f") + + done + + printf '%s\n' "$_find_src_files_result" } # This function generates a list of files to go into the Makefile. It generates @@ -403,10 +495,6 @@ gen_file_list() { _gen_file_list_contents="$1" shift - p=$(pwd) - - cd "$scriptdir" - if [ "$#" -ge 1 ]; then _gen_file_list_unneeded="$@" else @@ -422,7 +510,14 @@ gen_file_list() { _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_cbases="" + + for _gen_file_list_f in $_gen_file_list_replacement; do + _gen_file_list_b=$(basename "$_gen_file_list_f") + _gen_file_list_cbases="$_gen_file_list_cbases src/$_gen_file_list_b" + done + + _gen_file_list_replacement=$(replace_exts "$_gen_file_list_cbases" "c" "o") _gen_file_list_contents=$(replace "$_gen_file_list_contents" \ "$_gen_file_list_needle_obj" "$_gen_file_list_replacement") @@ -434,8 +529,6 @@ gen_file_list() { _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" } @@ -466,16 +559,16 @@ gen_std_tests() { 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_std_tests_name" "$_gen_std_tests_t" "$_gen_std_tests_name" \ - "$_gen_std_tests_t" >> "$scriptdir/Makefile" + "$_gen_std_tests_t" >> "Makefile" continue fi fi - printf 'test_%s_%s:\n\t@sh tests/test.sh %s %s %s %s %s\n\n' \ - "$_gen_std_tests_name" "$_gen_std_tests_t" "$_gen_std_tests_name" \ + printf 'test_%s_%s:\n\t@export BC_TEST_OUTPUT_DIR="%s/tests"; sh $(TESTSDIR)/test.sh %s %s %s %s %s\n\n' \ + "$_gen_std_tests_name" "$_gen_std_tests_t" "$builddir" "$_gen_std_tests_name" \ "$_gen_std_tests_t" "$generate_tests" "$time_tests" \ - "$*" >> "$scriptdir/Makefile" + "$*" >> "Makefile" done } @@ -502,7 +595,7 @@ gen_std_test_targets() { # This allows `make test_bc_errors` and `make test_dc_errors` to run in # parallel. # -# @param name Which calculator to generate tests for. +# @param name Which calculator to generate tests for. gen_err_tests() { _gen_err_tests_name="$1" @@ -512,9 +605,9 @@ gen_err_tests() { 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" + printf 'test_%s_error_%s:\n\t@export BC_TEST_OUTPUT_DIR="%s/tests"; sh $(TESTSDIR)/error.sh %s %s %s %s\n\n' \ + "$_gen_err_tests_name" "$_gen_err_tests_t" "$builddir" "$_gen_err_tests_name" \ + "$_gen_err_tests_t" "$problematic_tests" "$*" >> "Makefile" done @@ -566,10 +659,10 @@ gen_script_tests() { _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" \ + printf 'test_%s_script_%s:\n\t@export BC_TEST_OUTPUT_DIR="%s/tests"; sh $(TESTSDIR)/script.sh %s %s %s 1 %s %s %s\n\n' \ + "$_gen_script_tests_name" "$_gen_script_tests_b" "$builddir" "$_gen_script_tests_name" \ "$_gen_script_tests_f" "$_gen_script_tests_extra_math" "$_gen_script_tests_generate" \ - "$_gen_script_tests_time" "$*" >> "$scriptdir/Makefile" + "$_gen_script_tests_time" "$*" >> "Makefile" done } @@ -594,11 +687,171 @@ set_default() { 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" ;; + bc.expr_exit) bc_default_expr_exit="$_set_default_on";; + dc.expr_exit) dc_default_expr_exit="$_set_default_on";; + bc.digit_clamp) bc_default_digit_clamp="$_set_default_on";; + dc.digit_clamp) dc_default_digit_clamp="$_set_default_on";; ?) usage "Invalid setting: $_set_default_name" ;; esac } +predefined_build() { + + _predefined_build_type="$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 "$_predefined_build_type" in + + BSD) + bc_only=0 + dc_only=0 + coverage=0 + debug=0 + optimization="3" + hist=1 + hist_impl="editline" + extra_math=1 + generate_tests=$generate_tests + install_manpages=0 + nls=1 + force=0 + strip_bin=1 + all_locales=0 + library=0 + fuzz=0 + ossfuzz=0 + time_tests=0 + vg=0 + memcheck=0 + clean=1 + 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="" + bc_default_expr_exit=1 + dc_default_expr_exit=1 + bc_default_digit_clamp=0 + dc_default_digit_clamp=0;; + + GNU) + bc_only=0 + dc_only=0 + coverage=0 + debug=0 + optimization="3" + hist=1 + hist_impl="internal" + extra_math=1 + generate_tests=$generate_tests + install_manpages=1 + nls=1 + force=0 + strip_bin=1 + all_locales=0 + library=0 + fuzz=0 + ossfuzz=0 + time_tests=0 + vg=0 + memcheck=0 + clean=1 + bc_default_banner=1 + bc_default_sigint_reset=1 + dc_default_sigint_reset=0 + bc_default_tty_mode=1 + dc_default_tty_mode=0 + bc_default_prompt="" + dc_default_prompt="" + bc_default_expr_exit=1 + dc_default_expr_exit=1 + bc_default_digit_clamp=1 + dc_default_digit_clamp=0;; + + GDH) + CFLAGS="-Weverything -Wno-padded -Wno-unsafe-buffer-usage -Wno-poison-system-directories" + CFLAGS="$CFLAGS -Wno-switch-default -Werror -pedantic -std=c11" + bc_only=0 + dc_only=0 + coverage=0 + debug=0 + optimization="3" + hist=1 + hist_impl="internal" + extra_math=1 + generate_tests=1 + install_manpages=1 + nls=0 + force=0 + strip_bin=1 + all_locales=0 + library=0 + fuzz=0 + ossfuzz=0 + time_tests=0 + vg=0 + memcheck=0 + clean=1 + bc_default_banner=1 + bc_default_sigint_reset=1 + dc_default_sigint_reset=1 + bc_default_tty_mode=1 + dc_default_tty_mode=1 + bc_default_prompt="" + dc_default_prompt="" + bc_default_expr_exit=0 + dc_default_expr_exit=0 + bc_default_digit_clamp=1 + dc_default_digit_clamp=1;; + + DBG) + CFLAGS="-Weverything -Wno-padded -Wno-unsafe-buffer-usage -Wno-poison-system-directories" + CFLAGS="$CFLAGS -Wno-switch-default -Werror -pedantic -std=c11" + bc_only=0 + dc_only=0 + coverage=0 + debug=1 + optimization="0" + hist=1 + hist_impl="internal" + extra_math=1 + generate_tests=1 + install_manpages=1 + nls=1 + force=0 + strip_bin=1 + all_locales=0 + library=0 + fuzz=0 + ossfuzz=0 + time_tests=0 + vg=0 + memcheck=1 + clean=1 + bc_default_banner=1 + bc_default_sigint_reset=1 + dc_default_sigint_reset=1 + bc_default_tty_mode=1 + dc_default_tty_mode=1 + bc_default_prompt="" + dc_default_prompt="" + bc_default_expr_exit=0 + dc_default_expr_exit=0 + bc_default_digit_clamp=1 + dc_default_digit_clamp=1;; + + ?|'') usage "Invalid user build: \"$_predefined_build_type\". Accepted types are BSD, GNU, GDH, DBG.";; + + esac +} + # Generates a list of script test targets that will be used as prerequisites for # other targets. # @@ -632,6 +885,7 @@ coverage=0 karatsuba_len=32 debug=0 hist=1 +hist_impl="internal" extra_math=1 optimization="" generate_tests=1 @@ -642,10 +896,12 @@ strip_bin=1 all_locales=0 library=0 fuzz=0 +ossfuzz=0 time_tests=0 vg=0 memcheck=0 clean=1 +problematic_tests=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. @@ -656,11 +912,15 @@ bc_default_tty_mode=1 dc_default_tty_mode=0 bc_default_prompt="" dc_default_prompt="" +bc_default_expr_exit=1 +dc_default_expr_exit=1 +bc_default_digit_clamp=0 +dc_default_digit_clamp=0 # 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 +while getopts "abBcdDeEfgGhHik:lMmNO:p:PrS:s:tTvzZ-" opt; do case "$opt" in a) library=1 ;; @@ -670,24 +930,30 @@ while getopts "abBcdDEfgGhHk:lMmNO:S:s:tTvz-" opt; do C) clean=0 ;; d) dc_only=1 ;; D) bc_only=1 ;; + e) hist_impl="editline" ;; E) extra_math=0 ;; f) force=1 ;; g) debug=1 ;; G) generate_tests=0 ;; h) usage ;; H) hist=0 ;; + i) hist_impl="internal" ;; k) karatsuba_len="$OPTARG" ;; l) all_locales=1 ;; m) memcheck=1 ;; M) install_manpages=0 ;; N) nls=0 ;; O) optimization="$OPTARG" ;; + p) predefined_build "$OPTARG" ;; + P) problematic_tests=0 ;; + r) hist_impl="readline" ;; S) set_default 0 "$OPTARG" ;; s) set_default 1 "$OPTARG" ;; t) time_tests=1 ;; T) strip_bin=0 ;; v) vg=1 ;; z) fuzz=1 ;; + Z) ossfuzz=1 ;; -) arg="$1" arg="${arg#--}" @@ -763,13 +1029,6 @@ while getopts "abBcdDEfgGhHk:lMmNO:S:s:tTvz-" opt; do 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 @@ -798,6 +1057,13 @@ while getopts "abBcdDEfgGhHk:lMmNO:S:s:tTvz-" opt; do fi set_default 0 "$1" shift ;; + predefined-build-type=?*) predefined_build "$LONG_OPTARG" ;; + predefined-build-type) + if [ "$#" -lt 2 ]; then + usage "No argument given for '--$arg' option" + fi + predefined_build "$1" + shift ;; disable-bc) dc_only=1 ;; disable-dc) bc_only=1 ;; disable-clean) clean=0 ;; @@ -807,9 +1073,14 @@ while getopts "abBcdDEfgGhHk:lMmNO:S:s:tTvz-" opt; do disable-man-pages) install_manpages=0 ;; disable-nls) nls=0 ;; disable-strip) strip_bin=0 ;; + disable-problematic-tests) problematic_tests=0 ;; + enable-editline) hist_impl="editline" ;; + enable-readline) hist_impl="readline" ;; + enable-internal-history) hist_impl="internal" ;; enable-test-timing) time_tests=1 ;; enable-valgrind) vg=1 ;; enable-fuzz-mode) fuzz=1 ;; + enable-ossfuzz-mode) ossfuzz=1 ;; enable-memcheck) memcheck=1 ;; install-all-locales) all_locales=1 ;; help* | bc-only* | dc-only* | coverage* | debug*) @@ -822,10 +1093,16 @@ while getopts "abBcdDEfgGhHk:lMmNO:S:s:tTvz-" opt; do usage "No arg allowed for --$arg option" ;; disable-man-pages* | disable-nls* | disable-strip*) usage "No arg allowed for --$arg option" ;; + disable-problematic-tests*) + 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" ;; + enable-editline* | enable-readline*) + usage "No arg allowed for --$arg option" ;; + enable-internal-history*) + usage "No arg allowed for --$arg option" ;; '') break ;; # "--" terminates argument processing * ) usage "Invalid option $LONG_OPTARG" ;; esac @@ -874,7 +1151,7 @@ if [ -z "${LONG_BIT+set}" ]; then elif [ "$LONG_BIT" -lt 32 ]; then usage "LONG_BIT is less than 32" else - LONG_BIT_DEFINE="-DBC_LONG_BIT=\$(BC_LONG_BIT)" + LONG_BIT_DEFINE="-DBC_LONG_BIT=$LONG_BIT" fi if [ -z "$CC" ]; then @@ -946,12 +1223,12 @@ executable="BC_EXEC" 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)" +bc_test="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh bc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(BC_EXEC)" +bc_test_np="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh -n bc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(BC_EXEC)" +dc_test="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh dc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(DC_EXEC)" +dc_test_np="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh -n dc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(DC_EXEC)" -timeconst="@tests/bc/timeconst.sh tests/bc/scripts/timeconst.bc \$(BC_EXEC)" +timeconst="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/bc/timeconst.sh \$(TESTSDIR)/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. @@ -959,9 +1236,11 @@ if [ "$vg" -ne 0 ]; then debug=1 bc_test_exec='valgrind $(VALGRIND_ARGS) $(BC_EXEC)' dc_test_exec='valgrind $(VALGRIND_ARGS) $(DC_EXEC)' + bcl_test_exec='valgrind $(VALGRIND_ARGS) $(BCL_TEST)' else bc_test_exec='$(BC_EXEC)' dc_test_exec='$(DC_EXEC)' + bcl_test_exec='$(BCL_TEST)' fi test_bc_history_prereqs="test_bc_history_all" @@ -999,6 +1278,11 @@ if [ "$library" -ne 0 ]; then test_bc_history_prereqs=" test_bc_history_skip" test_dc_history_prereqs=" test_dc_history_skip" + install_prereqs=" install_library" + uninstall_prereqs=" uninstall_library" + install_man_prereqs=" install_bcl_manpage" + uninstall_man_prereqs=" uninstall_bcl_manpage" + elif [ "$bc_only" -eq 1 ]; then bc=1 @@ -1047,6 +1331,45 @@ elif [ "$dc_only" -eq 1 ]; then tests="test_dc" +elif [ "$ossfuzz" -eq 1 ]; then + + if [ "$bc_only" -ne 0 ] || [ "$dc_only" -ne 0 ]; then + usage "An OSS-Fuzz build must build both fuzzers." + fi + + bc=1 + dc=1 + + # Expressions *cannot* exit in an OSS-Fuzz build. + bc_default_expr_exit=0 + dc_default_expr_exit=0 + + executables="bc_fuzzer and dc_fuzzer" + + 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="src/bc_fuzzer.o $default_target_prereqs" + default_target_prereqs="\$(BC_FUZZER) src/dc_fuzzer.o $default_target_prereqs" + default_target_cmd="\$(CXX) \$(CFLAGS) src/dc_fuzzer.o \$(LIB_FUZZING_ENGINE) \$(OBJS) \$(LDFLAGS) -o \$(DC_FUZZER) \&\& ln -sf ./dc_fuzzer_c \$(DC_FUZZER_C)" + second_target_cmd="\$(CXX) \$(CFLAGS) src/bc_fuzzer.o \$(LIB_FUZZING_ENGINE) \$(OBJS) \$(LDFLAGS) -o \$(BC_FUZZER) \&\& ln -sf ./bc_fuzzer_c \$(BC_FUZZER_C)" + + default_target="\$(DC_FUZZER) \$(DC_FUZZER_C)" + second_target="\$(BC_FUZZER) \$(BC_FUZZER_C)" + else bc=1 @@ -1076,8 +1399,12 @@ else fi +if [ "$fuzz" -ne 0 ] && [ "$ossfuzz" -ne 0 ]; then + usage "Fuzzing mode and OSS-Fuzz mode are mutually exclusive" +fi + # We need specific stuff for fuzzing. -if [ "$fuzz" -ne 0 ]; then +if [ "$fuzz" -ne 0 ] || [ "$ossfuzz" -ne 0 ]; then debug=1 hist=0 nls=0 @@ -1094,12 +1421,7 @@ if [ "$debug" -eq 1 ]; then CFLAGS="-g $CFLAGS" else - CPPFLAGS="-DNDEBUG $CPPFLAGS" - - if [ "$strip_bin" -ne 0 ]; then - LDFLAGS="-s $LDFLAGS" - fi fi # Set optimization CFLAGS. @@ -1127,7 +1449,6 @@ else COVERAGE_PREREQS="" fi - # Set some defaults. if [ -z "${DESTDIR+set}" ]; then destdir="" @@ -1135,8 +1456,12 @@ else destdir="DESTDIR = $DESTDIR" fi +# defprefix is for a warning about locales later. if [ -z "${PREFIX+set}" ]; then PREFIX="/usr/local" + defprefix=1 +else + defprefix=0 fi if [ -z "${BINDIR+set}" ]; then @@ -1151,8 +1476,26 @@ if [ -z "${LIBDIR+set}" ]; then LIBDIR="$PREFIX/lib" fi +if [ -z "${PC_PATH+set}" ]; then + + set +e + + command -v pkg-config > /dev/null + err=$? + + set -e + + if [ "$err" -eq 0 ]; then + PC_PATH=$(pkg-config --variable=pc_path pkg-config) + PC_PATH="${PC_PATH%%:*}" + else + PC_PATH="" + fi + +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 +# installed, or locales are enabled because that's probably where NLSPATH # points. if [ "$install_manpages" -ne 0 ] || [ "$nls" -ne 0 ]; then if [ -z "${DATAROOTDIR+set}" ]; then @@ -1195,17 +1538,23 @@ if [ "$nls" -ne 0 ]; then 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" + flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -DBC_ENABLE_OSSFUZZ=0" + flags="$flags -I$scriptdir/include/ -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" + + ccbase=$(basename "$CC") + + if [ "$ccbase" = "clang" ]; then + flags="$flags -Wno-unreachable-code" + fi - "$CC" $CPPFLAGS $CFLAGS $flags -c "src/vm.c" -o "$scriptdir/vm.o" > /dev/null 2>&1 + "$CC" $CPPFLAGS $CFLAGS $flags -c "$scriptdir/src/vm.c" -E > /dev/null err="$?" - rm -rf "$scriptdir/vm.o" + rm -rf "./vm.o" - # If this errors, it is probably because of building on Windows, - # and NLS is not supported on Windows, so disable it. + # If this errors, it is probably because of building on Windows or musl, + # and NLS is not supported on Windows or musl, so disable it. if [ "$err" -ne 0 ]; then printf 'NLS does not work.\n' if [ $force -eq 0 ]; then @@ -1218,11 +1567,11 @@ if [ "$nls" -ne 0 ]; then printf 'NLS works.\n\n' printf 'Testing gencat...\n' - gencat "$scriptdir/en_US.cat" "$scriptdir/locales/en_US.msg" > /dev/null 2>&1 + gencat "./en_US.cat" "$scriptdir/locales/en_US.msg" > /dev/null err="$?" - rm -rf "$scriptdir/en_US.cat" + rm -rf "./en_US.cat" if [ "$err" -ne 0 ]; then printf 'gencat does not work.\n' @@ -1273,20 +1622,32 @@ fi # Like the above tested locale support, this tests history. if [ "$hist" -eq 1 ]; then + if [ "$hist_impl" = "editline" ]; then + editline=1 + readline=0 + elif [ "$hist_impl" = "readline" ]; then + editline=0 + readline=1 + else + editline=0 + readline=0 + fi + 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" + flags="$flags -DBC_ENABLE_EDITLINE=$editline -DBC_ENABLE_READLINE=$readline" + flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -DBC_ENABLE_OSSFUZZ=0" + flags="$flags -I$scriptdir/include/ -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 + "$CC" $CPPFLAGS $CFLAGS $flags -c "$scriptdir/src/history.c" -E > /dev/null err="$?" - rm -rf "$scriptdir/history.o" + rm -rf "./history.o" # If this errors, it is probably because of building on Windows, # and history is not supported on Windows, so disable it. @@ -1304,15 +1665,86 @@ if [ "$hist" -eq 1 ]; then set -e +else + + editline=0 + readline=0 + fi -# We have to disable the history tests if it is disabled or valgrind is on. +# We have to disable the history tests if it is disabled or valgrind is on. Or +# if we are using editline or readline. 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'" + CFLAGS="$CFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=0" +else + + if [ "$editline" -eq 0 ] && [ "$readline" -eq 0 ]; then + history_tests="@printf '\$(TEST_STARS)\\\\n\\\\nRunning history tests...\\\\n\\\\n'" + history_tests="$history_tests \&\& \$(TESTSDIR)/history.sh bc -a \&\&" + history_tests="$history_tests \$(TESTSDIR)/history.sh dc -a \&\& printf" + history_tests="$history_tests '\\\\nAll history tests passed.\\\\n\\\\n\$(TEST_STARS)\\\\n'" + else + test_bc_history_prereqs=" test_bc_history_skip" + test_dc_history_prereqs=" test_dc_history_skip" + history_tests="@printf 'Skipping history tests...\\\\n'" + fi + + # We are also setting the CFLAGS and LDFLAGS here. + if [ "$editline" -ne 0 ]; then + LDFLAGS="$LDFLAGS -ledit" + CPPFLAGS="$CPPFLAGS -DBC_ENABLE_EDITLINE=1 -DBC_ENABLE_READLINE=0" + elif [ "$readline" -ne 0 ]; then + LDFLAGS="$LDFLAGS -lreadline" + CPPFLAGS="$CPPFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=1" + else + CPPFLAGS="$CPPFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=0" + fi + +fi + +# Test FreeBSD. This is not in an if statement because regardless of whatever +# the user says, we need to know if we are on FreeBSD. If we are, we cannot set +# _POSIX_C_SOURCE and _XOPEN_SOURCE. The FreeBSD headers turn *off* stuff when +# that is done. +set +e +printf 'Testing for FreeBSD...\n' + +flags="-DBC_TEST_FREEBSD -DBC_ENABLE_AFL=0" +"$CC" $CPPFLAGS $CFLAGS $flags "-I$scriptdir/include" -E "$scriptdir/scripts/os.c" > /dev/null + +err="$?" + +if [ "$err" -ne 0 ]; then + printf 'On FreeBSD. Not using _POSIX_C_SOURCE and _XOPEN_SOURCE.\n\n' +else + printf 'Not on FreeBSD. Using _POSIX_C_SOURCE and _XOPEN_SOURCE.\n\n' + CPPFLAGS="$CPPFLAGS -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" +fi + +# Test macOS. This is not in an if statement because regardless of whatever the +# user says, we need to know if we are on macOS. If we are, we have to set +# _DARWIN_C_SOURCE. +printf 'Testing for macOS...\n' + +flags="-DBC_TEST_APPLE -DBC_ENABLE_AFL=0" +"$CC" $CPPFLAGS $CFLAGS $flags "-I$scriptdir/include" -E "$scriptdir/scripts/os.c" > /dev/null + +err="$?" + +if [ "$err" -ne 0 ]; then + printf 'On macOS. Using _DARWIN_C_SOURCE.\n\n' + apple="-D_DARWIN_C_SOURCE" 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'" + printf 'Not on macOS.\n\n' + apple="" +fi + +# We can't use the linker's strip flag on macOS. +if [ "$debug" -eq 0 ] && [ "$apple" = "" ] && [ "$strip_bin" -ne 0 ]; then + LDFLAGS="-s $LDFLAGS" fi # Test OpenBSD. This is not in an if statement because regardless of whatever @@ -1323,22 +1755,30 @@ fi # 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 +"$CC" $CPPFLAGS $CFLAGS $flags "-I$scriptdir/include" -E "$scriptdir/scripts/os.c" > /dev/null err="$?" if [ "$err" -ne 0 ]; then + printf 'On OpenBSD. Using _BSD_SOURCE.\n\n' bsd="-D_BSD_SOURCE" + + # Readline errors on OpenBSD, for some weird reason. + if [ "$readline" -ne 0 ]; then + usage "Cannot use readline on OpenBSD" + fi + else printf 'Not on OpenBSD.\n\n' bsd="" fi +set -e + if [ "$library" -eq 1 ]; then bc_lib="" fi @@ -1349,10 +1789,12 @@ else BC_LIB2_O="" fi +GEN_DIR="$scriptdir/gen" + # 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)" +GEN_EXEC_TARGET="\$(HOSTCC) -DBC_ENABLE_AFL=0 -DBC_ENABLE_OSSFUZZ=0 -I$scriptdir/include/ \$(HOSTCFLAGS) -o \$(GEN_EXEC) \$(GEN_C)" CLEAN_PREREQS=" clean_gen clean_coverage" if [ -z "${GEN_HOST+set}" ]; then @@ -1365,15 +1807,18 @@ else fi fi +# The fuzzer files are always unneeded because they'll be built separately. manpage_args="" -unneeded="" +unneeded="bc_fuzzer.c dc_fuzzer.c" headers="\$(HEADERS)" # This series of if statements figure out what source files are *not* needed. if [ "$extra_math" -eq 0 ]; then + exclude_extra_math=1 manpage_args="E" unneeded="$unneeded rand.c" else + exclude_extra_math=0 headers="$headers \$(EXTRA_MATH_HEADERS)" fi @@ -1403,19 +1848,60 @@ else headers="$headers \$(DC_HEADERS)" fi +# This convoluted mess does pull the version out. If you change the format of +# include/version.h, you may have to change this line. +version=$(cat "$scriptdir/include/version.h" | grep "VERSION " - | awk '{ print $3 }' -) + 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)" + + if [ "$PC_PATH" != "" ]; then + + contents=$(cat "$scriptdir/bcl.pc.in") + + contents=$(replace "$contents" "INCLUDEDIR" "$INCLUDEDIR") + contents=$(replace "$contents" "LIBDIR" "$LIBDIR") + contents=$(replace "$contents" "VERSION" "$version") + + printf '%s\n' "$contents" > "$scriptdir/bcl.pc" + + pkg_config_install="\$(SAFE_INSTALL) \$(PC_INSTALL_ARGS) \"\$(BCL_PC)\" \"\$(DESTDIR)\$(PC_PATH)/\$(BCL_PC)\"" + pkg_config_uninstall="\$(RM) -f \"\$(DESTDIR)\$(PC_PATH)/\$(BCL_PC)\"" + + else + + pkg_config_install="" + pkg_config_uninstall="" + + fi + +elif [ "$ossfuzz" -ne 0 ]; then + + unneeded="$unneeded library.c main.c" + + PC_PATH="" + pkg_config_install="" + pkg_config_uninstall="" + else + unneeded="$unneeded library.c" + + PC_PATH="" + pkg_config_install="" + pkg_config_uninstall="" + fi -# library.c is not needed under normal circumstances. +# library.c, bc_fuzzer.c, and dc_fuzzer.c are not needed under normal +# circumstances. if [ "$unneeded" = "" ]; then - unneeded="library.c" + unneeded="library.c bc_fuzzer.c dc_fuzzer.c" fi # This sets the appropriate manpage for a full build. @@ -1423,7 +1909,7 @@ if [ "$manpage_args" = "" ]; then manpage_args="A" fi -if [ "$vg" -ne 0 ]; then +if [ "$vg" -ne 0 ] || [ "$ossfuzz" -ne 0 ]; then memcheck=1 fi @@ -1443,7 +1929,11 @@ dc_tests=$(gen_std_test_targets dc) dc_script_tests=$(gen_script_test_targets dc) dc_err_tests=$(gen_err_test_targets dc) +printf 'unneeded: %s\n' "$unneeded" + # Print out the values; this is for debugging. +printf 'Version: %s\n' "$version" + if [ "$bc" -ne 0 ]; then printf 'Building bc\n' else @@ -1458,7 +1948,7 @@ 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_NLS=%s\n\n' "$nls" printf 'BC_ENABLE_AFL=%s\n' "$fuzz" printf '\n' printf 'BC_NUM_KARATSUBA_LEN=%s\n' "$karatsuba_len" @@ -1479,6 +1969,7 @@ printf 'MANDIR=%s\n' "$MANDIR" printf 'MAN1DIR=%s\n' "$MAN1DIR" printf 'MAN3DIR=%s\n' "$MAN3DIR" printf 'NLSPATH=%s\n' "$NLSPATH" +printf 'PC_PATH=%s\n' "$PC_PATH" printf 'EXECSUFFIX=%s\n' "$EXECSUFFIX" printf 'EXECPREFIX=%s\n' "$EXECPREFIX" printf 'DESTDIR=%s\n' "$DESTDIR" @@ -1495,6 +1986,32 @@ 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" +printf 'bc.expr_exit=%s\n' "$bc_default_expr_exit" +printf 'dc.expr_exit=%s\n' "$dc_default_expr_exit" +printf 'bc.digit_clamp=%s\n' "$bc_default_digit_clamp" +printf 'dc.digit_clamp=%s\n' "$dc_default_digit_clamp" + +# This code outputs a warning. The warning is to not surprise users when locales +# are installed outside of the prefix. This warning is suppressed when the +# default prefix is used, as well, so as not to panic users just installing by +# hand. I believe this will be okay because NLSPATH is usually in /usr and the +# default prefix is /usr/local, so they'll be close that way. +if [ "$nls" -ne 0 ] && [ "${NLSPATH#$PREFIX}" = "${NLSPATH}" ] && [ "$defprefix" -eq 0 ]; then + printf '\n********************************************************************************\n\n' + printf 'WARNING: Locales will *NOT* be installed in $PREFIX (%s).\n' "$PREFIX" + printf '\n' + printf ' This is because they *MUST* be installed at a fixed location to even\n' + printf ' work, and that fixed location is $NLSPATH (%s).\n' "$NLSPATH" + printf '\n' + printf ' This location is *outside* of $PREFIX. If you do not wish to install\n' + printf ' locales outside of $PREFIX, you must disable NLS with the -N or the\n' + printf ' --disable-nls options.\n' + printf '\n' + printf ' The author apologizes for the inconvenience, but the need to install\n' + printf ' the locales at a fixed location is mandated by POSIX, and it is not\n' + printf ' possible for the author to change that requirement.\n' + printf '\n********************************************************************************\n' +fi # This is where the real work begins. This is the point at which the Makefile.in # template is edited and output to the Makefile. @@ -1518,11 +2035,15 @@ 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' \ + o=$(basename "$o") + SRC_TARGETS=$(printf '%s\n\nsrc/%s: src %s %s\n\t$(CC) $(CFLAGS) -o src/%s -c %s\n' \ "$SRC_TARGETS" "$o" "$headers" "$f" "$o" "$f") done # Replace all the placeholders. +contents=$(replace "$contents" "ROOTDIR" "$scriptdir") +contents=$(replace "$contents" "BUILDDIR" "$builddir") + contents=$(replace "$contents" "HEADERS" "$headers") contents=$(replace "$contents" "BC_ENABLED" "$bc") @@ -1543,14 +2064,19 @@ 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" "BCL_TEST_EXEC" "$bcl_test_exec") + contents=$(replace "$contents" "BUILD_TYPE" "$manpage_args") +contents=$(replace "$contents" "EXCLUDE_EXTRA_MATH" "$exclude_extra_math") 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" "OSSFUZZ" "$ossfuzz") contents=$(replace "$contents" "MEMCHECK" "$memcheck") +contents=$(replace "$contents" "LIB_FUZZING_ENGINE" "$LIB_FUZZING_ENGINE") contents=$(replace "$contents" "BC_LIB_O" "$bc_lib") contents=$(replace "$contents" "BC_HELP_O" "$bc_help") @@ -1583,6 +2109,10 @@ 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" "PC_PATH" "$PC_PATH") +contents=$(replace "$contents" "PKG_CONFIG_INSTALL" "$pkg_config_install") +contents=$(replace "$contents" "PKG_CONFIG_UNINSTALL" "$pkg_config_uninstall") + 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") @@ -1613,15 +2143,16 @@ 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_DIR" "$GEN_DIR") 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" "APPLE" "$apple") contents=$(replace "$contents" "BC_DEFAULT_BANNER" "$bc_default_banner") contents=$(replace "$contents" "BC_DEFAULT_SIGINT_RESET" "$bc_default_sigint_reset") @@ -1630,9 +2161,13 @@ 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") +contents=$(replace "$contents" "BC_DEFAULT_EXPR_EXIT" "$bc_default_expr_exit") +contents=$(replace "$contents" "DC_DEFAULT_EXPR_EXIT" "$dc_default_expr_exit") +contents=$(replace "$contents" "BC_DEFAULT_DIGIT_CLAMP" "$bc_default_digit_clamp") +contents=$(replace "$contents" "DC_DEFAULT_DIGIT_CLAMP" "$dc_default_digit_clamp") # Do the first print to the Makefile. -printf '%s\n%s\n\n' "$contents" "$SRC_TARGETS" > "$scriptdir/Makefile" +printf '%s\n%s\n\n' "$contents" "$SRC_TARGETS" > "Makefile" # Generate the individual test targets. if [ "$bc" -ne 0 ]; then @@ -1647,12 +2182,20 @@ if [ "$dc" -ne 0 ]; then gen_err_tests dc $dc_test_exec fi -cd "$scriptdir" +if [ "$ossfuzz" -ne 0 ]; then + + printf 'bc_fuzzer_c: $(BC_FUZZER)\n\tln -sf $(BC_FUZZER) bc_fuzzer_c\n' >> Makefile + printf 'bc_fuzzer_C: $(BC_FUZZER)\n\tln -sf $(BC_FUZZER) bc_fuzzer_C\n' >> Makefile + printf 'dc_fuzzer_c: $(DC_FUZZER)\n\tln -sf $(DC_FUZZER) dc_fuzzer_c\n' >> Makefile + printf 'dc_fuzzer_C: $(DC_FUZZER)\n\tln -sf $(DC_FUZZER) dc_fuzzer_C\n' >> Makefile + +fi # 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 +mkdir -p manuals +cp -f "$scriptdir/manuals/bc/$manpage_args.1.md" manuals/bc.1.md +cp -f "$scriptdir/manuals/bc/$manpage_args.1" manuals/bc.1 +cp -f "$scriptdir/manuals/dc/$manpage_args.1.md" manuals/dc.1.md +cp -f "$scriptdir/manuals/dc/$manpage_args.1" manuals/dc.1 make clean > /dev/null diff --git a/contrib/bc/gen/bc_help.txt b/contrib/bc/gen/bc_help.txt index 9ba34c60648..489b54a185f 100644 --- a/contrib/bc/gen/bc_help.txt +++ b/contrib/bc/gen/bc_help.txt @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -37,7 +37,7 @@ 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. +https://git.gavinhoward.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 @@ -63,6 +63,37 @@ This bc also implements the dot (.) extension of the BSD bc. Options: + -C --no-digit-clamp + + Disables clamping of digits that are larger than or equal to the current + ibase when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If multiple of this option and the -c option are given, the last is used. + + -c --digit-clamp + + Enables clamping of digits that are larger than or equal to the current + ibase when parsing numbers. + + This means that digits that the value added to a number from a digit that + is greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If multiple of this option and the -C option are given, the last is used. +{{ A H N HN }} + + -E seed --seed=seed + + Sets the builtin variable seed to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. +{{ end }} + -e expr --expression=expr Run "expr" and quit. If multiple expressions or files (see below) are @@ -82,6 +113,12 @@ Options: Print this usage message and exit. + -I ibase --ibase=ibase + + Sets the builtin variable ibase to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. + -i --interactive Force interactive mode. @@ -104,6 +141,12 @@ Options: This bc may load more functions with these options. See the manpage or online documentation for details. + -O obase --obase=obase + + Sets the builtin variable obase to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. + -P --no-prompt Disable the prompts in interactive mode. @@ -127,6 +170,12 @@ Options: Don't print version and copyright. + -S scale --scale=scale + + Sets the builtin variable scale to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. + -s --standard Error if any non-POSIX extensions are used. @@ -163,6 +212,8 @@ Environment variables: If an integer and non-zero, display the copyright banner in interactive mode. + If zero, disable the banner. + Overrides the default, which is %s print the banner. BC_SIGINT_RESET @@ -170,16 +221,36 @@ Environment variables: If an integer and non-zero, reset on SIGINT, rather than exit, when in interactive mode. + If zero, do not reset on SIGINT in all cases, but exit instead. + Overrides the default, which is %s. BC_TTY_MODE If an integer and non-zero, enable TTY mode when it is available. + If zero, disable TTY mode in all cases. + Overrides the default, which is TTY mode %s. BC_PROMPT If an integer and non-zero, enable prompt when TTY mode is possible. + If zero, disable prompt in all cases. + Overrides the default, which is prompt %s. + + BC_EXPR_EXIT + + If an integer and non-zero, exit when expressions or expression files are + given on the command-line, and does not exit when an integer and zero. + + Overrides the default, which is %s. + + BC_DIGIT_CLAMP + + If an integer and non-zero, clamp digits larger than or equal to the + current ibase when parsing numbers. + + Overrides the default, which is %s. diff --git a/contrib/bc/gen/dc_help.txt b/contrib/bc/gen/dc_help.txt index 4cf10826cd7..df4ede1583a 100644 --- a/contrib/bc/gen/dc_help.txt +++ b/contrib/bc/gen/dc_help.txt @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -37,7 +37,7 @@ 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. +at https://git.gavinhoward.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 @@ -72,6 +72,37 @@ This dc has a few differences from the two above: Options: + -C --no-digit-clamp + + Disables clamping of digits that are larger than or equal to the current + ibase when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If multiple of this option and the -c option are given, the last is used. + + -c --digit-clamp + + Enables clamping of digits that are larger than or equal to the current + ibase when parsing numbers. + + This means that digits that the value added to a number from a digit that + is greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If multiple of this option and the -C option are given, the last is used. +{{ A H N HN }} + + -E seed --seed=seed + + Sets the builtin variable seed to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. +{{ end }} + -e expr --expression=expr Run "expr" and quit. If multiple expressions or files (see below) are @@ -85,6 +116,12 @@ Options: Print this usage message and exit. + -I ibase --ibase=ibase + + Sets the builtin variable ibase to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. + -i --interactive Put dc into interactive mode. See the man page for more details. @@ -93,6 +130,12 @@ Options: Disable line length checking. + -O obase --obase=obase + + Sets the builtin variable obase to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. + -P --no-prompt Disable the prompts in interactive mode. @@ -101,6 +144,12 @@ Options: Disable the read prompt in interactive mode. + -S scale --scale=scale + + Sets the builtin variable scale to the given value assuming that the given + value is in base 10. It is a fatal error if the given value is not a valid + number. + -V --version Print version and copyright and exit. @@ -129,16 +178,36 @@ Environment variables: If an integer and non-zero, reset on SIGINT, rather than exit, when in interactive mode. + If zero, do not reset on SIGINT in all cases, but exit instead. + Overrides the default, which is %s. DC_TTY_MODE If an integer and non-zero, enable TTY mode when it is available. + If zero, disable TTY mode in all cases. + Overrides the default, which is TTY mode %s. DC_PROMPT If an integer and non-zero, enable prompt when TTY mode is possible. + If zero, disable prompt in all cases. + Overrides the default, which is prompt %s. + + DC_EXPR_EXIT + + If an integer and non-zero, exit when expressions or expression files are + given on the command-line, and does not exit when an integer and zero. + + Overrides the default, which is %s. + + DC_DIGIT_CLAMP + + If an integer and non-zero, clamp digits larger than or equal to the + current ibase when parsing numbers. + + Overrides the default, which is %s. diff --git a/contrib/bc/gen/lib.bc b/contrib/bc/gen/lib.bc index c0cd7f7dc8d..0c9389b8510 100644 --- a/contrib/bc/gen/lib.bc +++ b/contrib/bc/gen/lib.bc @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -33,7 +33,6 @@ * */ -scale=2*A define e(x){ auto b,s,n,r,d,i,p,f,v b=ibase diff --git a/contrib/bc/gen/lib2.bc b/contrib/bc/gen/lib2.bc index 23cbec104d0..d6d9f70fe06 100644 --- a/contrib/bc/gen/lib2.bc +++ b/contrib/bc/gen/lib2.bc @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -34,10 +34,34 @@ */ define p(x,y){ - auto a + auto a,i,s,z + if(y==0)return 1@scale + if(x==0){ + if(y>0)return 0 + return 1/0 + } a=y$ - if(y==a)return (x^a)@scale - return e(y*l(x)) + if(y==a)return(x^a)@scale + z=0 + if(x<1){ + y=-y + a=-a + z=x + x=1/x + } + if(y<0){ + return e(y*l(x)) + } + i=x^a + s=scale + scale+=length(i)+5 + if(z){ + x=1/z + i=x^a + } + i*=e((y-a)*l(x)) + scale=s + return i@scale } define r(x,p){ auto t,n @@ -66,6 +90,14 @@ define f(n){ for(r=1;n>1;--n)r*=n return r } +define max(a,b){ + if(a>b)return a + return b +} +define min(a,b){ + if(an)return 0 @@ -93,6 +125,18 @@ define comb(n,r){ scale=s return f } +define fib(n){ + auto i,t,p,r + if(!n)return 0 + n=abs(n)$ + t=1 + for (i=1;i>p } define ifrand(i,p){return irand(abs(i)$)+frand(p)} +define i2rand(a,b){ + auto n,x + a=a$ + b=b$ + if(a==b)return a + n=min(a,b) + x=max(a,b) + return irand(x-n+1)+n +} define srand(x){ if(irand(2))return -x return x @@ -250,8 +307,7 @@ define ubytes(x){ define sbytes(x){ auto p,n,z z=(x<0) - x=abs(x) - x=x$ + x=abs(x)$ n=ubytes(x) p=2^(n*8-1) if(x>p||(!z&&x==p))n*=2 @@ -311,21 +367,19 @@ define void pnlznl(x){ print"\n" } define void output_byte(x,i){ - auto j,p,y,b - j=ibase - ibase=A + auto j,p,y,b,s s=scale scale=0 x=abs(x)$ b=x/(2^(i*8)) - b%=256 - y=log(256,obase) + j=2^8 + b%=j + y=log(j,obase) if(b>1)p=log(b,obase)+1 else p=b for(i=y-p;i>0;--i)print 0 if(b)print b scale=s - ibase=j } define void output_uint(x,n){ auto i @@ -477,7 +531,7 @@ define bxor(a,b){ return bunrev(t) } define bshl(a,b){return abs(a)$*2^abs(b)$} -define bshr(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 diff --git a/contrib/bc/gen/strgen.c b/contrib/bc/gen/strgen.c index 63faf1ec347..1394a05c4a7 100644 --- a/contrib/bc/gen/strgen.c +++ b/contrib/bc/gen/strgen.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -33,6 +33,7 @@ * */ +#include #include #include #include @@ -40,17 +41,37 @@ #include -// For some reason, Windows needs this header. +#include +#include + +#ifndef _WIN32 +#include +#endif // _WIN32 + +// For some reason, Windows can't have this header. #ifndef _WIN32 #include #endif // _WIN32 +// This pulls in cross-platform stuff. +#include + +// clang-format off + +// The usage help. +static const char* const bc_gen_usage = + "usage: %s input output exclude name [label [define [remove_tabs]]]\n"; + +static const char* const bc_gen_ex_start = "{{ A H N HN }}"; +static const char* const bc_gen_ex_end = "{{ end }}"; + // This is exactly what it looks like. It just slaps a simple license header on // the generated C source file. static const char* const bc_gen_header = - "// Copyright (c) 2018-2021 Gavin D. Howard and contributors.\n" + "// Copyright (c) 2018-2024 Gavin D. Howard and contributors.\n" "// Licensed under the 2-clause BSD license.\n" "// *** AUTOMATICALLY GENERATED FROM %s. DO NOT MODIFY. ***\n\n"; +// clang-format on // These are just format strings used to generate the C source. static const char* const bc_gen_label = "const char *%s = \"%s\";\n\n"; @@ -77,8 +98,9 @@ static const char* const bc_gen_name_extern = "extern const char %s[];\n\n"; * @param filename The name of the file. * @param mode The mode to open the file in. */ -static void open_file(FILE** f, const char* filename, const char* mode) { - +static void +open_file(FILE** f, const char* filename, const char* mode) +{ #ifndef _WIN32 *f = fopen(filename, mode); @@ -93,6 +115,108 @@ static void open_file(FILE** f, const char* filename, const char* mode) { #endif // _WIN32 } +/** + * A portability file open function. This is copied from src/read.c. Make sure + * to update that if this changes. + * @param path The path to the file to open. + * @param mode The mode to open in. + */ +static int +bc_read_open(const char* path, int mode) +{ + int fd; + +#ifndef _WIN32 + fd = open(path, mode); +#else // _WIN32 + fd = -1; + open(&fd, path, mode); +#endif + + return fd; +} + +/** + * Reads a file and returns the file as a string. This has been copied from + * src/read.c. Make sure to change that if this changes. + * @param path The path to the file. + * @return The contents of the file as a string. + */ +static char* +bc_read_file(const char* path) +{ + int e = IO_ERR; + size_t size, to_read; + struct stat pstat; + int fd; + char* buf; + char* buf2; + + // This has been copied from src/read.c. Make sure to change that if this + // changes. + + assert(path != NULL); + +#if BC_DEBUG + // Need this to quiet MSan. + // NOLINTNEXTLINE + memset(&pstat, 0, sizeof(struct stat)); +#endif // BC_DEBUG + + fd = bc_read_open(path, O_RDONLY); + + // If we can't read a file, we just barf. + if (BC_ERR(fd < 0)) + { + fprintf(stderr, "Could not open file: %s\n", path); + exit(INVALID_INPUT_FILE); + } + + // The reason we call fstat is to eliminate TOCTOU race conditions. This + // way, we have an open file, so it's not going anywhere. + if (BC_ERR(fstat(fd, &pstat) == -1)) + { + fprintf(stderr, "Could not stat file: %s\n", path); + exit(INVALID_INPUT_FILE); + } + + // Make sure it's not a directory. + if (BC_ERR(S_ISDIR(pstat.st_mode))) + { + fprintf(stderr, "Path is directory: %s\n", path); + exit(INVALID_INPUT_FILE); + } + + // Get the size of the file and allocate that much. + size = (size_t) pstat.st_size; + buf = (char*) malloc(size + 1); + if (buf == NULL) + { + fprintf(stderr, "Could not malloc\n"); + exit(INVALID_INPUT_FILE); + } + buf2 = buf; + to_read = size; + + do + { + // Read the file. We just bail if a signal interrupts. This is so that + // users can interrupt the reading of big files if they want. + ssize_t r = read(fd, buf2, to_read); + if (BC_ERR(r < 0)) exit(e); + to_read -= (size_t) r; + buf2 += (size_t) r; + } + while (to_read); + + // Got to have a nul byte. + buf[size] = '\0'; + + close(fd); + + return buf; +} + /** * Outputs a label, which is a string literal that the code can use as a name * for the file that is being turned into a string. This is important for the @@ -112,8 +236,9 @@ static void open_file(FILE** f, const char* filename, const char* mode) { * @param name The actual label text, which is a filename. * @return Positive if no error, negative on error, just like *printf(). */ -static int output_label(FILE* out, const char* label, const char* name) { - +static int +output_label(FILE* out, const char* label, const char* name) +{ #ifndef _WIN32 return fprintf(out, bc_gen_label, label, name); @@ -125,7 +250,10 @@ static int output_label(FILE* out, const char* label, const char* name) { int ret; // This loop counts how many backslashes there are in the label. - for (i = 0; i < len; ++i) count += (name[i] == '\\'); + for (i = 0; i < len; ++i) + { + count += (name[i] == '\\'); + } buf = (char*) malloc(len + 1 + count); if (buf == NULL) return -1; @@ -136,11 +264,12 @@ static int output_label(FILE* out, const char* label, const char* name) { // label byte-for-byte, unless it encounters a backslash, in which case, it // copies the backslash twice to have it escaped properly in the string // literal. - for (i = 0; i < len; ++i) { - + for (i = 0; i < len; ++i) + { buf[i + count] = name[i]; - if (name[i] == '\\') { + if (name[i] == '\\') + { count += 1; buf[i + count] = name[i]; } @@ -178,9 +307,10 @@ static int output_label(FILE* out, const char* label, const char* name) { * * The required command-line parameters are: * - * input Input filename. - * output Output filename. - * name The name of the char array. + * input Input filename. + * output Output filename. + * exclude Whether to exclude extra math-only stuff. + * name The name of the char array. * * The optional parameters are: * @@ -202,34 +332,41 @@ static int output_label(FILE* out, const char* label, const char* name) { * All text files that are transformed have license comments. This program finds * the end of that comment and strips it out as well. */ -int main(int argc, char *argv[]) { - - FILE *in, *out; - char *label, *define, *name; - int c, count, slashes, err = IO_ERR; - bool has_label, has_define, remove_tabs; - - if (argc < 4) { - printf("usage: %s input output name [label [define [remove_tabs]]]\n", - argv[0]); +int +main(int argc, char* argv[]) +{ + char* in; + FILE* out; + const char* label; + const char* define; + char* name; + unsigned int count, slashes, err = IO_ERR; + bool has_label, has_define, remove_tabs, exclude_extra_math; + size_t i; + + if (argc < 5) + { + printf(bc_gen_usage, argv[0]); return INVALID_PARAMS; } - name = argv[3]; + exclude_extra_math = (strtoul(argv[3], NULL, 10) != 0); - has_label = (argc > 4 && strcmp("", argv[4]) != 0); - label = has_label ? argv[4] : ""; + name = argv[4]; - has_define = (argc > 5 && strcmp("", argv[5]) != 0); - define = has_define ? argv[5] : ""; + has_label = (argc > 5 && strcmp("", argv[5]) != 0); + label = has_label ? argv[5] : ""; - remove_tabs = (argc > 6); + has_define = (argc > 6 && strcmp("", argv[6]) != 0); + define = has_define ? argv[6] : ""; - open_file(&in, argv[1], "r"); - if (!in) return INVALID_INPUT_FILE; + remove_tabs = (argc > 7 && atoi(argv[7]) != 0); + + in = bc_read_file(argv[1]); + if (in == NULL) return INVALID_INPUT_FILE; open_file(&out, argv[2], "w"); - if (!out) goto out_err; + if (out == NULL) goto out_err; if (fprintf(out, bc_gen_header, argv[1]) < 0) goto err; if (has_label && fprintf(out, bc_gen_label_extern, label) < 0) goto err; @@ -238,46 +375,121 @@ int main(int argc, char *argv[]) { if (has_label && output_label(out, label, argv[1]) < 0) goto err; if (fprintf(out, bc_gen_name, name) < 0) goto err; - c = count = slashes = 0; + i = count = slashes = 0; // This is where the end of the license comment is found. - while (slashes < 2 && (c = fgetc(in)) >= 0) { - slashes += (slashes == 1 && c == '/' && fgetc(in) == '\n'); - slashes += (!slashes && c == '/' && fgetc(in) == '*'); + while (slashes < 2 && in[i] > 0) + { + if (slashes == 1 && in[i] == '*' && in[i + 1] == '/' && + (in[i + 2] == '\n' || in[i + 2] == '\r')) + { + slashes += 1; + i += 2; + } + else if (!slashes && in[i] == '/' && in[i + 1] == '*') + { + slashes += 1; + i += 1; + } + + i += 1; } // The file is invalid if the end of the license comment could not be found. - if (c < 0) { + if (in[i] == 0) + { + fprintf(stderr, "Could not find end of license comment\n"); err = INVALID_INPUT_FILE; goto err; } + i += 1; + // Do not put extra newlines at the beginning of the char array. - while ((c = fgetc(in)) == '\n'); + while (in[i] == '\n' || in[i] == '\r') + { + i += 1; + } // This loop is what generates the actual char array. It counts how many // chars it has printed per line in order to insert newlines at appropriate // places. It also skips tabs if they should be removed. - while (c >= 0) { - + while (in[i] != 0) + { int val; - if (!remove_tabs || c != '\t') { + if (in[i] == '\r') + { + i += 1; + continue; + } + + if (!remove_tabs || in[i] != '\t') + { + // Check for excluding something for extra math. + if (in[i] == '{') + { + // If we found the start... + if (!strncmp(in + i, bc_gen_ex_start, strlen(bc_gen_ex_start))) + { + if (exclude_extra_math) + { + // Get past the braces. + i += 2; + + // Find the end of the end. + while (in[i] != '{' && strncmp(in + i, bc_gen_ex_end, + strlen(bc_gen_ex_end))) + { + i += 1; + } + + i += strlen(bc_gen_ex_end); + + // Skip the last newline. + if (in[i] == '\r') i += 1; + i += 1; + continue; + } + else + { + i += strlen(bc_gen_ex_start); + + // Skip the last newline. + if (in[i] == '\r') i += 1; + i += 1; + continue; + } + } + else if (!exclude_extra_math && + !strncmp(in + i, bc_gen_ex_end, strlen(bc_gen_ex_end))) + { + i += strlen(bc_gen_ex_end); + + // Skip the last newline. + if (in[i] == '\r') i += 1; + i += 1; + continue; + } + } + // Print a tab if we are at the beginning of a line. if (!count && fputc('\t', out) == EOF) goto err; - val = fprintf(out, "%d,", c); + // Print the character. + val = fprintf(out, "%d,", in[i]); if (val < 0) goto err; - count += val; - - if (count > MAX_WIDTH) { + // Adjust the count. + count += (unsigned int) val; + if (count > MAX_WIDTH) + { count = 0; if (fputc('\n', out) == EOF) goto err; } } - c = fgetc(in); + i += 1; } // Make sure the end looks nice and insert the NUL byte at the end. @@ -289,6 +501,6 @@ int main(int argc, char *argv[]) { err: fclose(out); out_err: - fclose(in); - return err; + free(in); + return (int) err; } diff --git a/contrib/bc/gen/strgen.sh b/contrib/bc/gen/strgen.sh index acaa6cdf079..8542bd40ee8 100755 --- a/contrib/bc/gen/strgen.sh +++ b/contrib/bc/gen/strgen.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -32,24 +32,53 @@ export LC_CTYPE=C progname=${0##*/} +script="$0" +scriptdir=$(dirname "$script") +. "$scriptdir/../scripts/functions.sh" + +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s input output exclude name [label [define [remove_tabs]]]\n' "$progname" + exit 1 +} + # See strgen.c comment on main() for what these mean. Note, however, that this # script generates a string literal, not a char array. To understand the # consequences of that, see manuals/development.md#strgenc. if [ $# -lt 3 ]; then - echo "usage: $progname input output name [label [define [remove_tabs]]]" - exit 1 + usage "Not enough arguments" fi input="$1" +check_file_arg "$input" output="$2" -name="$3" -label="$4" -define="$5" -remove_tabs="$6" +exclude="$3" +name="$4" +label="$5" +define="$6" +remove_tabs="$7" +if [ "$remove_tabs" != "" ]; then + check_bool_arg "$remove_tabs" +fi -exec < "$input" +tmpinput=$(mktemp -t "${input##*/}_XXXXXX") + +if [ "$exclude" -ne 0 ]; then + filter_text "$input" "$tmpinput" "E" +else + filter_text "$input" "$tmpinput" "A" +fi + +exec < "$tmpinput" exec > "$output" +rm -f "$tmpinput" + if [ -n "$label" ]; then nameline="const char *${label} = \"${input}\";" labelexternline="extern const char *${label};" @@ -67,7 +96,7 @@ if [ -n "$remove_tabs" ]; then fi cat<exprs.len > 1) + +#else // DC_ENABLED + +/// Returns true if the banner should be quieted. +#define BC_ARGS_SHOULD_BE_QUIET (vm->exprs.len > 1) + +#endif // DC_ENABLED + +#else // BC_ENABLED + +/// Returns true if the banner should be quieted. +#define BC_ARGS_SHOULD_BE_QUIET (BC_IS_DC) + +#endif // BC_ENABLED // A reference to the list of long options. extern const BcOptLong bc_args_lopt[]; diff --git a/contrib/bc/include/bc.h b/contrib/bc/include/bc.h index a4198b91ebc..2213278be1d 100644 --- a/contrib/bc/include/bc.h +++ b/contrib/bc/include/bc.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -48,8 +48,10 @@ /** * The main function for bc. It just sets variables and passes its arguments * through to @a bc_vm_boot(). + * @return A status. */ -void bc_main(int argc, char *argv[]); +BcStatus +bc_main(int argc, const char* argv[]); // These are references to the help text, the library text, and the "filename" // for the library. @@ -66,8 +68,8 @@ extern const char* bc_lib2_name; /** * A struct containing information about a bc keyword. */ -typedef struct BcLexKeyword { - +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; @@ -94,13 +96,13 @@ typedef struct BcLexKeyword { /// 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 (35) +#define BC_LEX_NKWS (37) #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 (31) +#define BC_LEX_NKWS (33) #endif // BC_ENABLE_EXTRA_MATH @@ -113,7 +115,8 @@ extern const size_t bc_lex_kws_len; * @a BcLexNext.) * @param l The lexer. */ -void bc_lex_token(BcLex *l); +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. @@ -144,49 +147,49 @@ void bc_lex_token(BcLex *l); // 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_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_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_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_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_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_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_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_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_FLAG_IF_END (UINTMAX_C(1) << 8) #define BC_PARSE_IF_END(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF_END) /** @@ -261,7 +264,7 @@ void bc_lex_token(BcLex *l); * @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) \ +#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)) @@ -353,8 +356,8 @@ void bc_lex_token(BcLex *l); /// /// 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 { - +typedef struct BcParseNext +{ /// The number of tokens in the tokens array. uchar len; @@ -373,8 +376,8 @@ typedef struct BcParseNext { /// A status returned by @a bc_parse_expr_err(). It can either return success or /// an error indicating an empty expression. -typedef enum BcParseStatus { - +typedef enum BcParseStatus +{ BC_PARSE_STATUS_SUCCESS, BC_PARSE_STATUS_EMPTY_EXPR, @@ -387,14 +390,16 @@ typedef enum BcParseStatus { * @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); +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); +void +bc_parse_parse(BcParse* p); /** * Ends a series of if statements. This is to ensure that full parses happen @@ -403,7 +408,8 @@ void bc_parse_parse(BcParse *p); * function definition, we know we can add an empty else clause. * @param p The parser. */ -void bc_parse_endif(BcParse *p); +void +bc_parse_endif(BcParse* p); /// References to the signal message and its length. extern const char bc_sig_msg[]; diff --git a/contrib/bc/include/bcl.h b/contrib/bc/include/bcl.h index 9c0e5e59cfd..8e762b694f4 100644 --- a/contrib/bc/include/bcl.h +++ b/contrib/bc/include/bcl.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -36,6 +36,17 @@ #ifndef BC_BCL_H #define BC_BCL_H +#include +#include +#include +#include + +#ifndef NDEBUG +#define BC_DEBUG (1) +#else // NDEBUG +#define BC_DEBUG (0) +#endif // NDEBUG + #ifdef _WIN32 #include #include @@ -43,44 +54,8 @@ #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) | _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) @@ -129,8 +104,8 @@ typedef uint32_t BclRandInt; #if BC_ENABLE_LIBRARY -typedef enum BclError { - +typedef enum BclError +{ BCL_ERROR_NONE, BCL_ERROR_INVALID_NUM, @@ -151,8 +126,8 @@ typedef enum BclError { } BclError; -typedef struct BclNumber { - +typedef struct BclNumber +{ size_t i; } BclNumber; @@ -161,81 +136,233 @@ 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); +BclError +bcl_start(void); + +void +bcl_end(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); + +bool +bcl_digitClamp(void); + +void +bcl_setDigitClamp(bool digitClamp); + +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); + +BclError +bcl_bigdig_keep(BclNumber n, BclBigDig* result); + +BclNumber +bcl_bigdig2num(BclBigDig val); + +BclNumber +bcl_add(BclNumber a, BclNumber b); + +BclNumber +bcl_add_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_sub(BclNumber a, BclNumber b); + +BclNumber +bcl_sub_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_mul(BclNumber a, BclNumber b); + +BclNumber +bcl_mul_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_div(BclNumber a, BclNumber b); + +BclNumber +bcl_div_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_mod(BclNumber a, BclNumber b); + +BclNumber +bcl_mod_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_pow(BclNumber a, BclNumber b); + +BclNumber +bcl_pow_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_lshift(BclNumber a, BclNumber b); + +BclNumber +bcl_lshift_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_rshift(BclNumber a, BclNumber b); + +BclNumber +bcl_rshift_keep(BclNumber a, BclNumber b); + +BclNumber +bcl_sqrt(BclNumber a); + +BclNumber +bcl_sqrt_keep(BclNumber a); + +BclError +bcl_divmod(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d); + +BclError +bcl_divmod_keep(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d); + +BclNumber +bcl_modexp(BclNumber a, BclNumber b, BclNumber c); + +BclNumber +bcl_modexp_keep(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); + +char* +bcl_string_keep(BclNumber n); + +BclNumber +bcl_irand(BclNumber a); + +BclNumber +bcl_irand_keep(BclNumber a); + +BclNumber +bcl_frand(size_t places); + +BclNumber +bcl_ifrand(BclNumber a, size_t places); + +BclNumber +bcl_ifrand_keep(BclNumber a, size_t places); + +BclError +bcl_rand_seedWithNum(BclNumber n); + +BclError +bcl_rand_seedWithNum_keep(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 diff --git a/contrib/bc/include/dc.h b/contrib/bc/include/dc.h index 88b5e054f87..63f5ccbd10e 100644 --- a/contrib/bc/include/dc.h +++ b/contrib/bc/include/dc.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -45,8 +45,10 @@ /** * The main function for dc. It just sets variables and passes its arguments * through to @a bc_vm_boot(). + * @return A status. */ -void dc_main(int argc, char *argv[]); +BcStatus +dc_main(int argc, const char* argv[]); // A reference to the dc help text. extern const char dc_help[]; @@ -56,7 +58,8 @@ extern const char dc_help[]; * @a BcLexNext.) * @param l The lexer. */ -void dc_lex_token(BcLex *l); +void +dc_lex_token(BcLex* l); /** * Returns true if the negative char `_` should be treated as a command or not. @@ -66,7 +69,8 @@ void dc_lex_token(BcLex *l); * @return True if a negative should be treated as a command, false if it * should be treated as a negative sign on a number. */ -bool dc_lex_negCommand(BcLex *l); +bool +dc_lex_negCommand(BcLex* l); // References to the signal message and its length. extern const char dc_sig_msg[]; @@ -88,7 +92,8 @@ extern const uint8_t dc_parse_insts[]; * @a BcParseParse.) * @param p The parser. */ -void dc_parse_parse(BcParse *p); +void +dc_parse_parse(BcParse* p); /** * The @a BcParseExpr function for dc. (See include/parse.h for a definition of @@ -97,7 +102,8 @@ void dc_parse_parse(BcParse *p); * @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 dc_parse_expr(BcParse *p, uint8_t flags); +void +dc_parse_expr(BcParse* p, uint8_t flags); #endif // DC_ENABLED diff --git a/contrib/bc/include/file.h b/contrib/bc/include/file.h index b30b932c9ab..86f368db11c 100644 --- a/contrib/bc/include/file.h +++ b/contrib/bc/include/file.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -38,18 +38,40 @@ #include +#include #include #define BC_FILE_ULL_LENGTH (21) +#if BC_ENABLE_LINE_LIB + +#include + /// The file struct. -typedef struct BcFile { +typedef struct BcFile +{ + // The file. This is here simply to make the line lib code as compatible + // with the existing code as possible. + FILE* f; + + // True if errors should be fatal, false otherwise. + bool errors_fatal; + +} BcFile; +#else // BC_ENABLE_LINE_LIB + +/// The file struct. +typedef struct BcFile +{ // The actual file descriptor. int fd; + // True if errors should be fatal, false otherwise. + bool errors_fatal; + // The buffer for the file. - char *buf; + char* buf; // The length (number of actual chars) in the buffer. size_t len; @@ -59,13 +81,15 @@ typedef struct BcFile { } BcFile; -#if BC_ENABLE_HISTORY +#endif // BC_ENABLE_LINE_LIB + +#if BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB /// Types of flushing. These are important because of history and printing /// strings without newlines, something that users could use as their own /// prompts. -typedef enum BcFlushType { - +typedef enum BcFlushType +{ /// Do not clear the stored partial line, but don't add to it. BC_FLUSH_NO_EXTRAS_NO_CLEAR, @@ -80,33 +104,59 @@ typedef enum BcFlushType { } BcFlushType; -#else // BC_ENABLE_HISTORY +// These are here to satisfy a clang warning about recursive macros. + +#define bc_file_putchar(f, t, c) bc_file_putchar_impl(f, t, c) +#define bc_file_flushErr(f, t) bc_file_flushErr_impl(f, t) +#define bc_file_flush(f, t) bc_file_flush_impl(f, t) +#define bc_file_write(f, t, b, n) bc_file_write_impl(f, t, b, n) +#define bc_file_puts(f, t, s) bc_file_puts_impl(f, t, s) + +#else // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB // These make sure that the BcFlushType parameter disappears if history is not -// used. +// used, editline is used, or readline is used. + +#define bc_file_putchar(f, t, c) bc_file_putchar_impl(f, c) +#define bc_file_flushErr(f, t) bc_file_flushErr_impl(f) +#define bc_file_flush(f, t) bc_file_flush_impl(f) +#define bc_file_write(f, t, b, n) bc_file_write_impl(f, b, n) +#define bc_file_puts(f, t, s) bc_file_puts_impl(f, s) -#define bc_file_putchar(f, t, c) bc_file_putchar(f, c) -#define bc_file_flushErr(f, t) bc_file_flushErr(f) -#define bc_file_flush(f, t) bc_file_flush(f) -#define bc_file_write(f, t, b, n) bc_file_write(f, b, n) -#define bc_file_puts(f, t, s) bc_file_puts(f, s) +#endif // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB -#endif // BC_ENABLE_HISTORY +#if BC_ENABLE_LINE_LIB /** * Initialize a file. - * @param f The file to initialize. - * @param fd The file descriptor. - * @param buf The buffer for the file. - * @param cap The capacity of the buffer. + * @param f The file to initialize. + * @param file The stdio file. + * @param errors_fatal True if errors should be fatal, false otherwise. */ -void bc_file_init(BcFile *f, int fd, char *buf, size_t cap); +void +bc_file_init(BcFile* f, FILE* file, bool errors_fatal); + +#else // BC_ENABLE_LINE_LIB + +/** + * Initialize a file. + * @param f The file to initialize. + * @param fd The file descriptor. + * @param buf The buffer for the file. + * @param cap The capacity of the buffer. + * @param errors_fatal True if errors should be fatal, false otherwise. + */ +void +bc_file_init(BcFile* f, int fd, char* buf, size_t cap, bool errors_fatal); + +#endif // BC_ENABLE_LINE_LIB /** * Frees a file, including flushing it. * @param f The file to free. */ -void bc_file_free(BcFile *f); +void +bc_file_free(BcFile* f); /** * Print a char into the file. @@ -114,7 +164,8 @@ void bc_file_free(BcFile *f); * @param type The flush type. * @param c The character to write. */ -void bc_file_putchar(BcFile *restrict f, BcFlushType type, uchar c); +void +bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c); /** * Flush and return an error if it failed. This is meant to be used when needing @@ -124,14 +175,16 @@ void bc_file_putchar(BcFile *restrict f, BcFlushType type, uchar c); * @param type The flush type. * @return A status indicating if an error occurred. */ -BcStatus bc_file_flushErr(BcFile *restrict f, BcFlushType type); +BcStatus +bc_file_flushErr(BcFile* restrict f, BcFlushType type); /** * Flush and throw an error on failure. * @param f The file to flush. * @param type The flush type. */ -void bc_file_flush(BcFile *restrict f, BcFlushType type); +void +bc_file_flush(BcFile* restrict f, BcFlushType type); /** * Write the contents of buf to the file. @@ -140,22 +193,24 @@ void bc_file_flush(BcFile *restrict f, BcFlushType type); * @param buf The buffer whose contents will be written to the file. * @param n The length of buf. */ -void bc_file_write(BcFile *restrict f, BcFlushType type, - const char *buf, size_t n); +void +bc_file_write(BcFile* restrict f, BcFlushType type, const char* buf, size_t n); /** * Write to the file like fprintf would. This is very rudimentary. * @param f The file to flush. * @param fmt The format string. */ -void bc_file_printf(BcFile *restrict f, const char *fmt, ...); +void +bc_file_printf(BcFile* restrict f, const char* fmt, ...); /** * Write to the file like vfprintf would. This is very rudimentary. * @param f The file to flush. * @param fmt The format string. */ -void bc_file_vprintf(BcFile *restrict f, const char *fmt, va_list args); +void +bc_file_vprintf(BcFile* restrict f, const char* fmt, va_list args); /** * Write str to the file. @@ -163,15 +218,16 @@ void bc_file_vprintf(BcFile *restrict f, const char *fmt, va_list args); * @param type The flush type. * @param str The string to write to the file. */ -void bc_file_puts(BcFile *restrict f, BcFlushType type, const char *str); +void +bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str); -#if BC_ENABLE_HISTORY +#if BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB // Some constant flush types for ease of use. extern const BcFlushType bc_flush_none; extern const BcFlushType bc_flush_err; extern const BcFlushType bc_flush_save; -#endif // BC_ENABLE_HISTORY +#endif // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB #endif // BC_FILE_H diff --git a/contrib/bc/include/history.h b/contrib/bc/include/history.h index 8d9c3417d89..13f6dc6e985 100644 --- a/contrib/bc/include/history.h +++ b/contrib/bc/include/history.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -79,13 +79,96 @@ #ifndef BC_HISTORY_H #define BC_HISTORY_H -#ifndef BC_ENABLE_HISTORY -#define BC_ENABLE_HISTORY (1) -#endif // BC_ENABLE_HISTORY +// These must come before the #if BC_ENABLE_LINE_LIB below because status.h +// defines it. +#include +#include -#if BC_ENABLE_HISTORY +#if BC_ENABLE_LINE_LIB #include +#include +#include + +extern sigjmp_buf bc_history_jmpbuf; +extern volatile sig_atomic_t bc_history_inlinelib; + +#endif // BC_ENABLE_LINE_LIB + +#if BC_ENABLE_EDITLINE + +#include +#include + +/** + * The history struct for editline. + */ +typedef struct BcHistory +{ + /// A place to store the current line. + EditLine* el; + + /// The history. + History* hist; + + /// Whether the terminal is bad. This is more or less not used. + bool badTerm; + +} BcHistory; + +// The path to the editrc and its length. +extern const char bc_history_editrc[]; +extern const size_t bc_history_editrc_len; + +#ifdef __APPLE__ + +/** + * Returns true if the line is a valid line, false otherwise. + * @param line The line. + * @param len The length of the line. + * @return True if the line is valid, false otherwise. + */ +#define BC_HISTORY_INVALID_LINE(line, len) \ + ((line) == NULL && ((len) == -1 || errno == EINTR)) + +#else // __APPLE__ + +/** + * Returns true if the line is a valid line, false otherwise. + * @param line The line. + * @param len The length of the line. + * @return True if the line is valid, false otherwise. + */ +#define BC_HISTORY_INVALID_LINE(line, len) \ + ((line) == NULL && (len) == -1 && errno == EINTR) + +#endif // __APPLE__ + +#else // BC_ENABLE_EDITLINE + +#if BC_ENABLE_READLINE + +#include +#include +#include + +/** + * The history struct for readline. + */ +typedef struct BcHistory +{ + /// A place to store the current line. + char* line; + + /// Whether the terminal is bad. This is more or less not used. + bool badTerm; + +} BcHistory; + +#else // BC_ENABLE_READLINE + +#if BC_ENABLE_HISTORY + #include #include @@ -106,7 +189,7 @@ #include #define strncasecmp _strnicmp -#define strcasecmp _stricmp +#define strcasecmp _stricmp #endif // _WIN32 @@ -114,10 +197,6 @@ #include #include -#if BC_DEBUG_CODE -#include -#endif // BC_DEBUG_CODE - /// Default columns. #define BC_HIST_DEF_COLS (80) @@ -154,9 +233,12 @@ #define BC_HISTORY_DEBUG_BUF_SIZE (1024) +// clang-format off #define lndebug(...) \ - do { \ - if (bc_history_debug_fp.fd == 0) { \ + 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), \ @@ -169,15 +251,17 @@ } \ bc_file_printf(&bc_history_debug_fp, ", " __VA_ARGS__); \ bc_file_flush(&bc_history_debug_fp); \ - } while (0) + } \ + while (0) #else // BC_DEBUG_CODE #define lndebug(fmt, ...) #endif // BC_DEBUG_CODE +// clang-format on /// An enum of useful actions. To understand what these mean, check terminal /// emulators for their shortcuts or the VT100 codes. -typedef enum BcHistoryAction { - +typedef enum BcHistoryAction +{ BC_ACTION_NULL = 0, BC_ACTION_CTRL_A = 1, BC_ACTION_CTRL_B = 2, @@ -200,7 +284,7 @@ typedef enum BcHistoryAction { BC_ACTION_CTRL_Z = 26, BC_ACTION_ESC = 27, BC_ACTION_CTRL_BSLASH = 28, - BC_ACTION_BACKSPACE = 127 + BC_ACTION_BACKSPACE = 127 } BcHistoryAction; @@ -208,8 +292,8 @@ typedef enum BcHistoryAction { * This represents the state during line editing. We pass this state * to functions implementing specific editing functionalities. */ -typedef struct BcHistory { - +typedef struct BcHistory +{ /// Edited line buffer. BcVec buf; @@ -220,7 +304,7 @@ typedef struct BcHistory { BcVec extras; /// Prompt to display. - const char *prompt; + const char* prompt; /// Prompt length. size_t plen; @@ -272,39 +356,15 @@ typedef struct BcHistory { } 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); +void +bc_history_string_free(void* str); // A list of terminals that don't work. -extern const char *bc_history_bad_terms[]; +extern const char* bc_history_bad_terms[]; // A tab in history and its length. extern const char bc_history_tab[]; @@ -323,16 +383,53 @@ extern const size_t bc_history_combo_chars_len; // Debug data. extern BcFile bc_history_debug_fp; -extern char *bc_history_debug_buf; +extern char* bc_history_debug_buf; /** * A function to print keycodes for debugging. * @param h The history data. */ -void bc_history_printKeyCodes(BcHistory* h); +void +bc_history_printKeyCodes(BcHistory* h); #endif // BC_DEBUG_CODE #endif // BC_ENABLE_HISTORY +#endif // BC_ENABLE_READLINE + +#endif // BC_ENABLE_EDITLINE + +#if BC_ENABLE_HISTORY + +/** + * 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); + +#endif // BC_ENABLE_HISTORY + #endif // BC_HISTORY_H diff --git a/contrib/bc/include/lang.h b/contrib/bc/include/lang.h index 705aca35df1..6c824513971 100644 --- a/contrib/bc/include/lang.h +++ b/contrib/bc/include/lang.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -38,15 +38,19 @@ #include +// These have to come first to silence a warning on BC_C11 below. #include #include #include -/// The instructions for bytecode. -typedef enum BcInst { +#if BC_C11 +#include +#endif // BC_C11 +/// 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, @@ -58,6 +62,7 @@ typedef enum BcInst { /// Boolean not. BC_INST_BOOL_NOT, + #if BC_ENABLE_EXTRA_MATH /// Truncation operator. BC_INST_TRUNC, @@ -72,7 +77,6 @@ typedef enum BcInst { BC_INST_MINUS, #if BC_ENABLE_EXTRA_MATH - /// Places operator. BC_INST_PLACES, @@ -174,6 +178,8 @@ typedef enum BcInst { BC_INST_SCALE_FUNC, BC_INST_SQRT, BC_INST_ABS, + BC_INST_IS_NUMBER, + BC_INST_IS_STRING, #if BC_ENABLE_EXTRA_MATH /// Another builtin function. @@ -271,6 +277,9 @@ typedef enum BcInst { #if DC_ENABLED + /// dc extended registers command. + BC_INST_EXTENDED_REGISTERS, + /// dc's return; it pops an executing string off of the stack. BC_INST_POP_EXEC, @@ -324,11 +333,16 @@ typedef enum BcInst { } BcInst; -/// Used by maps to identify where items are in the array. -typedef struct BcId { +#if BC_C11 +_Static_assert(BC_INST_INVALID <= UCHAR_MAX, + "Too many instructions to fit into an unsigned char"); +#endif // BC_C11 +/// Used by maps to identify where items are in the array. +typedef struct BcId +{ /// The name of the item. - char *name; + char* name; /// The index into the array where the item is. size_t idx; @@ -336,21 +350,27 @@ typedef struct BcId { } BcId; /// The location of a var, array, or array element. -typedef struct BcLoc { - +typedef struct BcLoc +{ /// The index of the var or array. size_t loc; + /// The index of the array or variable in the array stack. This is to + /// prevent a bug with getting the wrong array element or variable after a + /// function call. See the tests/bc/scripts/array.bc test for the array + /// case; the variable case is in various variable tests. + size_t stack_idx; + /// The index of the array element. Only used for array elements. size_t idx; } BcLoc; /// An entry for a constant. -typedef struct BcConst { - +typedef struct BcConst +{ /// The original string as parsed from the source code. - char *val; + char* val; /// The last base that the constant was parsed in. BcBigDig base; @@ -363,8 +383,8 @@ typedef struct 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 { - +typedef struct BcFunc +{ /// The bytecode instructions. BcVec code; @@ -383,14 +403,8 @@ typedef struct BcFunc { #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; + const char* name; #if BC_ENABLED /// True if the function is a void function. @@ -400,8 +414,8 @@ typedef struct BcFunc { } BcFunc; /// Types of results that can be pushed onto the results stack. -typedef enum BcResultType { - +typedef enum BcResultType +{ /// Result is a variable. BC_RESULT_VAR, @@ -455,8 +469,8 @@ typedef enum BcResultType { } BcResultType; /// A union to store data for various result types. -typedef union BcResultData { - +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 @@ -473,8 +487,8 @@ typedef union BcResultData { } BcResultData; /// A tagged union for results. -typedef struct BcResult { - +typedef struct BcResult +{ /// The tag. The type of the result. BcResultType t; @@ -485,8 +499,8 @@ typedef struct BcResult { /// An instruction pointer. This is how bc knows where in the bytecode vector, /// and which function, the current execution is. -typedef struct BcInstPtr { - +typedef struct BcInstPtr +{ /// The index of the currently executing function in the fns vector. size_t func; @@ -501,8 +515,8 @@ typedef struct BcInstPtr { } BcInstPtr; /// Types of identifiers. -typedef enum BcType { - +typedef enum BcType +{ /// Variable. BC_TYPE_VAR, @@ -520,8 +534,8 @@ typedef enum BcType { #if BC_ENABLED /// An auto variable in bc. -typedef struct BcAuto { - +typedef struct BcAuto +{ /// The index of the variable in the vars or arrs vectors. size_t idx; @@ -540,7 +554,8 @@ struct BcProgram; * @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); +void +bc_func_init(BcFunc* f, const char* name); /** * Inserts an auto into the function. @@ -551,25 +566,28 @@ void bc_func_init(BcFunc *f, const char* name); * @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); +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); +void +bc_func_reset(BcFunc* f); -#ifndef NDEBUG +#if BC_DEBUG /** * 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 +void +bc_func_free(void* func); +#endif // BC_DEBUG /** * Initializes an array, which is the array type in bc and dc source code. Since @@ -582,7 +600,8 @@ void bc_func_free(void *func); * @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); +void +bc_array_init(BcVec* a, bool nums); /** * Copies an array to another array. This is used to do pass arrays to functions @@ -591,19 +610,22 @@ void bc_array_init(BcVec *a, bool nums); * @param d The destination array. * @param s The source array. */ -void bc_array_copy(BcVec *d, const BcVec *s); +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); +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); +void +bc_const_free(void* constant); /** * Clears a result. It sets the type to BC_RESULT_TEMP and clears the union by @@ -611,7 +633,8 @@ void bc_const_free(void *constant); * uninitialized data. * @param r The result to clear. */ -void bc_result_clear(BcResult *r); +void +bc_result_clear(BcResult* r); /** * Copies a result into another. This is done for things like duplicating the @@ -620,13 +643,15 @@ void bc_result_clear(BcResult *r); * @param d The destination result. * @param src The source result. */ -void bc_result_copy(BcResult *d, BcResult *src); +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); +void +bc_result_free(void* result); /** * Expands an array to @a len. This can happen because in bc, you do not have to @@ -637,17 +662,8 @@ void bc_result_free(void *result); * @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); +void +bc_array_expand(BcVec* a, size_t len); #if BC_ENABLED diff --git a/contrib/bc/include/lex.h b/contrib/bc/include/lex.h index 0e7af174200..d2be3c7526e 100644 --- a/contrib/bc/include/lex.h +++ b/contrib/bc/include/lex.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -43,10 +43,30 @@ #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. +/** + * A convenience macro for throwing errors in lex code. This takes care of + * plumbing like passing in the current line the lexer is on. + * @param l The lexer. + * @param e The error. + */ +#if BC_DEBUG +#define bc_lex_err(l, e) (bc_vm_handleError((e), __FILE__, __LINE__, (l)->line)) +#else // BC_DEBUG #define bc_lex_err(l, e) (bc_vm_handleError((e), (l)->line)) +#endif // BC_DEBUG + +/** + * A convenience macro for throwing errors in lex code. This takes care of + * plumbing like passing in the current line the lexer is on. + * @param l The lexer. + * @param e The error. + */ +#if BC_DEBUG +#define bc_lex_verr(l, e, ...) \ + (bc_vm_handleError((e), __FILE__, __LINE__, (l)->line, __VA_ARGS__)) +#else // BC_DEBUG #define bc_lex_verr(l, e, ...) (bc_vm_handleError((e), (l)->line, __VA_ARGS__)) +#endif // BC_DEBUG // BC_LEX_NEG_CHAR returns the char that corresponds to negative for the // current calculator. @@ -84,8 +104,8 @@ ((c) == '.' && !(pt) && !(int_only))) /// An enum of lex token types. -typedef enum BcLexType { - +typedef enum BcLexType +{ /// End of file. BC_LEX_EOF, @@ -136,6 +156,7 @@ typedef enum BcLexType { BC_LEX_OP_MINUS, #if BC_ENABLE_EXTRA_MATH + /// Places (truncate or extend) operator. BC_LEX_OP_PLACES, @@ -144,6 +165,7 @@ typedef enum BcLexType { /// Right (decimal) shift operator. BC_LEX_OP_RSHIFT, + #endif // BC_ENABLE_EXTRA_MATH /// Equal operator. @@ -171,6 +193,7 @@ typedef enum BcLexType { BC_LEX_OP_BOOL_AND, #if BC_ENABLED + /// Power assignment operator. BC_LEX_OP_ASSIGN_POWER, @@ -314,6 +337,12 @@ typedef enum BcLexType { /// bc abs keyword. BC_LEX_KW_ABS, + /// bc is_number keyword. + BC_LEX_KW_IS_NUMBER, + + /// bc is_string keyword. + BC_LEX_KW_IS_STRING, + #if BC_ENABLE_EXTRA_MATH /// bc irand keyword. @@ -353,8 +382,10 @@ typedef enum BcLexType { 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. @@ -378,6 +409,9 @@ typedef enum BcLexType { #if DC_ENABLED + /// dc extended registers keyword. + BC_LEX_EXTENDED_REGISTERS, + /// A special token for dc to calculate equal without a register. BC_LEX_EQ_NO_REG, @@ -418,8 +452,10 @@ typedef enum BcLexType { 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. @@ -462,10 +498,10 @@ struct BcLex; typedef void (*BcLexNext)(struct BcLex* l); /// The lexer. -typedef struct BcLex { - +typedef struct BcLex +{ /// A pointer to the text to lex. - const char *buf; + const char* buf; /// The current index into buf. size_t i; @@ -487,9 +523,8 @@ typedef struct BcLex { /// 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; + /// The mode the lexer is in. + BcMode mode; } BcLex; @@ -497,55 +532,63 @@ typedef struct BcLex { * Initializes a lexer. * @param l The lexer to initialize. */ -void bc_lex_init(BcLex *l); +void +bc_lex_init(BcLex* l); /** - * Frees a lexer. This is not guarded by #ifndef NDEBUG because a separate + * Frees a lexer. This is not guarded by #if BC_DEBUG 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); +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); +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. + * @param l The lexer. + * @param text The text to lex. + * @param mode The mode to lex in. */ -void bc_lex_text(BcLex *l, const char *text, bool is_stdin); +void +bc_lex_text(BcLex* l, const char* text, BcMode mode); /** * 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); +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); +void +bc_lex_lineComment(BcLex* l); /** * Lexes a general comment (C-style comment). * @param l The lexer. */ -void bc_lex_comment(BcLex *l); +void +bc_lex_comment(BcLex* l); /** * Lexes whitespace, finding as much as possible. * @param l The lexer. */ -void bc_lex_whitespace(BcLex *l); +void +bc_lex_whitespace(BcLex* l); /** * Lexes a number that begins with char @a start. This takes care of parsing @@ -555,32 +598,37 @@ void bc_lex_whitespace(BcLex *l); * 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); +void +bc_lex_number(BcLex* l, char start); /** * Lexes a name/identifier. * @param l The lexer. */ -void bc_lex_name(BcLex *l); +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); +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); +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. + * @param l The lexer. */ -bool bc_lex_readLine(BcLex *l); +bool +bc_lex_readLine(BcLex* l); #endif // BC_LEX_H diff --git a/contrib/bc/include/library.h b/contrib/bc/include/library.h index 8a055eb8106..9942705a5f3 100644 --- a/contrib/bc/include/library.h +++ b/contrib/bc/include/library.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -36,138 +36,256 @@ #ifndef LIBBC_PRIVATE_H #define LIBBC_PRIVATE_H +#ifndef _WIN32 + +#include + +#endif // _WIN32 + #include #include +#include + +#if BC_ENABLE_MEMCHECK + +/** + * A typedef for Valgrind builds. This is to add a generation index for error + * checking. + */ +typedef struct BclNum +{ + /// The number. + BcNum n; + + /// The generation index. + size_t gen_idx; + +} BclNum; + +/** + * Clears the generation byte in a BclNumber and returns the value. + * @param n The BclNumber. + * @return The value of the index. + */ +#define BCL_NO_GEN(n) \ + ((n).i & ~(((size_t) UCHAR_MAX) << ((sizeof(size_t) - 1) * CHAR_BIT))) + +/** + * Gets the generation index in a BclNumber. + * @param n The BclNumber. + * @return The generation index. + */ +#define BCL_GET_GEN(n) ((n).i >> ((sizeof(size_t) - 1) * CHAR_BIT)) /** - * A header for functions that need to lock and setjmp(). It also sets the - * variable that tells bcl that it is running. - * @param l The label to jump to on error. + * Turns a BclNumber into a BcNum. + * @param c The context. + * @param n The BclNumber. */ -#define BC_FUNC_HEADER_LOCK(l) \ - do { \ - BC_SIG_LOCK; \ - BC_SETJMP_LOCKED(l); \ - vm.err = BCL_ERROR_NONE; \ - vm.running = 1; \ - } while (0) +#define BCL_NUM(c, n) ((BclNum*) bc_vec_item(&(c)->nums, BCL_NO_GEN(n))) /** - * A footer to unlock and stop the jumping if an error happened. It also sets - * the variable that tells bcl that it is running. - * @param e The error variable to set. + * Clears the generation index top byte in the BclNumber. + * @param n The BclNumber. */ -#define BC_FUNC_FOOTER_UNLOCK(e) \ - do { \ - BC_SIG_ASSERT_LOCKED; \ - e = vm.err; \ - vm.running = 0; \ - BC_UNSETJMP; \ - BC_LONGJMP_STOP; \ - vm.sig_lock = 0; \ - } while (0) +#define BCL_CLEAR_GEN(n) \ + do \ + { \ + (n).i &= ~(((size_t) UCHAR_MAX) << ((sizeof(size_t) - 1) * CHAR_BIT)); \ + } \ + while (0) + +#define BCL_CHECK_NUM_GEN(c, bn) \ + do \ + { \ + size_t gen_ = BCL_GET_GEN(bn); \ + BclNum* ptr_ = BCL_NUM(c, bn); \ + if (BCL_NUM_ARRAY(ptr_) == NULL) \ + { \ + bcl_nonexistentNum(); \ + } \ + if (gen_ != ptr_->gen_idx) \ + { \ + bcl_invalidGeneration(); \ + } \ + } \ + while (0) + +#define BCL_CHECK_NUM_VALID(c, bn) \ + do \ + { \ + size_t idx_ = BCL_NO_GEN(bn); \ + if ((c)->nums.len <= idx_) \ + { \ + bcl_numIdxOutOfRange(); \ + } \ + BCL_CHECK_NUM_GEN(c, bn); \ + } \ + while (0) /** - * A header that sets a jump and sets running. - * @param l The label to jump to on error. + * Returns the limb array of the number. + * @param bn The number. + * @return The limb array. */ -#define BC_FUNC_HEADER(l) \ - do { \ - BC_SETJMP(l); \ - vm.err = BCL_ERROR_NONE; \ - vm.running = 1; \ - } while (0) +#define BCL_NUM_ARRAY(bn) ((bn)->n.num) /** - * A header that assumes that signals are already locked. It sets a jump and - * running. - * @param l The label to jump to on error. + * Returns the limb array of the number for a non-pointer. + * @param bn The number. + * @return The limb array. */ -#define BC_FUNC_HEADER_INIT(l) \ - do { \ - BC_SETJMP_LOCKED(l); \ - vm.err = BCL_ERROR_NONE; \ - vm.running = 1; \ - } while (0) +#define BCL_NUM_ARRAY_NP(bn) ((bn).n.num) /** - * A footer for functions that do not return an error code. It clears running - * and unlocks the signals. It also stops the jumping. + * Returns the BcNum pointer. + * @param bn The number. + * @return The BcNum pointer. */ -#define BC_FUNC_FOOTER_NO_ERR \ - do { \ - vm.running = 0; \ - BC_UNSETJMP; \ - BC_LONGJMP_STOP; \ - vm.sig_lock = 0; \ - } while (0) +#define BCL_NUM_NUM(bn) (&(bn)->n) /** - * A footer for functions that *do* return an error code. It clears running and - * unlocks the signals. It also stops the jumping. - * @param e The error variable to set. + * Returns the BcNum pointer for a non-pointer. + * @param bn The number. + * @return The BcNum pointer. */ -#define BC_FUNC_FOOTER(e) \ - do { \ - e = vm.err; \ - BC_FUNC_FOOTER_NO_ERR; \ - } while (0) +#define BCL_NUM_NUM_NP(bn) (&(bn).n) + +// These functions only abort. They exist to give developers some idea of what +// went wrong when bugs are found, if they look at the Valgrind stack trace. + +BC_NORETURN void +bcl_invalidGeneration(void); + +BC_NORETURN void +bcl_nonexistentNum(void); + +BC_NORETURN void +bcl_numIdxOutOfRange(void); + +#else // BC_ENABLE_MEMCHECK + +/** + * A typedef for non-Valgrind builds. + */ +typedef BcNum BclNum; + +#define BCL_NO_GEN(n) ((n).i) +#define BCL_NUM(c, n) ((BclNum*) bc_vec_item(&(c)->nums, (n).i)) +#define BCL_CLEAR_GEN(n) ((void) (n)) + +#define BCL_CHECK_NUM_GEN(c, bn) +#define BCL_CHECK_NUM_VALID(c, n) + +#define BCL_NUM_ARRAY(bn) ((bn)->num) +#define BCL_NUM_ARRAY_NP(bn) ((bn).num) + +#define BCL_NUM_NUM(bn) (bn) +#define BCL_NUM_NUM_NP(bn) (&(bn)) + +#endif // BC_ENABLE_MEMCHECK + +/** + * A header that sets a jump. + * @param vm The thread data. + * @param l The label to jump to on error. + */ +#define BC_FUNC_HEADER(vm, l) \ + do \ + { \ + BC_SETJMP(vm, l); \ + vm->err = BCL_ERROR_NONE; \ + } \ + while (0) + +/** + * A footer for functions that do not return an error code. + */ +#define BC_FUNC_FOOTER_NO_ERR(vm) \ + do \ + { \ + BC_UNSETJMP(vm); \ + } \ + while (0) + +/** + * A footer for functions that *do* return an error code. + * @param vm The thread data. + * @param e The error variable to set. + */ +#define BC_FUNC_FOOTER(vm, e) \ + do \ + { \ + e = vm->err; \ + BC_FUNC_FOOTER_NO_ERR(vm); \ + } \ + while (0) /** * A footer that sets up n based the value of e and sets up the return value in * idx. * @param c The context. * @param e The error. - * @param n The number. + * @param bn The number. * @param idx The idx to set as the return value. */ -#define BC_MAYBE_SETUP(c, e, n, idx) \ - do { \ - if (BC_ERR((e) != BCL_ERROR_NONE)) { \ - if ((n).num != NULL) bc_num_free(&(n)); \ - idx.i = 0 - (size_t) (e); \ - } \ - else idx = bcl_num_insert(c, &(n)); \ - } while (0) +#define BC_MAYBE_SETUP(c, e, bn, idx) \ + do \ + { \ + if (BC_ERR((e) != BCL_ERROR_NONE)) \ + { \ + if (BCL_NUM_ARRAY_NP(bn) != NULL) bc_num_free(BCL_NUM_NUM_NP(bn)); \ + idx.i = 0 - (size_t) (e); \ + } \ + else idx = bcl_num_insert(c, &(bn)); \ + } \ + while (0) /** * A header to check the context and return an error encoded in a number if it * is bad. * @param c The context. */ -#define BC_CHECK_CTXT(c) \ - do { \ - c = bcl_context(); \ - if (BC_ERR(c == NULL)) { \ - BclNumber n_num; \ - n_num.i = 0 - (size_t) BCL_ERROR_INVALID_CONTEXT; \ - return n_num; \ - } \ - } while (0) - +#define BC_CHECK_CTXT(vm, c) \ + do \ + { \ + c = bcl_contextHelper(vm); \ + if (BC_ERR(c == NULL)) \ + { \ + BclNumber n_num_; \ + n_num_.i = 0 - (size_t) BCL_ERROR_INVALID_CONTEXT; \ + return n_num_; \ + } \ + } \ + while (0) /** * A header to check the context and return an error directly if it is bad. * @param c The context. */ -#define BC_CHECK_CTXT_ERR(c) \ - do { \ - c = bcl_context(); \ - if (BC_ERR(c == NULL)) { \ +#define BC_CHECK_CTXT_ERR(vm, c) \ + do \ + { \ + c = bcl_contextHelper(vm); \ + if (BC_ERR(c == NULL)) \ + { \ return BCL_ERROR_INVALID_CONTEXT; \ } \ - } while (0) + } \ + while (0) /** * A header to check the context and abort if it is bad. * @param c The context. */ -#define BC_CHECK_CTXT_ASSERT(c) \ - do { \ - c = bcl_context(); \ - assert(c != NULL); \ - } while (0) +#define BC_CHECK_CTXT_ASSERT(vm, c) \ + do \ + { \ + c = bcl_contextHelper(vm); \ + assert(c != NULL); \ + } \ + while (0) /** * A header to check the number in the context and return an error encoded as a @@ -176,16 +294,24 @@ * @param n The BclNumber. */ #define BC_CHECK_NUM(c, n) \ - do { \ - if (BC_ERR((n).i >= (c)->nums.len)) { \ + do \ + { \ + size_t no_gen_ = BCL_NO_GEN(n); \ + if (BC_ERR(no_gen_ >= (c)->nums.len)) \ + { \ if ((n).i > 0 - (size_t) BCL_ERROR_NELEMS) return (n); \ - else { \ - BclNumber n_num; \ - n_num.i = 0 - (size_t) BCL_ERROR_INVALID_NUM; \ - return n_num; \ + else \ + { \ + BclNumber n_num_; \ + n_num_.i = 0 - (size_t) BCL_ERROR_INVALID_NUM; \ + return n_num_; \ } \ } \ - } while (0) + BCL_CHECK_NUM_GEN(c, n); \ + } \ + while (0) + +//clang-format off /** * A header to check the number in the context and return an error directly if @@ -194,30 +320,47 @@ * @param n The BclNumber. */ #define BC_CHECK_NUM_ERR(c, n) \ - do { \ - if (BC_ERR((n).i >= (c)->nums.len)) { \ + do \ + { \ + size_t no_gen_ = BCL_NO_GEN(n); \ + if (BC_ERR(no_gen_ >= (c)->nums.len)) \ + { \ if ((n).i > 0 - (size_t) BCL_ERROR_NELEMS) \ + { \ return (BclError) (0 - (n).i); \ + } \ else return BCL_ERROR_INVALID_NUM; \ } \ - } while (0) + BCL_CHECK_NUM_GEN(c, n); \ + } \ + while (0) + +//clang-format on /** - * Turns a BclNumber into a BcNum. + * Grows the context's nums array if necessary. * @param c The context. - * @param n The BclNumber. */ -#define BC_NUM(c, n) ((BcNum*) bc_vec_item(&(c)->nums, (n).i)) +#define BCL_GROW_NUMS(c) \ + do \ + { \ + if ((c)->free_nums.len == 0) \ + { \ + bc_vec_grow(&((c)->nums), 1); \ + } \ + } \ + while (0) /** * Frees a BcNum for bcl. This is a destructor. * @param num The BcNum to free, as a void pointer. */ -void bcl_num_destruct(void *num); +void +bcl_num_destruct(void* num); /// The actual context struct. -typedef struct BclCtxt { - +typedef struct BclCtxt +{ /// The context's scale. size_t scale; @@ -236,4 +379,21 @@ typedef struct BclCtxt { } BclCtxt; +/** + * Returns the @a BcVm for the current thread. + * @return The vm for the current thread. + */ +BcVm* +bcl_getspecific(void); + +#ifndef _WIN32 + +typedef pthread_key_t BclTls; + +#else // _WIN32 + +typedef DWORD BclTls; + +#endif // _WIN32 + #endif // LIBBC_PRIVATE_H diff --git a/contrib/bc/include/num.h b/contrib/bc/include/num.h index bfd360b520f..6cead6eb382 100644 --- a/contrib/bc/include/num.h +++ b/contrib/bc/include/num.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -47,10 +47,6 @@ #include #include -#ifndef BC_ENABLE_EXTRA_MATH -#define BC_ENABLE_EXTRA_MATH (1) -#endif // BC_ENABLE_EXTRA_MATH - /// Everything in bc is base 10.. #define BC_BASE (10) @@ -75,6 +71,10 @@ typedef BclBigDig BcBigDig; /// An alias for portability. #define BC_NUM_BIGDIG_C UINT64_C +/// The max number + 1 that two limbs can hold. This is used for generating +/// numbers because the PRNG can generate a number that will fill two limbs. +#define BC_BASE_RAND_POW (BC_NUM_BIGDIG_C(1000000000000000000)) + /// The actual limb type. typedef int_least32_t BcDig; @@ -92,6 +92,10 @@ typedef int_least32_t BcDig; /// An alias for portability. #define BC_NUM_BIGDIG_C UINT32_C +/// The max number + 1 that two limbs can hold. This is used for generating +/// numbers because the PRNG can generate a number that will fill two limbs. +#define BC_BASE_RAND_POW (UINT64_C(100000000)) + /// The actual limb type. typedef int_least16_t BcDig; @@ -106,12 +110,12 @@ typedef int_least16_t BcDig; #define BC_NUM_DEF_SIZE (8) /// The actual number struct. This is where the magic happens. -typedef struct BcNum { - +typedef struct BcNum +{ /// The limb array. It is restrict because *no* other item should own the /// array. For more information, see the development manual /// (manuals/development.md#numbers). - BcDig *restrict num; + BcDig* restrict num; /// The number of limbs before the decimal (radix) point. This also stores /// the negative bit in the least significant bit since it uses at least two @@ -207,9 +211,9 @@ struct BcRNG; #define BC_NUM_KARATSUBA_ALLOCS (6) /** - * Rounds @a s (scale) up to the next power of BC_BASE_DIGS. This also check for - * overflow and gives a fatal error if that happens because we just can't go - * over the limits we have imposed. + * Rounds @a s (scale) up to the next power of BC_BASE_DIGS. This will also + * check for overflow and gives a fatal error if that happens because we just + * can't go over the limits we have imposed. * @param s The scale to round up. * @return @a s rounded up to the next power of BC_BASE_DIGS. */ @@ -259,8 +263,7 @@ struct BcRNG; * @param v The value to set the rdx to. * @param neg The value to set the negative bit to. */ -#define BC_NUM_RDX_SET_NEG(n, v, neg) \ - ((n)->rdx = (((v) << 1) | (neg))) +#define BC_NUM_RDX_SET_NEG(n, v, neg) ((n)->rdx = (((v) << 1) | (neg))) /** * Returns true if the rdx and scale for @a n match. @@ -350,11 +353,11 @@ struct BcRNG; // These are for debugging only. #if BC_DEBUG_CODE -#define BC_NUM_PRINT(x) fprintf(stderr, "%s = %lu\n", #x, (unsigned long)(x)) +#define BC_NUM_PRINT(x) fprintf(stderr, "%s = %lu\n", #x, (unsigned long) (x)) #define DUMP_NUM bc_num_dump #else // BC_DEBUG_CODE #undef DUMP_NUM -#define DUMP_NUM(x,y) +#define DUMP_NUM(x, y) #define BC_NUM_PRINT(x) #endif // BC_DEBUG_CODE @@ -419,7 +422,8 @@ typedef void (*BcNumShiftAddOp)(BcDig* restrict a, const BcDig* restrict b, * @param n The number to initialize. * @param req The number of limbs @a n must have in its limb array. */ -void bc_num_init(BcNum *restrict n, size_t req); +void +bc_num_init(BcNum* restrict n, size_t req); /** * Initializes (sets up) @a n with the preallocated limb array @a num that has @@ -429,7 +433,8 @@ void bc_num_init(BcNum *restrict n, size_t req); * @param num The preallocated limb array. * @param cap The capacity of @a num. */ -void bc_num_setup(BcNum *restrict n, BcDig *restrict num, size_t cap); +void +bc_num_setup(BcNum* restrict n, BcDig* restrict num, size_t cap); /** * Copies @a s into @a d. This does a deep copy and requires that @a d is @@ -437,7 +442,8 @@ void bc_num_setup(BcNum *restrict n, BcDig *restrict num, size_t cap); * @param d The destination BcNum. * @param s The source BcNum. */ -void bc_num_copy(BcNum *d, const BcNum *s); +void +bc_num_copy(BcNum* d, const BcNum* s); /** * Creates @a d and copies @a s into @a d. This does a deep copy and requires @@ -445,7 +451,8 @@ void bc_num_copy(BcNum *d, const BcNum *s); * @param d The destination BcNum. * @param s The source BcNum. */ -void bc_num_createCopy(BcNum *d, const BcNum *s); +void +bc_num_createCopy(BcNum* d, const BcNum* s); /** * Creates (initializes) @a n and sets its value to the equivalent of @a val. @@ -453,27 +460,31 @@ void bc_num_createCopy(BcNum *d, const BcNum *s); * @param n The number to initialize and set. * @param val The value to set @a n's value to. */ -void bc_num_createFromBigdig(BcNum *restrict n, BcBigDig val); +void +bc_num_createFromBigdig(BcNum* restrict n, BcBigDig val); /** * Makes @a n valid for holding strings. @a n must *not* be allocated; this * simply clears some fields, including setting the num field to NULL. * @param n The number to clear. */ -void bc_num_clear(BcNum *restrict n); +void +bc_num_clear(BcNum* restrict n); /** * Frees @a num, which is a BcNum as a void pointer. This is a destructor. * @param num The BcNum to free as a void pointer. */ -void bc_num_free(void *num); +void +bc_num_free(void* num); /** * Returns the scale of @a n. * @param n The number. * @return The scale of @a n. */ -size_t bc_num_scale(const BcNum *restrict n); +size_t +bc_num_scale(const BcNum* restrict n); /** * Returns the length (in decimal digits) of @a n. This is complicated. First, @@ -483,7 +494,8 @@ size_t bc_num_scale(const BcNum *restrict n); * @param n The number. * @return The length of @a n. */ -size_t bc_num_len(const BcNum *restrict n); +size_t +bc_num_len(const BcNum* restrict n); /** * Convert a number to a BcBigDig (hardware integer). This version does error @@ -492,7 +504,8 @@ size_t bc_num_len(const BcNum *restrict n); * @param n The number to convert. * @return The number as a hardware integer. */ -BcBigDig bc_num_bigdig(const BcNum *restrict n); +BcBigDig +bc_num_bigdig(const BcNum* restrict n); /** * Convert a number to a BcBigDig (hardware integer). This version does no error @@ -500,7 +513,8 @@ BcBigDig bc_num_bigdig(const BcNum *restrict n); * @param n The number to convert. * @return The number as a hardware integer. */ -BcBigDig bc_num_bigdig2(const BcNum *restrict n); +BcBigDig +bc_num_bigdig2(const BcNum* restrict n); /** * Sets @a n to the value of @a val. @a n is expected to be a valid and @@ -508,7 +522,8 @@ BcBigDig bc_num_bigdig2(const BcNum *restrict n); * @param n The number to set. * @param val The value to set the number to. */ -void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val); +void +bc_num_bigdig2num(BcNum* restrict n, BcBigDig val); #if BC_ENABLE_EXTRA_MATH @@ -519,22 +534,24 @@ void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val); * @param b The return value. * @param rng The pseudo-random number generator. */ -void bc_num_irand(BcNum *restrict a, BcNum *restrict b, - struct BcRNG *restrict rng); +void +bc_num_irand(BcNum* restrict a, BcNum* restrict b, struct BcRNG* restrict rng); /** * Sets the seed for the PRNG @a rng from @a n. * @param n The new seed for the PRNG. * @param rng The PRNG to set the seed for. */ -void bc_num_rng(const BcNum *restrict n, struct BcRNG *rng); +void +bc_num_rng(const BcNum* restrict n, struct BcRNG* rng); /** * Sets @a n to the value produced by the PRNG. This implements rand(). * @param n The number to set. * @param rng The pseudo-random number generator. */ -void bc_num_createFromRNG(BcNum *restrict n, struct BcRNG *rng); +void +bc_num_createFromRNG(BcNum* restrict n, struct BcRNG* rng); #endif // BC_ENABLE_EXTRA_MATH @@ -545,7 +562,8 @@ void bc_num_createFromRNG(BcNum *restrict n, struct BcRNG *rng); * @param c The return value. * @param scale The current scale. */ -void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_add(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The subtract function. This is a BcNumBinaryOp function. @@ -554,7 +572,8 @@ void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_sub(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The multiply function. @@ -563,7 +582,8 @@ void bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_mul(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The division function. @@ -572,7 +592,8 @@ void bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_div(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The modulus function. @@ -581,7 +602,8 @@ void bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_mod(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The power function. @@ -590,7 +612,8 @@ void bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_pow(BcNum* a, BcNum* b, BcNum* c, size_t scale); #if BC_ENABLE_EXTRA_MATH /** @@ -600,7 +623,8 @@ void bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_places(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_places(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The left shift function (<< operator). This is a BcNumBinaryOp function. @@ -609,7 +633,8 @@ void bc_num_places(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_lshift(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_lshift(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The right shift function (>> operator). This is a BcNumBinaryOp function. @@ -618,7 +643,8 @@ void bc_num_lshift(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param c The return value. * @param scale The current scale. */ -void bc_num_rshift(BcNum *a, BcNum *b, BcNum *c, size_t scale); +void +bc_num_rshift(BcNum* a, BcNum* b, BcNum* c, size_t scale); #endif // BC_ENABLE_EXTRA_MATH @@ -628,7 +654,8 @@ void bc_num_rshift(BcNum *a, BcNum *b, BcNum *c, size_t scale); * @param b The return value. * @param scale The current scale. */ -void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale); +void +bc_num_sqrt(BcNum* restrict a, BcNum* restrict b, size_t scale); /** * Divsion and modulus together. This is a dc extension. @@ -638,7 +665,8 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale); * @param d The second return value (modulus). * @param scale The current scale. */ -void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale); +void +bc_num_divmod(BcNum* a, BcNum* b, BcNum* c, BcNum* d, size_t scale); /** * A function returning the required allocation size for an addition or a @@ -649,7 +677,8 @@ void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale); * @return The size of allocation needed for the result of add or subtract * with @a a, @a b, and @a scale. */ -size_t bc_num_addReq(const BcNum* a, const BcNum* b, size_t scale); +size_t +bc_num_addReq(const BcNum* a, const BcNum* b, size_t scale); /** * A function returning the required allocation size for a multiplication. This @@ -660,7 +689,8 @@ size_t bc_num_addReq(const BcNum* a, const BcNum* b, size_t scale); * @return The size of allocation needed for the result of multiplication * with @a a, @a b, and @a scale. */ -size_t bc_num_mulReq(const BcNum *a, const BcNum *b, size_t scale); +size_t +bc_num_mulReq(const BcNum* a, const BcNum* b, size_t scale); /** * A function returning the required allocation size for a division or modulus. @@ -671,7 +701,8 @@ size_t bc_num_mulReq(const BcNum *a, const BcNum *b, size_t scale); * @return The size of allocation needed for the result of division or * modulus with @a a, @a b, and @a scale. */ -size_t bc_num_divReq(const BcNum *a, const BcNum *b, size_t scale); +size_t +bc_num_divReq(const BcNum* a, const BcNum* b, size_t scale); /** * A function returning the required allocation size for an exponentiation. This @@ -682,7 +713,8 @@ size_t bc_num_divReq(const BcNum *a, const BcNum *b, size_t scale); * @return The size of allocation needed for the result of exponentiation * with @a a, @a b, and @a scale. */ -size_t bc_num_powReq(const BcNum *a, const BcNum *b, size_t scale); +size_t +bc_num_powReq(const BcNum* a, const BcNum* b, size_t scale); #if BC_ENABLE_EXTRA_MATH @@ -695,7 +727,8 @@ size_t bc_num_powReq(const BcNum *a, const BcNum *b, size_t scale); * @return The size of allocation needed for the result of places, left * shift, or right shift with @a a, @a b, and @a scale. */ -size_t bc_num_placesReq(const BcNum *a, const BcNum *b, size_t scale); +size_t +bc_num_placesReq(const BcNum* a, const BcNum* b, size_t scale); #endif // BC_ENABLE_EXTRA_MATH @@ -705,7 +738,8 @@ size_t bc_num_placesReq(const BcNum *a, const BcNum *b, size_t scale); * @param n The number to truncate. * @param places The number of places to truncate @a n by. */ -void bc_num_truncate(BcNum *restrict n, size_t places); +void +bc_num_truncate(BcNum* restrict n, size_t places); /** * Extend @a n *by* @a places decimal places. This only extends places *after* @@ -713,7 +747,8 @@ void bc_num_truncate(BcNum *restrict n, size_t places); * @param n The number to truncate. * @param places The number of places to extend @a n by. */ -void bc_num_extend(BcNum *restrict n, size_t places); +void +bc_num_extend(BcNum* restrict n, size_t places); /** * Shifts @a n right by @a places decimal places. This is the workhorse of the @@ -722,7 +757,8 @@ void bc_num_extend(BcNum *restrict n, size_t places); * @param n The number to shift right. * @param places The number of decimal places to shift @a n right by. */ -void bc_num_shiftRight(BcNum *restrict n, size_t places); +void +bc_num_shiftRight(BcNum* restrict n, size_t places); /** * Compare a and b and return the result of their comparison as an ssize_t. @@ -732,7 +768,8 @@ void bc_num_shiftRight(BcNum *restrict n, size_t places); * @param b The second number. * @return The result of the comparison. */ -ssize_t bc_num_cmp(const BcNum *a, const BcNum *b); +ssize_t +bc_num_cmp(const BcNum* a, const BcNum* b); /** * Modular exponentiation. @@ -741,28 +778,30 @@ ssize_t bc_num_cmp(const BcNum *a, const BcNum *b); * @param c The third parameter. * @param d The return value. */ -void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d); +void +bc_num_modexp(BcNum* a, BcNum* b, BcNum* c, BcNum* restrict d); /** * Sets @a n to zero with a scale of zero. * @param n The number to zero. */ -void bc_num_zero(BcNum *restrict n); +void +bc_num_zero(BcNum* restrict n); /** * Sets @a n to one with a scale of zero. * @param n The number to set to one. */ -void bc_num_one(BcNum *restrict n); +void +bc_num_one(BcNum* restrict n); /** * An efficient function to compare @a n to zero. * @param n The number to compare to zero. * @return The result of the comparison. */ -ssize_t bc_num_cmpZero(const BcNum *n); - -#if !defined(NDEBUG) || BC_ENABLE_LIBRARY +ssize_t +bc_num_cmpZero(const BcNum* n); /** * Check a number string for validity and return true if it is, false otherwise. @@ -772,9 +811,8 @@ ssize_t bc_num_cmpZero(const BcNum *n); * @param val The string to check. * @return True if the string is a valid number, false otherwise. */ -bool bc_num_strValid(const char *restrict val); - -#endif // !defined(NDEBUG) || BC_ENABLE_LIBRARY +bool +bc_num_strValid(const char* restrict val); /** * Parses a number string into the number @a n according to @a base. @@ -782,7 +820,8 @@ bool bc_num_strValid(const char *restrict val); * @param val The number string to parse. * @param base The base to parse the number string by. */ -void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base); +void +bc_num_parse(BcNum* restrict n, const char* restrict val, BcBigDig base); /** * Prints the number @a n according to @a base. @@ -791,7 +830,16 @@ void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base); * @param newline True if a newline should be inserted at the end, false * otherwise. */ -void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline); +void +bc_num_print(BcNum* restrict n, BcBigDig base, bool newline); + +/** + * 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. + */ +#define bc_num_inv(a, b, scale) bc_num_div(&vm->one, (a), (b), (scale)) #if !BC_ENABLE_LIBRARY @@ -799,7 +847,8 @@ void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline); * Prints a number as a character stream. * @param n The number to print as a character stream. */ -void bc_num_stream(BcNum *restrict n); +void +bc_num_stream(BcNum* restrict n); #endif // !BC_ENABLE_LIBRARY @@ -811,7 +860,8 @@ void bc_num_stream(BcNum *restrict n); * @param name The label to print the number with. * @param emptyline True if there should be an empty line after the number. */ -void bc_num_printDebug(const BcNum *n, const char *name, bool emptyline); +void +bc_num_printDebug(const BcNum* n, const char* name, bool emptyline); /** * Print the limbs of @a n. This is a debug-only function. @@ -819,7 +869,8 @@ void bc_num_printDebug(const BcNum *n, const char *name, bool emptyline); * @param len The length of the number. * @param emptyline True if there should be an empty line after the number. */ -void bc_num_printDigs(const BcDig* n, size_t len, bool emptyline); +void +bc_num_printDigs(const BcDig* n, size_t len, bool emptyline); /** * Print debug info about @a n along with its limbs. @@ -827,14 +878,16 @@ void bc_num_printDigs(const BcDig* n, size_t len, bool emptyline); * @param name The label to print the number with. * @param emptyline True if there should be an empty line after the number. */ -void bc_num_printWithDigs(const BcNum *n, const char *name, bool emptyline); +void +bc_num_printWithDigs(const BcNum* n, const char* name, bool emptyline); /** * Dump debug info about a BcNum variable. * @param varname The variable name. * @param n The number. */ -void bc_num_dump(const char *varname, const BcNum *n); +void +bc_num_dump(const char* varname, const BcNum* n); #endif // BC_DEBUG_CODE @@ -842,7 +895,7 @@ void bc_num_dump(const char *varname, const BcNum *n); extern const char bc_num_hex_digits[]; /// An array of powers of 10 for easy conversion from number of digits to -//powers. +/// powers. extern const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1]; /// A reference to a constant array that is the max of a BigDig. diff --git a/contrib/bc/include/opt.h b/contrib/bc/include/opt.h index cffe6368223..41058cb4e29 100644 --- a/contrib/bc/include/opt.h +++ b/contrib/bc/include/opt.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -44,10 +44,10 @@ #include /// The data required to parse command-line arguments. -typedef struct BcOpt { - +typedef struct BcOpt +{ /// The array of arguments. - char **argv; + const char** argv; /// The index of the current argument. size_t optind; @@ -59,13 +59,13 @@ typedef struct BcOpt { int subopt; /// The option argument. - char *optarg; + const char* optarg; } BcOpt; /// The types of arguments. This is specially adapted for bc. -typedef enum BcOptType { - +typedef enum BcOptType +{ /// No argument required. BC_OPT_NONE, @@ -84,10 +84,10 @@ typedef enum BcOptType { } BcOptType; /// A struct to hold const data for long options. -typedef struct BcOptLong { - +typedef struct BcOptLong +{ /// The name of the option. - const char *name; + const char* name; /// The type of the option. BcOptType type; @@ -102,7 +102,8 @@ typedef struct BcOptLong { * @param o The option data to initialize. * @param argv The array of arguments. */ -void bc_opt_init(BcOpt *o, char **argv); +void +bc_opt_init(BcOpt* o, const char** argv); /** * Parse an option. This returns a value the same way getopt() and getopt_long() @@ -111,7 +112,8 @@ void bc_opt_init(BcOpt *o, char **argv); * @param longopts The long options. * @return A character for the parsed option, or -1 if done. */ -int bc_opt_parse(BcOpt *o, const BcOptLong *longopts); +int +bc_opt_parse(BcOpt* o, const BcOptLong* longopts); /** * Returns true if the option is `--` and not a long option. diff --git a/contrib/bc/include/ossfuzz.h b/contrib/bc/include/ossfuzz.h new file mode 100644 index 00000000000..5c12a3c9c9f --- /dev/null +++ b/contrib/bc/include/ossfuzz.h @@ -0,0 +1,79 @@ +/* + * ***************************************************************************** + * + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2018-2024 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. + * + * ***************************************************************************** + * + * Declarations for the OSS-Fuzz build of bc and dc. + * + */ + +#include +#include + +#ifndef BC_OSSFUZZ_H +#define BC_OSSFUZZ_H + +/// The number of args in fuzzer arguments, including the NULL terminator. +extern const size_t bc_fuzzer_args_len; + +/// The standard arguments for the bc fuzzer with the -c argument. +extern const char* bc_fuzzer_args_c[]; + +/// The standard arguments for the bc fuzzer with the -C argument. +extern const char* bc_fuzzer_args_C[]; + +/// The standard arguments for the dc fuzzer with the -c argument. +extern const char* dc_fuzzer_args_c[]; + +/// The standard arguments for the dc fuzzer with the -C argument. +extern const char* dc_fuzzer_args_C[]; + +/// The data pointer. +extern uint8_t* bc_fuzzer_data; + +/** + * The function that the fuzzer runs. + * @param Data The data. + * @param Size The number of bytes in @a Data. + * @return 0 on success, -1 on error. + * @pre @a Data must not be equal to NULL if @a Size > 0. + */ +int +LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size); + +/** + * The initialization function for the fuzzer. + * @param argc A pointer to the argument count. + * @param argv A pointer to the argument list. + * @return 0 on success, -1 on error. + */ +int +LLVMFuzzerInitialize(int* argc, char*** argv); + +#endif // BC_OSSFUZZ_H diff --git a/contrib/bc/include/parse.h b/contrib/bc/include/parse.h index 0088c1523ec..7f0f8768b0d 100644 --- a/contrib/bc/include/parse.h +++ b/contrib/bc/include/parse.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -53,23 +53,24 @@ /// loops, while loops, and if statements. This is because POSIX requires that /// certain operators are *only* used in those cases. It's whacked, but that's /// how it is. -#define BC_PARSE_REL (UINTMAX_C(1)<<0) +#define BC_PARSE_REL (UINTMAX_C(1) << 0) /// A flag that requires that the expression is valid for a print statement. -#define BC_PARSE_PRINT (UINTMAX_C(1)<<1) +#define BC_PARSE_PRINT (UINTMAX_C(1) << 1) /// A flag that requires that the expression does *not* have any function call. -#define BC_PARSE_NOCALL (UINTMAX_C(1)<<2) +#define BC_PARSE_NOCALL (UINTMAX_C(1) << 2) -/// A flag that requires that the expression does *not* have a read() expression. -#define BC_PARSE_NOREAD (UINTMAX_C(1)<<3) +/// A flag that requires that the expression does *not* have a read() +/// expression. +#define BC_PARSE_NOREAD (UINTMAX_C(1) << 3) /// A flag that *allows* (rather than requires) that an array appear in the /// expression. This is mostly used as parameters in bc. -#define BC_PARSE_ARRAY (UINTMAX_C(1)<<4) +#define BC_PARSE_ARRAY (UINTMAX_C(1) << 4) /// A flag that requires that the expression is not empty and returns a value. -#define BC_PARSE_NEEDVAL (UINTMAX_C(1)<<5) +#define BC_PARSE_NEEDVAL (UINTMAX_C(1) << 5) /** * Returns true if the parser has been initialized. @@ -79,18 +80,6 @@ */ #define BC_PARSE_IS_INITED(p, prg) ((p)->prog == (prg)) -#if BC_ENABLED - -/** - * Returns true if the current parser state allows parsing, false otherwise. - * @param p The parser. - * @return True if parsing can proceed, false otherwise. - */ -#define BC_PARSE_CAN_PARSE(p) \ - ((p).l.t != BC_LEX_EOF && (p).l.t != BC_LEX_KW_DEFINE) - -#else // BC_ENABLED - /** * Returns true if the current parser state allows parsing, false otherwise. * @param p The parser. @@ -98,8 +87,6 @@ */ #define BC_PARSE_CAN_PARSE(p) ((p).l.t != BC_LEX_EOF) -#endif // BC_ENABLED - /** * Pushes the instruction @a i onto the bytecode vector for the current * function. @@ -118,22 +105,32 @@ #define bc_parse_pushIndex(p, idx) (bc_vec_pushIndex(&(p)->func->code, (idx))) /** - * A convenience macro for throwing errors in parse code. They take care of + * A convenience macro for throwing errors in parse code. This takes care of * plumbing like passing in the current line the lexer is on. * @param p The parser. * @param e The error. */ +#if BC_DEBUG +#define bc_parse_err(p, e) \ + (bc_vm_handleError((e), __FILE__, __LINE__, (p)->l.line)) +#else // BC_DEBUG #define bc_parse_err(p, e) (bc_vm_handleError((e), (p)->l.line)) +#endif // BC_DEBUG /** - * A convenience macro for throwing errors in parse code. They take care of + * A convenience macro for throwing errors in parse code. This takes care of * plumbing like passing in the current line the lexer is on. * @param p The parser. * @param e The error. * @param ... The varags that are needed. */ +#if BC_DEBUG +#define bc_parse_verr(p, e, ...) \ + (bc_vm_handleError((e), __FILE__, __LINE__, (p)->l.line, __VA_ARGS__)) +#else // BC_DEBUG #define bc_parse_verr(p, e, ...) \ (bc_vm_handleError((e), (p)->l.line, __VA_ARGS__)) +#endif // BC_DEBUG // Forward declarations. struct BcParse; @@ -154,8 +151,8 @@ typedef void (*BcParseParse)(struct BcParse* p); typedef void (*BcParseExpr)(struct BcParse* p, uint8_t flags); /// The parser struct. -typedef struct BcParse { - +typedef struct BcParse +{ /// The lexer. BcLex l; @@ -191,11 +188,11 @@ typedef struct BcParse { #endif // BC_ENABLED /// A reference to the program to grab the current function when necessary. - struct BcProgram *prog; + struct BcProgram* prog; /// A reference to the current function. The function is what holds the /// bytecode vector that the parser is filling. - BcFunc *func; + BcFunc* func; /// The index of the function. size_t fidx; @@ -214,40 +211,46 @@ typedef struct BcParse { * @param prog A referenc to the program. * @param func The index of the current function. */ -void bc_parse_init(BcParse *p, struct BcProgram *prog, size_t func); +void +bc_parse_init(BcParse* p, struct BcProgram* prog, size_t func); /** - * Frees a parser. This is not guarded by #ifndef NDEBUG because a separate + * Frees a parser. This is not guarded by #if BC_DEBUG because a separate * parser is created at runtime to parse read() expressions and dc strings. * @param p The parser to free. */ -void bc_parse_free(BcParse *p); +void +bc_parse_free(BcParse* p); /** * Resets the parser. Resetting means erasing all state to the point that the * parser would think it was just initialized. * @param p The parser to reset. */ -void bc_parse_reset(BcParse *p); +void +bc_parse_reset(BcParse* p); /** * Adds a string. See @a BcProgram in include/program.h for more details. * @param p The parser that parsed the string. */ -void bc_parse_addString(BcParse *p); +void +bc_parse_addString(BcParse* p); /** * Adds a number. See @a BcProgram in include/program.h for more details. * @param p The parser that parsed the number. */ -void bc_parse_number(BcParse *p); +void +bc_parse_number(BcParse* p); /** * Update the current function in the parser. * @param p The parser. * @param fidx The index of the new function. */ -void bc_parse_updateFunc(BcParse *p, size_t fidx); +void +bc_parse_updateFunc(BcParse* p, size_t fidx); /** * Adds a new variable or array. See @a BcProgram in include/program.h for more @@ -256,15 +259,17 @@ void bc_parse_updateFunc(BcParse *p, size_t fidx); * @param name The name of the variable or array to add. * @param var True if the name is for a variable, false if it's for an array. */ -void bc_parse_pushName(const BcParse* p, char *name, bool var); +void +bc_parse_pushName(const BcParse* p, char* name, bool var); /** * Sets the text that the parser will parse. - * @param p The parser. - * @param text The text to lex. - * @param is_stdin True if the text is from stdin, false otherwise. + * @param p The parser. + * @param text The text to lex. + * @param mode The mode to parse in. */ -void bc_parse_text(BcParse *p, const char *text, bool is_stdin); +void +bc_parse_text(BcParse* p, const char* text, BcMode mode); // References to const 0 and 1 strings for special cases. bc and dc have // specific instructions for 0 and 1 because they pop up so often and (in the diff --git a/contrib/bc/include/program.h b/contrib/bc/include/program.h index 3f90f2b9f55..e16e5c079d7 100644 --- a/contrib/bc/include/program.h +++ b/contrib/bc/include/program.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -64,13 +64,15 @@ /// The length of the globals array. #define BC_PROG_GLOBALS_LEN (3 + BC_ENABLE_EXTRA_MATH) -typedef struct BcProgram { - +typedef struct BcProgram +{ /// The array of globals values. BcBigDig globals[BC_PROG_GLOBALS_LEN]; +#if BC_ENABLED /// The array of globals stacks. BcVec globals_v[BC_PROG_GLOBALS_LEN]; +#endif // BC_ENABLED #if BC_ENABLE_EXTRA_MATH @@ -85,11 +87,21 @@ typedef struct BcProgram { /// The execution stack. BcVec stack; - /// A pointer to the current function's constants. - BcVec *consts; + /// The constants encountered in the program. They are global to the program + /// to prevent bad accesses when functions that used non-auto variables are + /// replaced. + BcVec consts; + + /// The map of constants to go with consts. + BcVec const_map; - /// A pointer to the current function's strings. - BcVec *strs; + /// The strings encountered in the program. They are global to the program + /// to prevent bad accesses when functions that used non-auto variables are + /// replaced. + BcVec strs; + + /// The map of strings to go with strs. + BcVec str_map; /// The array of functions. BcVec fns; @@ -122,6 +134,10 @@ typedef struct BcProgram { /// A BcNum that has the proper base for asciify. BcNum strmb; + // A BcNum to run asciify. This is to prevent GCC longjmp() clobbering + // warnings. + BcNum asciify; + #if BC_ENABLED /// The last printed value for bc. @@ -204,26 +220,36 @@ typedef struct BcProgram { #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) +/// Returns true if the calculator should pop after printing. +#define BC_PROGRAM_POP(pop) (pop) + +#else // !BC_ENABLED + +/// Returns true if the calculator should pop after printing. +#define BC_PROGRAM_POP(pop) (BC_IS_BC || (pop)) #endif // !BC_ENABLED +// This is here to satisfy a clang warning about recursive macros. +#define bc_program_pushVar(p, code, bgn, pop, copy) \ + bc_program_pushVar_impl(p, code, bgn, pop, copy) + #else // DC_ENABLED -/// This define disappears pop and copy because for bc, 'pop' and 'copy' are -/// always false. +// 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) + bc_program_pushVar_impl(p, code, bgn) + +/// Returns true if the calculator should pop after printing. +#define BC_PROGRAM_POP(pop) (BC_IS_BC) // 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 +#ifdef BC_DEBUG #define BC_PROG_NO_STACK_CHECK -#endif // NDEBUG +#endif // BC_DEBUG #endif // DC_ENABLED @@ -263,15 +289,16 @@ typedef struct BcProgram { * @param r The BcResult to store the result into. * @param n The parameter to the unary operation. */ -typedef void (*BcProgramUnary)(BcResult *r, BcNum *n); +typedef void (*BcProgramUnary)(BcResult* r, BcNum* n); /** * Initializes the BcProgram. * @param p The program to initialize. */ -void bc_program_init(BcProgram *p); +void +bc_program_init(BcProgram* p); -#ifndef NDEBUG +#if BC_DEBUG /** * Frees a BcProgram. This is only used in debug builds because a BcProgram is @@ -279,9 +306,17 @@ void bc_program_init(BcProgram *p); * exit. * @param p The program to initialize. */ -void bc_program_free(BcProgram *p); +void +bc_program_free(BcProgram* p); + +#endif // BC_DEBUG -#endif // NDEBUG +/** + * Prints a stack trace of the bc functions or dc strings currently executing. + * @param p The program. + */ +void +bc_program_printStackTrace(BcProgram* p); #if BC_DEBUG_CODE #if BC_ENABLED && DC_ENABLED @@ -290,7 +325,8 @@ void bc_program_free(BcProgram *p); * Prints the bytecode in a function. This is a debug-only function. * @param p The program. */ -void bc_program_code(const BcProgram *p); +void +bc_program_code(const BcProgram* p); /** * Prints an instruction. This is a debug-only function. @@ -299,34 +335,38 @@ void bc_program_code(const BcProgram *p); * @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); +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); +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. + * @param p The program. + * @param name The name 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); +size_t +bc_program_search(BcProgram* p, const char* name, 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. + * Adds a string to the program and returns the string's index in the program. + * @param p The program. + * @param str The string to add. + * @return The string's index in the program. */ -size_t bc_program_addString(BcProgram *p, const char *str, size_t fidx); +size_t +bc_program_addString(BcProgram* p, const char* str); /** * Inserts a function into the program and returns the index of the function in @@ -335,33 +375,38 @@ size_t bc_program_addString(BcProgram *p, const char *str, size_t fidx); * @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); +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); +void +bc_program_reset(BcProgram* p); /** * Executes bc or dc code in the BcProgram. * @param p The program. */ -void bc_program_exec(BcProgram *p); +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); +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); +void +bc_program_not(BcResult* r, BcNum* n); #if BC_ENABLE_EXTRA_MATH @@ -370,10 +415,30 @@ void bc_program_not(BcResult *r, BcNum *n); * @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); +void +bc_program_trunc(BcResult* r, BcNum* n); + +/** + * Assigns a value to the seed builtin variable. + * @param p The program. + * @param val The value to assign to the seed. + */ +void +bc_program_assignSeed(BcProgram* p, BcNum* val); #endif // BC_ENABLE_EXTRA_MATH +/** + * Assigns a value to a builtin value that is not seed. + * @param p The program. + * @param scale True if the builtin is scale. + * @param obase True if the builtin is obase. This cannot be true at the same + * time @a scale is. + * @param val The value to assign to the builtin. + */ +void +bc_program_assignBuiltin(BcProgram* p, bool scale, bool obase, BcBigDig val); + /// A reference to an array of binary operator functions. extern const BcNumBinaryOp bc_program_ops[]; @@ -406,34 +471,42 @@ extern const char bc_program_esc_seqs[]; #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) +// clang-format off +#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) +// clang-format on #else // BC_DEBUG_CODE +// clang-format off #define BC_PROG_JUMP(inst, code, ip) \ - do { \ + do \ + { \ inst = (uchar) (code)[(ip)->idx++]; \ goto *bc_program_inst_lbls[inst]; \ - } while (0) + } \ + while (0) +// clang-format on #endif // BC_DEBUG_CODE -#define BC_PROG_DIRECT_JUMP(l) goto lbl_ ## l; -#define BC_PROG_LBL(l) lbl_ ## l +#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") +#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 @@ -447,197 +520,205 @@ extern const char bc_program_esc_seqs[]; #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, \ -} +#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_IS_NUMBER, \ + &&lbl_BC_INST_IS_STRING, \ + &&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_EXTENDED_REGISTERS, \ + &&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, \ -} +#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_IS_NUMBER, \ + &&lbl_BC_INST_IS_STRING, \ + &&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_EXTENDED_REGISTERS, \ + &&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 @@ -645,169 +726,175 @@ extern const char bc_program_esc_seqs[]; #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, \ -} +#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_IS_NUMBER, \ + &&lbl_BC_INST_IS_STRING, \ + &&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, \ -} +#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_IS_NUMBER, \ + &&lbl_BC_INST_IS_STRING, \ + &&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 @@ -817,141 +904,83 @@ extern const char bc_program_esc_seqs[]; #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, \ -} +#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_IS_NUMBER, \ + &&lbl_BC_INST_IS_STRING, &&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_EXTENDED_REGISTERS, \ + &&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, \ -} +#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_IS_NUMBER, &&lbl_BC_INST_IS_STRING, \ + &&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_EXTENDED_REGISTERS, \ + &&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 diff --git a/contrib/bc/include/rand.h b/contrib/bc/include/rand.h index 58eb2cf0e32..aee63b866cf 100644 --- a/contrib/bc/include/rand.h +++ b/contrib/bc/include/rand.h @@ -13,7 +13,7 @@ * This code is under the following license: * * Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 Gavin D. Howard and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -53,11 +53,11 @@ #if BC_ENABLE_LIBRARY #define BC_RAND_USE_FREE (1) #else // BC_ENABLE_LIBRARY -#ifndef NDEBUG +#if BC_DEBUG #define BC_RAND_USE_FREE (1) -#else // NDEBUG +#else // BC_DEBUG #define BC_RAND_USE_FREE (0) -#endif // NDEBUG +#endif // BC_DEBUG #endif // BC_ENABLE_LIBRARY /** @@ -65,7 +65,7 @@ * @param ptr A void ptr to some data that will help generate the random ulong. * @return The random ulong. */ -typedef ulong (*BcRandUlong)(void *ptr); +typedef ulong (*BcRandUlong)(void* ptr); #if BC_LONG_BIT >= 64 @@ -178,8 +178,8 @@ typedef __uint128_t BcRandState; #else // BC_RAND_BUILTIN /// A typedef for the PCG state. -typedef struct BcRandState { - +typedef struct BcRandState +{ /// The low bits. uint_fast64_t lo; @@ -272,7 +272,7 @@ typedef struct BcRandState { * @param n The integer to truncate. * @return The bottom 32 bits of @a n. */ -#define BC_RAND_TRUNC32(n) ((n) & BC_RAND_BOTTOM32) +#define BC_RAND_TRUNC32(n) ((n) & (BC_RAND_BOTTOM32)) /** * Returns the second 32 bits of @a n. @@ -419,8 +419,8 @@ typedef uint_fast64_t BcRandState; #define BC_RAND_SRAND_BITS ((1 << CHAR_BIT) - 1) /// The actual RNG data. These are the actual PRNG's. -typedef struct BcRNGData { - +typedef struct BcRNGData +{ /// The state. BcRandState state; @@ -431,8 +431,8 @@ typedef struct BcRNGData { /// The public PRNG. This is just a stack of PRNG's to maintain the globals /// stack illusion. -typedef struct BcRNG { - +typedef struct BcRNG +{ /// The stack of PRNG's. BcVec v; @@ -442,7 +442,8 @@ typedef struct BcRNG { * Initializes a BcRNG. * @param r The BcRNG to initialize. */ -void bc_rand_init(BcRNG *r); +void +bc_rand_init(BcRNG* r); #if BC_RAND_USE_FREE @@ -451,7 +452,8 @@ void bc_rand_init(BcRNG *r); * exit. * @param r The BcRNG to free. */ -void bc_rand_free(BcRNG *r); +void +bc_rand_free(BcRNG* r); #endif // BC_RAND_USE_FREE @@ -460,7 +462,8 @@ void bc_rand_free(BcRNG *r); * @param r The PRNG. * @return A random integer. */ -BcRand bc_rand_int(BcRNG *r); +BcRand +bc_rand_int(BcRNG* r); /** * Returns a random integer from the PRNG bounded by @a bound. Bias is @@ -469,7 +472,8 @@ BcRand bc_rand_int(BcRNG *r); * @param bound The bound for the random integer. * @return A bounded random integer. */ -BcRand bc_rand_bounded(BcRNG *r, BcRand bound); +BcRand +bc_rand_bounded(BcRNG* r, BcRand bound); /** * Seed the PRNG with the state in two parts and the increment in two parts. @@ -479,13 +483,15 @@ BcRand bc_rand_bounded(BcRNG *r, BcRand bound); * @param inc1 The first part of the increment. * @param inc2 The second part of the increment. */ -void bc_rand_seed(BcRNG *r, ulong state1, ulong state2, ulong inc1, ulong inc2); +void +bc_rand_seed(BcRNG* r, ulong state1, ulong state2, ulong inc1, ulong inc2); /** * Pushes a new PRNG onto the PRNG stack. * @param r The PRNG. */ -void bc_rand_push(BcRNG *r); +void +bc_rand_push(BcRNG* r); /** * Pops one or all but one items off of the PRNG stack. @@ -493,7 +499,8 @@ void bc_rand_push(BcRNG *r); * @param reset True if all but one PRNG should be popped off the stack, false * if only one should be popped. */ -void bc_rand_pop(BcRNG *r, bool reset); +void +bc_rand_pop(BcRNG* r, bool reset); /** * Returns, via pointers, the state of the PRNG in pieces. @@ -503,13 +510,15 @@ void bc_rand_pop(BcRNG *r, bool reset); * @param i1 The return value for the first part of the increment. * @param i2 The return value for the second part of the increment. */ -void bc_rand_getRands(BcRNG *r, BcRand *s1, BcRand *s2, BcRand *i1, BcRand *i2); +void +bc_rand_getRands(BcRNG* r, BcRand* s1, BcRand* s2, BcRand* i1, BcRand* i2); /** * Seed the PRNG with random data. * @param rng The PRNG. */ -void bc_rand_srand(BcRNGData *rng); +void +bc_rand_srand(BcRNGData* rng); /// A reference to a constant multiplier. extern const BcRandState bc_rand_multiplier; diff --git a/contrib/bc/include/read.h b/contrib/bc/include/read.h index 2ebb456e83f..62e6897635a 100644 --- a/contrib/bc/include/read.h +++ b/contrib/bc/include/read.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -53,14 +53,16 @@ * @param vec The vector to put the stdin data into. * @param prompt The prompt to print, if desired. */ -BcStatus bc_read_line(BcVec *vec, const char *prompt); +BcStatus +bc_read_line(BcVec* vec, const char* prompt); /** * Read a file and return a buffer with the data. The buffer must be freed by * the caller. * @param path The path to the file to read. */ -char* bc_read_file(const char *path); +char* +bc_read_file(const char* path); /** * Helper function for reading characters from stdin. This takes care of a bunch @@ -69,7 +71,8 @@ char* bc_read_file(const char *path); * @param vec The vec to put the stdin into. * @param prompt The prompt to print, if desired. */ -BcStatus bc_read_chars(BcVec *vec, const char *prompt); +BcStatus +bc_read_chars(BcVec* vec, const char* prompt); /** * Read a line from buf into vec. @@ -77,6 +80,7 @@ BcStatus bc_read_chars(BcVec *vec, const char *prompt); * @param buf The buffer to read from. * @param buf_len The length of the buffer. */ -bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len); +bool +bc_read_buf(BcVec* vec, char* buf, size_t* buf_len); #endif // BC_READ_H diff --git a/contrib/bc/include/status.h b/contrib/bc/include/status.h index 662f2b89c04..203f09af628 100644 --- a/contrib/bc/include/status.h +++ b/contrib/bc/include/status.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -36,14 +36,48 @@ #ifndef BC_STATUS_H #define BC_STATUS_H +#ifdef _WIN32 +#include +#include +#include +#include +#endif // _WIN32 + #include +#include -// This is used by configure.sh to test for OpenBSD. -#ifdef BC_TEST_OPENBSD -#ifdef __OpenBSD__ -#error On OpenBSD without _BSD_SOURCE -#endif // __OpenBSD__ -#endif // BC_TEST_OPENBSD +// 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) | _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 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 #ifndef BC_ENABLED #define BC_ENABLED (1) @@ -53,10 +87,46 @@ #define DC_ENABLED (1) #endif // DC_ENABLED +#ifndef BC_ENABLE_EXTRA_MATH +#define BC_ENABLE_EXTRA_MATH (1) +#endif // BC_ENABLE_EXTRA_MATH + #ifndef BC_ENABLE_LIBRARY #define BC_ENABLE_LIBRARY (0) #endif // BC_ENABLE_LIBRARY +#ifndef BC_ENABLE_HISTORY +#define BC_ENABLE_HISTORY (1) +#endif // BC_ENABLE_HISTORY + +#ifndef BC_ENABLE_EDITLINE +#define BC_ENABLE_EDITLINE (0) +#endif // BC_ENABLE_EDITLINE + +#ifndef BC_ENABLE_READLINE +#define BC_ENABLE_READLINE (0) +#endif // BC_ENABLE_READLINE + +#ifndef BC_ENABLE_NLS +#define BC_ENABLE_NLS (0) +#endif // BC_ENABLE_NLS + +#ifdef __OpenBSD__ +#if BC_ENABLE_READLINE +#error Cannot use readline on OpenBSD +#endif // BC_ENABLE_READLINE +#endif // __OpenBSD__ + +#if BC_ENABLE_EDITLINE && BC_ENABLE_READLINE +#error Must enable only one of editline or readline, not both. +#endif // BC_ENABLE_EDITLINE && BC_ENABLE_READLINE + +#if BC_ENABLE_EDITLINE || BC_ENABLE_READLINE +#define BC_ENABLE_LINE_LIB (1) +#else // BC_ENABLE_EDITLINE || BC_ENABLE_READLINE +#define BC_ENABLE_LINE_LIB (0) +#endif // BC_ENABLE_EDITLINE || BC_ENABLE_READLINE + // This is error checking for fuzz builds. #if BC_ENABLE_AFL #ifndef __AFL_HAVE_MANUAL_CONTROL @@ -115,8 +185,20 @@ #define BC_DEBUG_CODE (0) #endif // BC_DEBUG_CODE +#if defined(__clang__) +#define BC_CLANG (1) +#else // defined(__clang__) +#define BC_CLANG (0) +#endif // defined(__clang__) + +#if defined(__GNUC__) && !BC_CLANG +#define BC_GCC (1) +#else // defined(__GNUC__) && !BC_CLANG +#define BC_GCC (0) +#endif // defined(__GNUC__) && !BC_CLANG + // We want to be able to use _Noreturn on C11 compilers. -#if __STDC_VERSION__ >= 201100L +#if __STDC_VERSION__ >= 201112L #include #define BC_NORETURN _Noreturn @@ -124,7 +206,19 @@ #else // __STDC_VERSION__ +#if BC_CLANG +#if __has_attribute(noreturn) +#define BC_NORETURN __attribute((noreturn)) +#else // __has_attribute(noreturn) #define BC_NORETURN +#endif // __has_attribute(noreturn) + +#else // BC_CLANG + +#define BC_NORETURN + +#endif // BC_CLANG + #define BC_MUST_RETURN #define BC_C11 (0) @@ -136,7 +230,7 @@ // GCC and Clang complain if fallthroughs are not marked with their special // attribute. Jerks. This creates a define for marking the fallthroughs that is // nothing on other compilers. -#if defined(__clang__) || defined(__GNUC__) +#if BC_CLANG || BC_GCC #if defined(__has_attribute) @@ -146,28 +240,28 @@ #define BC_FALLTHROUGH #endif // __has_attribute(fallthrough) -#ifdef __GNUC__ +#if BC_GCC #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) #undef BC_HAS_UNREACHABLE #define BC_HAS_UNREACHABLE (1) #endif // __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -#else // __GNUC__ +#else // BC_GCC #if __clang_major__ >= 4 #undef BC_HAS_UNREACHABLE #define BC_HAS_UNREACHABLE (1) #endif // __clang_major__ >= 4 -#endif // __GNUC__ +#endif // BC_GCC #else // defined(__has_attribute) #define BC_FALLTHROUGH #endif // defined(__has_attribute) -#else // defined(__clang__) || defined(__GNUC__) +#else // BC_CLANG || BC_GCC #define BC_FALLTHROUGH -#endif // defined(__clang__) || defined(__GNUC__) +#endif // BC_CLANG || BC_GCC #if BC_HAS_UNREACHABLE @@ -187,7 +281,7 @@ #endif // BC_HAS_UNREACHABLE -#ifdef __GNUC__ +#if BC_GCC #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) @@ -196,9 +290,9 @@ #endif // __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -#endif // __GNUC__ +#endif // BC_GCC -#ifdef __clang__ +#if BC_CLANG #if __clang_major__ >= 4 @@ -207,7 +301,7 @@ #endif // __clang_major__ >= 4 -#endif // __GNUC__ +#endif // BC_CLANG #ifdef BC_NO_COMPUTED_GOTO @@ -216,12 +310,12 @@ #endif // BC_NO_COMPUTED_GOTO -#ifdef __GNUC__ +#if BC_GCC #ifdef __OpenBSD__ // The OpenBSD GCC doesn't like inline. #define inline #endif // __OpenBSD__ -#endif // __GNUC__ +#endif // BC_GCC // Workarounds for AIX's POSIX incompatibility. #ifndef SIZE_MAX @@ -268,6 +362,14 @@ #define BC_DEFAULT_PROMPT BC_DEFAULT_TTY_MODE #endif // BC_DEFAULT_PROMPT +#ifndef BC_DEFAULT_EXPR_EXIT +#define BC_DEFAULT_EXPR_EXIT (1) +#endif // BC_DEFAULT_EXPR_EXIT + +#ifndef BC_DEFAULT_DIGIT_CLAMP +#define BC_DEFAULT_DIGIT_CLAMP (0) +#endif // BC_DEFAULT_DIGIT_CLAMP + // All of these set defaults for settings. #ifndef DC_DEFAULT_SIGINT_RESET #define DC_DEFAULT_SIGINT_RESET (1) @@ -285,10 +387,18 @@ #define DC_DEFAULT_PROMPT DC_DEFAULT_TTY_MODE #endif // DC_DEFAULT_PROMPT +#ifndef DC_DEFAULT_EXPR_EXIT +#define DC_DEFAULT_EXPR_EXIT (1) +#endif // DC_DEFAULT_EXPR_EXIT + +#ifndef DC_DEFAULT_DIGIT_CLAMP +#define DC_DEFAULT_DIGIT_CLAMP (0) +#endif // DC_DEFAULT_DIGIT_CLAMP + /// Statuses, which mark either which category of error happened, or some other /// status that matters. -typedef enum BcStatus { - +typedef enum BcStatus +{ /// Normal status. BC_STATUS_SUCCESS = 0, @@ -313,8 +423,8 @@ typedef enum BcStatus { } BcStatus; /// Errors, which are more specific errors. -typedef enum BcErr { - +typedef enum BcErr +{ // Math errors. /// Negative number used when not allowed. @@ -393,7 +503,7 @@ typedef enum BcErr { /// Void value used in an expression error. BC_ERR_EXEC_VOID_VAL, - // Parse (and lex errors). + // Parse (and lex) errors. /// EOF encountered when not expected error. BC_ERR_PARSE_EOF, @@ -472,6 +582,10 @@ typedef enum BcErr { /// Empty statements in POSIX for loop error. BC_ERR_POSIX_FOR, + /// POSIX's grammar does not allow a function definition right after a + /// semicolon. + BC_ERR_POSIX_FUNC_AFTER_SEMICOLON, + /// Non-POSIX exponential (scientific or engineering) number used error. BC_ERR_POSIX_EXP_NUM, @@ -530,6 +644,26 @@ typedef enum BcErr { #endif // BC_ENABLED +/** + * The mode bc is in. This is basically what input it is processing. + */ +typedef enum BcMode +{ + /// Expressions mode. + BC_MODE_EXPRS, + + /// File mode. + BC_MODE_FILE, + +#if !BC_ENABLE_OSSFUZZ + + /// stdin mode. + BC_MODE_STDIN, + +#endif // !BC_ENABLE_OSSFUZZ + +} BcMode; + /// Do a longjmp(). This is what to use when activating an "exception", i.e., a /// longjmp(). With debug code, it will print the name of the function it jumped /// from. @@ -539,29 +673,48 @@ typedef enum BcErr { #define BC_JMP bc_vm_jmp() #endif // BC_DEBUG_CODE +#if !BC_ENABLE_LIBRARY + /// Returns true if an exception is in flight, false otherwise. -#define BC_SIG_EXC \ - BC_UNLIKELY(vm.status != (sig_atomic_t) BC_STATUS_SUCCESS || vm.sig) +#define BC_SIG_EXC(vm) \ + BC_UNLIKELY((vm)->status != (sig_atomic_t) BC_STATUS_SUCCESS || (vm)->sig) /// Returns true if there is *no* exception in flight, false otherwise. -#define BC_NO_SIG_EXC \ - BC_LIKELY(vm.status == (sig_atomic_t) BC_STATUS_SUCCESS && !vm.sig) +#define BC_NO_SIG_EXC(vm) \ + BC_LIKELY((vm)->status == (sig_atomic_t) BC_STATUS_SUCCESS && !(vm)->sig) + +#ifndef _WIN32 +#define BC_SIG_INTERRUPT(vm) \ + BC_UNLIKELY((vm)->sig != 0 && (vm)->sig != SIGWINCH) +#else // _WIN32 +#define BC_SIG_INTERRUPT(vm) BC_UNLIKELY((vm)->sig != 0) +#endif // _WIN32 -#ifndef NDEBUG +#if BC_DEBUG /// Assert that signals are locked. There are non-async-signal-safe functions in /// bc, and they *must* have signals locked. Other functions are expected to /// *not* have signals locked, for reasons. So this is a pre-built assert /// (no-op in non-debug mode) that check that signals are locked. -#define BC_SIG_ASSERT_LOCKED do { assert(vm.sig_lock); } while (0) +#define BC_SIG_ASSERT_LOCKED \ + do \ + { \ + assert(vm->sig_lock); \ + } \ + while (0) /// Assert that signals are unlocked. There are non-async-signal-safe functions /// in bc, and they *must* have signals locked. Other functions are expected to /// *not* have signals locked, for reasons. So this is a pre-built assert /// (no-op in non-debug mode) that check that signals are unlocked. -#define BC_SIG_ASSERT_NOT_LOCKED do { assert(vm.sig_lock == 0); } while (0) +#define BC_SIG_ASSERT_NOT_LOCKED \ + do \ + { \ + assert(vm->sig_lock == 0); \ + } \ + while (0) -#else // NDEBUG +#else // BC_DEBUG /// Assert that signals are locked. There are non-async-signal-safe functions in /// bc, and they *must* have signals locked. Other functions are expected to @@ -575,83 +728,84 @@ typedef enum BcErr { /// (no-op in non-debug mode) that check that signals are unlocked. #define BC_SIG_ASSERT_NOT_LOCKED -#endif // NDEBUG +#endif // BC_DEBUG /// Locks signals. #define BC_SIG_LOCK \ - do { \ + do \ + { \ BC_SIG_ASSERT_NOT_LOCKED; \ - vm.sig_lock = 1; \ - } while (0) + vm->sig_lock = 1; \ + } \ + while (0) /// Unlocks signals. If a signal happened, then this will cause a jump. #define BC_SIG_UNLOCK \ - do { \ + do \ + { \ BC_SIG_ASSERT_LOCKED; \ - vm.sig_lock = 0; \ - if (vm.sig) BC_JMP; \ - } while (0) + vm->sig_lock = 0; \ + if (vm->sig) BC_JMP; \ + } \ + while (0) /// Locks signals, regardless of if they are already locked. This is really only /// used after labels that longjmp() goes to after the jump because the cleanup /// code must have signals locked, and BC_LONGJMP_CONT will unlock signals if it /// doesn't jump. -#define BC_SIG_MAYLOCK \ - do { \ - vm.sig_lock = 1; \ - } while (0) +#define BC_SIG_MAYLOCK \ + do \ + { \ + vm->sig_lock = 1; \ + } \ + while (0) /// Unlocks signals, regardless of if they were already unlocked. If a signal /// happened, then this will cause a jump. -#define BC_SIG_MAYUNLOCK \ - do { \ - vm.sig_lock = 0; \ - if (vm.sig) BC_JMP; \ - } while (0) +#define BC_SIG_MAYUNLOCK \ + do \ + { \ + vm->sig_lock = 0; \ + if (vm->sig) BC_JMP; \ + } \ + while (0) -/* +/** * Locks signals, but stores the old lock state, to be restored later by * BC_SIG_TRYUNLOCK. * @param v The variable to store the old lock state to. */ #define BC_SIG_TRYLOCK(v) \ - do { \ - v = vm.sig_lock; \ - vm.sig_lock = 1; \ - } while (0) + do \ + { \ + v = vm->sig_lock; \ + vm->sig_lock = 1; \ + } \ + while (0) -/* Restores the previous state of a signal lock, and if it is now unlocked, +/** + * Restores the previous state of a signal lock, and if it is now unlocked, * initiates an exception/jump. * @param v The old lock state. */ -#define BC_SIG_TRYUNLOCK(v) \ - do { \ - vm.sig_lock = (v); \ - if (!(v) && vm.sig) BC_JMP; \ - } while (0) +#define BC_SIG_TRYUNLOCK(v) \ + do \ + { \ + vm->sig_lock = (v); \ + if (!(v) && vm->sig) BC_JMP; \ + } \ + while (0) -/** - * Sets a jump, and sets it up as well so that if a longjmp() happens, bc will - * immediately goto a label where some cleanup code is. This one assumes that - * signals are not locked and will lock them, set the jump, and unlock them. - * Setting the jump also includes pushing the jmp_buf onto the jmp_buf stack. - * This grows the jmp_bufs vector first to prevent a fatal error from happening - * after the setjmp(). This is done because BC_SETJMP(l) is assumed to be used - * *before* the actual initialization calls that need the setjmp(). - * param l The label to jump to on a longjmp(). - */ -#define BC_SETJMP(l) \ - do { \ - sigjmp_buf sjb; \ - BC_SIG_LOCK; \ - bc_vec_grow(&vm.jmp_bufs, 1); \ - if (sigsetjmp(sjb, 0)) { \ - assert(BC_SIG_EXC); \ - goto l; \ - } \ - bc_vec_push(&vm.jmp_bufs, &sjb); \ - BC_SIG_UNLOCK; \ - } while (0) +/// Stops a stack unwinding. Technically, a stack unwinding needs to be done +/// manually, but it will always be done unless certain flags are cleared. This +/// clears the flags. +#define BC_LONGJMP_STOP \ + do \ + { \ + vm->sig_pop = 0; \ + vm->sig = 0; \ + } \ + while (0) /** * Sets a jump like BC_SETJMP, but unlike BC_SETJMP, it assumes signals are @@ -660,50 +814,108 @@ typedef enum BcErr { * the initializations that need the setjmp(). * param l The label to jump to on a longjmp(). */ -#define BC_SETJMP_LOCKED(l) \ - do { \ - sigjmp_buf sjb; \ - BC_SIG_ASSERT_LOCKED; \ - if (sigsetjmp(sjb, 0)) { \ - assert(BC_SIG_EXC); \ - goto l; \ - } \ - bc_vec_push(&vm.jmp_bufs, &sjb); \ - } while (0) +#define BC_SETJMP_LOCKED(vm, l) \ + do \ + { \ + sigjmp_buf sjb; \ + BC_SIG_ASSERT_LOCKED; \ + if (sigsetjmp(sjb, 0)) \ + { \ + assert(BC_SIG_EXC(vm)); \ + goto l; \ + } \ + bc_vec_push(&vm->jmp_bufs, &sjb); \ + } \ + while (0) /// Used after cleanup labels set by BC_SETJMP and BC_SETJMP_LOCKED to jump to /// the next place. This is what continues the stack unwinding. This basically /// copies BC_SIG_UNLOCK into itself, but that is because its condition for /// jumping is BC_SIG_EXC, not just that a signal happened. -#define BC_LONGJMP_CONT \ - do { \ - BC_SIG_ASSERT_LOCKED; \ - if (!vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); \ - vm.sig_lock = 0; \ - if (BC_SIG_EXC) BC_JMP; \ - } while (0) +#define BC_LONGJMP_CONT(vm) \ + do \ + { \ + BC_SIG_ASSERT_LOCKED; \ + if (!vm->sig_pop) bc_vec_pop(&vm->jmp_bufs); \ + vm->sig_lock = 0; \ + if (BC_SIG_EXC(vm)) BC_JMP; \ + } \ + while (0) + +#else // !BC_ENABLE_LIBRARY + +#define BC_SIG_LOCK +#define BC_SIG_UNLOCK +#define BC_SIG_MAYLOCK +#define BC_SIG_TRYLOCK(lock) +#define BC_SIG_TRYUNLOCK(lock) +#define BC_SIG_ASSERT_LOCKED + +/// Returns true if an exception is in flight, false otherwise. +#define BC_SIG_EXC(vm) \ + BC_UNLIKELY(vm->status != (sig_atomic_t) BC_STATUS_SUCCESS) + +/// Returns true if there is *no* exception in flight, false otherwise. +#define BC_NO_SIG_EXC(vm) \ + BC_LIKELY(vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) + +/// Used after cleanup labels set by BC_SETJMP and BC_SETJMP_LOCKED to jump to +/// the next place. This is what continues the stack unwinding. This basically +/// copies BC_SIG_UNLOCK into itself, but that is because its condition for +/// jumping is BC_SIG_EXC, not just that a signal happened. +#define BC_LONGJMP_CONT(vm) \ + do \ + { \ + bc_vec_pop(&vm->jmp_bufs); \ + if (BC_SIG_EXC(vm)) BC_JMP; \ + } \ + while (0) + +#endif // !BC_ENABLE_LIBRARY + +/** + * Sets a jump, and sets it up as well so that if a longjmp() happens, bc will + * immediately goto a label where some cleanup code is. This one assumes that + * signals are not locked and will lock them, set the jump, and unlock them. + * Setting the jump also includes pushing the jmp_buf onto the jmp_buf stack. + * This grows the jmp_bufs vector first to prevent a fatal error from happening + * after the setjmp(). This is done because BC_SETJMP(l) is assumed to be used + * *before* the actual initialization calls that need the setjmp(). + * param l The label to jump to on a longjmp(). + */ +#define BC_SETJMP(vm, l) \ + do \ + { \ + sigjmp_buf sjb; \ + BC_SIG_LOCK; \ + bc_vec_grow(&vm->jmp_bufs, 1); \ + if (sigsetjmp(sjb, 0)) \ + { \ + assert(BC_SIG_EXC(vm)); \ + goto l; \ + } \ + bc_vec_push(&vm->jmp_bufs, &sjb); \ + BC_SIG_UNLOCK; \ + } \ + while (0) /// Unsets a jump. It always assumes signals are locked. This basically just /// pops a jmp_buf off of the stack of jmp_bufs, and since the jump mechanism /// always jumps to the location at the top of the stack, this effectively /// undoes a setjmp(). -#define BC_UNSETJMP \ - do { \ - BC_SIG_ASSERT_LOCKED; \ - bc_vec_pop(&vm.jmp_bufs); \ - } while (0) +#define BC_UNSETJMP(vm) \ + do \ + { \ + BC_SIG_ASSERT_LOCKED; \ + bc_vec_pop(&vm->jmp_bufs); \ + } \ + while (0) -/// Stops a stack unwinding. Technically, a stack unwinding needs to be done -/// manually, but it will always be done unless certain flags are cleared. This -/// clears the flags. -#define BC_LONGJMP_STOP \ - do { \ - vm.sig_pop = 0; \ - vm.sig = 0; \ - } while (0) +#if BC_ENABLE_LIBRARY + +#define BC_SETJMP_LOCKED(vm, l) BC_SETJMP(vm, l) // Various convenience macros for calling the bc's error handling routine. -#if BC_ENABLE_LIBRARY /** * Call bc's error handling routine. @@ -727,25 +939,41 @@ typedef enum BcErr { #else // BC_ENABLE_LIBRARY +// Various convenience macros for calling the bc's error handling routine. + /** * Call bc's error handling routine. * @param e The error. * @param l The line of the script that the error happened. * @param ... Extra arguments for error messages as necessary. */ +#if BC_DEBUG +#define bc_error(e, l, ...) \ + (bc_vm_handleError((e), __FILE__, __LINE__, (l), __VA_ARGS__)) +#else // BC_DEBUG #define bc_error(e, l, ...) (bc_vm_handleError((e), (l), __VA_ARGS__)) +#endif // BC_DEBUG /** * Call bc's error handling routine. * @param e The error. */ +#if BC_DEBUG +#define bc_err(e) (bc_vm_handleError((e), __FILE__, __LINE__, 0)) +#else // BC_DEBUG #define bc_err(e) (bc_vm_handleError((e), 0)) +#endif // BC_DEBUG /** * Call bc's error handling routine. * @param e The error. */ +#if BC_DEBUG +#define bc_verr(e, ...) \ + (bc_vm_handleError((e), __FILE__, __LINE__, 0, __VA_ARGS__)) +#else // BC_DEBUG #define bc_verr(e, ...) (bc_vm_handleError((e), 0, __VA_ARGS__)) +#endif // BC_DEBUG #endif // BC_ENABLE_LIBRARY @@ -760,31 +988,35 @@ typedef enum BcErr { // Convenience macros that can be placed at the beginning and exits of functions // for easy marking of where functions are entered and exited. #if BC_DEBUG_CODE -#define BC_FUNC_ENTER \ - do { \ - size_t bc_func_enter_i; \ - for (bc_func_enter_i = 0; bc_func_enter_i < vm.func_depth; \ - ++bc_func_enter_i) \ - { \ - bc_file_puts(&vm.ferr, bc_flush_none, " "); \ - } \ - vm.func_depth += 1; \ - bc_file_printf(&vm.ferr, "Entering %s\n", __func__); \ - bc_file_flush(&vm.ferr, bc_flush_none); \ - } while (0); - -#define BC_FUNC_EXIT \ - do { \ - size_t bc_func_enter_i; \ - vm.func_depth -= 1; \ - for (bc_func_enter_i = 0; bc_func_enter_i < vm.func_depth; \ - ++bc_func_enter_i) \ - { \ - bc_file_puts(&vm.ferr, bc_flush_none, " "); \ - } \ - bc_file_printf(&vm.ferr, "Leaving %s\n", __func__); \ - bc_file_flush(&vm.ferr, bc_flush_none); \ - } while (0); +#define BC_FUNC_ENTER \ + do \ + { \ + size_t bc_func_enter_i; \ + for (bc_func_enter_i = 0; bc_func_enter_i < vm->func_depth; \ + ++bc_func_enter_i) \ + { \ + bc_file_puts(&vm->ferr, bc_flush_none, " "); \ + } \ + vm->func_depth += 1; \ + bc_file_printf(&vm->ferr, "Entering %s\n", __func__); \ + bc_file_flush(&vm->ferr, bc_flush_none); \ + } \ + while (0); + +#define BC_FUNC_EXIT \ + do \ + { \ + size_t bc_func_enter_i; \ + vm->func_depth -= 1; \ + for (bc_func_enter_i = 0; bc_func_enter_i < vm->func_depth; \ + ++bc_func_enter_i) \ + { \ + bc_file_puts(&vm->ferr, bc_flush_none, " "); \ + } \ + bc_file_printf(&vm->ferr, "Leaving %s\n", __func__); \ + bc_file_flush(&vm->ferr, bc_flush_none); \ + } \ + while (0); #else // BC_DEBUG_CODE #define BC_FUNC_ENTER #define BC_FUNC_EXIT diff --git a/contrib/bc/include/vector.h b/contrib/bc/include/vector.h index c35d22c9eff..cad5fc2aa7c 100644 --- a/contrib/bc/include/vector.h +++ b/contrib/bc/include/vector.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -47,7 +47,7 @@ /// The starting capacity for vectors. This is based on the minimum allocation /// for 64-bit systems. -#define BC_VEC_START_CAP (UINTMAX_C(1)<<5) +#define BC_VEC_START_CAP (UINTMAX_C(1) << 5) /// An alias. typedef unsigned char uchar; @@ -57,10 +57,7 @@ typedef unsigned char uchar; * to free the memory they own. * @param ptr Pointer to the data to free. */ -typedef void (*BcVecFree)(void *ptr); - -// Forward declaration. -struct BcId; +typedef void (*BcVecFree)(void* ptr); #if BC_LONG_BIT >= 64 @@ -75,8 +72,8 @@ typedef uint16_t BcSize; #endif // BC_LONG_BIT >= 64 /// An enum of all of the destructors. We use an enum to save space. -typedef enum BcDtorType { - +typedef enum BcDtorType +{ /// No destructor needed. BC_DTOR_NONE, @@ -88,12 +85,12 @@ typedef enum BcDtorType { #if !BC_ENABLE_LIBRARY -#ifndef NDEBUG +#if BC_DEBUG /// BcFunc destructor. BC_DTOR_FUNC, -#endif // NDEBUG +#endif // BC_DEBUG /// BcSlab destructor. BC_DTOR_SLAB, @@ -120,11 +117,11 @@ typedef enum BcDtorType { } BcDtorType; /// The actual vector struct. -typedef struct BcVec { - +typedef struct BcVec +{ /// The vector array itself. This uses a char* because it is compatible with /// pointers of all other types, and I can do pointer arithmetic on it. - char *restrict v; + char* restrict v; /// The length of the vector, which is how many items actually exist. size_t len; @@ -147,7 +144,8 @@ typedef struct BcVec { * @param esize The size of the elements, as returned by sizeof(). * @param dtor The destructor of the elements, as a BcDtorType enum. */ -void bc_vec_init(BcVec *restrict v, size_t esize, BcDtorType dtor); +void +bc_vec_init(BcVec* restrict v, size_t esize, BcDtorType dtor); /** * Expands the vector to have a capacity of @a req items, if it doesn't have @@ -155,14 +153,16 @@ void bc_vec_init(BcVec *restrict v, size_t esize, BcDtorType dtor); * @param v The vector to expand. * @param req The requested capacity. */ -void bc_vec_expand(BcVec *restrict v, size_t req); +void +bc_vec_expand(BcVec* restrict v, size_t req); /** * Grow a vector by at least @a n elements. * @param v The vector to grow. * @param n The number of elements to grow the vector by. */ -void bc_vec_grow(BcVec *restrict v, size_t n); +void +bc_vec_grow(BcVec* restrict v, size_t n); /** * Pops @a n items off the back of the vector. The vector must have at least @@ -170,7 +170,8 @@ void bc_vec_grow(BcVec *restrict v, size_t n); * @param v The vector to pop off of. * @param n The number of elements to pop off. */ -void bc_vec_npop(BcVec *restrict v, size_t n); +void +bc_vec_npop(BcVec* restrict v, size_t n); /** * Pops @a n items, starting at index @a idx, off the vector. The vector must @@ -180,7 +181,8 @@ void bc_vec_npop(BcVec *restrict v, size_t n); * @param n The number of elements to pop off. * @param idx The index to start popping at. */ -void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx); +void +bc_vec_npopAt(BcVec* restrict v, size_t n, size_t idx); /** * Pushes one item on the back of the vector. It does a memcpy(), but it assumes @@ -188,7 +190,8 @@ void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx); * @param v The vector to push onto. * @param data A pointer to the data to push. */ -void bc_vec_push(BcVec *restrict v, const void *data); +void +bc_vec_push(BcVec* restrict v, const void* data); /** * Pushes @a n items on the back of the vector. It does a memcpy(), but it @@ -196,7 +199,8 @@ void bc_vec_push(BcVec *restrict v, const void *data); * @param v The vector to push onto. * @param data A pointer to the elements of data to push. */ -void bc_vec_npush(BcVec *restrict v, size_t n, const void *data); +void +bc_vec_npush(BcVec* restrict v, size_t n, const void* data); /** * Push an empty element and return a pointer to it. This is done as an @@ -205,7 +209,8 @@ void bc_vec_npush(BcVec *restrict v, size_t n, const void *data); * @param v The vector to push onto. * @return A pointer to the newly-pushed element. */ -void* bc_vec_pushEmpty(BcVec *restrict v); +void* +bc_vec_pushEmpty(BcVec* restrict v); /** * Pushes a byte onto a bytecode vector. This is a convenience function for the @@ -213,7 +218,8 @@ void* bc_vec_pushEmpty(BcVec *restrict v); * @param v The vector to push onto. * @param data The byte to push. */ -void bc_vec_pushByte(BcVec *restrict v, uchar data); +void +bc_vec_pushByte(BcVec* restrict v, uchar data); /** * Pushes and index onto a bytecode vector. The vector must be a bytecode @@ -222,7 +228,8 @@ void bc_vec_pushByte(BcVec *restrict v, uchar data); * @param v The vector to push onto. * @param idx The index to push. */ -void bc_vec_pushIndex(BcVec *restrict v, size_t idx); +void +bc_vec_pushIndex(BcVec* restrict v, size_t idx); /** * Push an item onto the vector at a certain index. The index must be valid @@ -233,7 +240,8 @@ void bc_vec_pushIndex(BcVec *restrict v, size_t idx); * @param data A pointer to the data to push. * @param idx The index to push at. */ -void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx); +void +bc_vec_pushAt(BcVec* restrict v, const void* data, size_t idx); /** * Empties the vector and sets it to the string. The vector must be a valid @@ -243,7 +251,8 @@ void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx); * of the string, but must never be more. * @param str The string to push. */ -void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str); +void +bc_vec_string(BcVec* restrict v, size_t len, const char* restrict str); /** * Appends the string to the end of the vector, which must be holding a string @@ -251,13 +260,15 @@ void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str); * @param v The vector to append to. * @param str The string to append (by copying). */ -void bc_vec_concat(BcVec *restrict v, const char *restrict str); +void +bc_vec_concat(BcVec* restrict v, const char* restrict str); /** * Empties a vector and pushes a nul-byte at the first index. The vector must be * a char vector. */ -void bc_vec_empty(BcVec *restrict v); +void +bc_vec_empty(BcVec* restrict v); #if BC_ENABLE_HISTORY @@ -268,7 +279,8 @@ void bc_vec_empty(BcVec *restrict v); * @param idx The index of the item to replace. * @param data The data to replace the item with. */ -void bc_vec_replaceAt(BcVec *restrict v, size_t idx, const void *data); +void +bc_vec_replaceAt(BcVec* restrict v, size_t idx, const void* data); #endif // BC_ENABLE_HISTORY @@ -279,7 +291,8 @@ void bc_vec_replaceAt(BcVec *restrict v, size_t idx, const void *data); * @param idx The index to the item to get a pointer to. * @return A pointer to the item at @a idx. */ -void* bc_vec_item(const BcVec *restrict v, size_t idx); +void* +bc_vec_item(const BcVec* restrict v, size_t idx); /** * Returns a pointer to the item in the vector at the index, reversed. This is @@ -288,22 +301,25 @@ void* bc_vec_item(const BcVec *restrict v, size_t idx); * @param idx The index to the item to get a pointer to. * @return A pointer to the item at len - @a idx - 1. */ -void* bc_vec_item_rev(const BcVec *restrict v, size_t idx); +void* +bc_vec_item_rev(const BcVec* restrict v, size_t idx); /** * Zeros a vector. The vector must not be allocated. * @param v The vector to clear. */ -void bc_vec_clear(BcVec *restrict v); +void +bc_vec_clear(BcVec* restrict v); /** * Frees a vector and its elements. This is a destructor. * @param vec A vector as a void pointer. */ -void bc_vec_free(void *vec); +void +bc_vec_free(void* vec); /** - * Attempts to insert an item into a map and returns true if it succeeded, false + * Attempts to insert an ID into a map and returns true if it succeeded, false * if the item already exists. * @param v The map vector to insert into. * @param name The name of the item to insert. This name is assumed to be owned @@ -313,8 +329,9 @@ void bc_vec_free(void *vec); * in the map. * @return True if the item was inserted, false if the item already exists. */ -bool bc_map_insert(BcVec *restrict v, const char *name, - size_t idx, size_t *restrict i); +bool +bc_map_insert(BcVec* restrict v, const char* name, size_t idx, + size_t* restrict i); /** * Returns the index of the item with @a name in the map, or BC_VEC_INVALID_IDX @@ -324,7 +341,8 @@ bool bc_map_insert(BcVec *restrict v, const char *name, * @return The index in the map of the item with @a name, or * BC_VEC_INVALID_IDX if the item does not exist. */ -size_t bc_map_index(const BcVec *restrict v, const char *name); +size_t +bc_map_index(const BcVec* restrict v, const char* name); #if DC_ENABLED @@ -334,7 +352,8 @@ size_t bc_map_index(const BcVec *restrict v, const char *name); * @param idx The index. * @return The name of the item at @a idx. */ -const char* bc_map_name(const BcVec *restrict v, size_t idx); +const char* +bc_map_name(const BcVec* restrict v, size_t idx); #endif // DC_ENABLED @@ -372,10 +391,10 @@ extern const BcVecFree bc_vec_dtors[]; #define BC_SLAB_SIZE (4096) /// A slab for allocating strings. -typedef struct BcSlab { - +typedef struct BcSlab +{ /// The actual allocation. - char *s; + char* s; /// How many bytes of the slab are taken. size_t len; @@ -386,13 +405,15 @@ typedef struct BcSlab { * Frees a slab. This is a destructor. * @param slab The slab as a void pointer. */ -void bc_slab_free(void *slab); +void +bc_slab_free(void* slab); /** * Initializes a slab vector. * @param v The vector to initialize. */ -void bc_slabvec_init(BcVec *restrict v); +void +bc_slabvec_init(BcVec* restrict v); /** * Duplicates the string using slabs in the slab vector. @@ -400,24 +421,16 @@ void bc_slabvec_init(BcVec *restrict v); * @param str The string to duplicate. * @return A pointer to the duplicated string, owned by the slab vector. */ -char* bc_slabvec_strdup(BcVec *restrict v, const char *str); - -#if BC_ENABLED - -/** - * Undoes the last allocation on the slab vector. This allows bc to have a - * heap-based stacks for strings. This is used by the bc parser. - */ -void bc_slabvec_undo(BcVec *restrict v, size_t len); - -#endif // BC_ENABLED +char* +bc_slabvec_strdup(BcVec* restrict v, const char* str); /** * Clears a slab vector. This deallocates all but the first slab and clears the * first slab. * @param v The slab vector to clear. */ -void bc_slabvec_clear(BcVec *restrict v); +void +bc_slabvec_clear(BcVec* restrict v); #if BC_DEBUG_CODE @@ -425,7 +438,8 @@ void bc_slabvec_clear(BcVec *restrict v); * Prints all of the items in a slab vector, in order. * @param v The vector whose items will be printed. */ -void bc_slabvec_print(BcVec *v, const char *func); +void +bc_slabvec_print(BcVec* v, const char* func); #endif // BC_DEBUG_CODE diff --git a/contrib/bc/include/version.h b/contrib/bc/include/version.h index 72500c8e3f2..e5c9ea3290e 100644 --- a/contrib/bc/include/version.h +++ b/contrib/bc/include/version.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -37,6 +37,6 @@ #define BC_VERSION_H /// The current version. -#define VERSION 5.1.1 +#define VERSION 7.0.3 #endif // BC_VERSION_H diff --git a/contrib/bc/include/vm.h b/contrib/bc/include/vm.h index bbc5e57e2ac..e81206b6387 100644 --- a/contrib/bc/include/vm.h +++ b/contrib/bc/include/vm.h @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -78,10 +78,6 @@ #endif // Set defaults. -// -#ifndef BC_ENABLE_NLS -#define BC_ENABLE_NLS (0) -#endif // BC_ENABLE_NLS #ifndef MAINEXEC #define MAINEXEC bc @@ -132,93 +128,105 @@ #if DC_ENABLED /// The flag for the extended register option. -#define DC_FLAG_X (UINTMAX_C(1)<<0) +#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) +#define BC_FLAG_W (UINTMAX_C(1) << 1) /// The flag for the POSIX error option. -#define BC_FLAG_S (UINTMAX_C(1)<<2) +#define BC_FLAG_S (UINTMAX_C(1) << 2) /// The flag for the math library option. -#define BC_FLAG_L (UINTMAX_C(1)<<3) +#define BC_FLAG_L (UINTMAX_C(1) << 3) /// The flag for the global stacks option. -#define BC_FLAG_G (UINTMAX_C(1)<<4) +#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) +#define BC_FLAG_Q (UINTMAX_C(1) << 5) /// The flag for interactive. -#define BC_FLAG_I (UINTMAX_C(1)<<6) +#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) +#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) +#define BC_FLAG_R (UINTMAX_C(1) << 8) /// The flag for a leading zero. -#define BC_FLAG_Z (UINTMAX_C(1)<<9) +#define BC_FLAG_Z (UINTMAX_C(1) << 9) /// The flag for stdin being a TTY. -#define BC_FLAG_TTYIN (UINTMAX_C(1)<<10) +#define BC_FLAG_TTYIN (UINTMAX_C(1) << 10) /// The flag for TTY mode. -#define BC_FLAG_TTY (UINTMAX_C(1)<<11) +#define BC_FLAG_TTY (UINTMAX_C(1) << 11) /// The flag for reset on SIGINT. -#define BC_FLAG_SIGINT (UINTMAX_C(1)<<12) +#define BC_FLAG_SIGINT (UINTMAX_C(1) << 12) + +/// The flag for exiting with expressions. +#define BC_FLAG_EXPR_EXIT (UINTMAX_C(1) << 13) + +/// The flag for digit clamping. +#define BC_FLAG_DIGIT_CLAMP (UINTMAX_C(1) << 14) /// A convenience macro for getting the TTYIN flag. -#define BC_TTYIN (vm.flags & BC_FLAG_TTYIN) +#define BC_TTYIN (vm->flags & BC_FLAG_TTYIN) /// A convenience macro for getting the TTY flag. -#define BC_TTY (vm.flags & BC_FLAG_TTY) +#define BC_TTY (vm->flags & BC_FLAG_TTY) /// A convenience macro for getting the SIGINT flag. -#define BC_SIGINT (vm.flags & BC_FLAG_SIGINT) +#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) +#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) +#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) +#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) +#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) +#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) +#define BC_I (vm->flags & BC_FLAG_I) /// A convenience macro for getting the prompt flag. -#define BC_P (vm.flags & BC_FLAG_P) +#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) +#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) +#define BC_Z (vm->flags & BC_FLAG_Z) + +/// A convenience macro for getting the expression exit flag. +#define BC_EXPR_EXIT (vm->flags & BC_FLAG_EXPR_EXIT) + +/// A convenience macro for getting the digit clamp flag. +#define BC_DIGIT_CLAMP (vm->flags & BC_FLAG_DIGIT_CLAMP) #if BC_ENABLED @@ -228,10 +236,57 @@ #if DC_ENABLED /// Returns true if bc is running. -#define BC_IS_BC (vm.name[0] != 'd') +#define BC_IS_BC (vm->name[0] != 'd') /// Returns true if dc is running. -#define BC_IS_DC (vm.name[0] == 'd') +#define BC_IS_DC (vm->name[0] == 'd') + +/// Returns the correct read prompt. +#define BC_VM_READ_PROMPT (BC_IS_BC ? "read> " : "?> ") + +/// Returns the string for the line length environment variable. +#define BC_VM_LINE_LENGTH_STR (BC_IS_BC ? "BC_LINE_LENGTH" : "DC_LINE_LENGTH") + +/// Returns the string for the environment args environment variable. +#define BC_VM_ENV_ARGS_STR (BC_IS_BC ? "BC_ENV_ARGS" : "DC_ENV_ARGS") + +/// Returns the string for the expression exit environment variable. +#define BC_VM_EXPR_EXIT_STR (BC_IS_BC ? "BC_EXPR_EXIT" : "DC_EXPR_EXIT") + +/// Returns the default for the expression exit environment variable. +#define BC_VM_EXPR_EXIT_DEF \ + (BC_IS_BC ? BC_DEFAULT_EXPR_EXIT : DC_DEFAULT_EXPR_EXIT) + +/// Returns the string for the digit clamp environment variable. +#define BC_VM_DIGIT_CLAMP_STR (BC_IS_BC ? "BC_DIGIT_CLAMP" : "DC_DIGIT_CLAMP") + +/// Returns the default for the digit clamp environment variable. +#define BC_VM_DIGIT_CLAMP_DEF \ + (BC_IS_BC ? BC_DEFAULT_DIGIT_CLAMP : DC_DEFAULT_DIGIT_CLAMP) + +/// Returns the string for the TTY mode environment variable. +#define BC_VM_TTY_MODE_STR (BC_IS_BC ? "BC_TTY_MODE" : "DC_TTY_MODE") + +/// Returns the default for the TTY mode environment variable. +#define BC_VM_TTY_MODE_DEF \ + (BC_IS_BC ? BC_DEFAULT_TTY_MODE : DC_DEFAULT_TTY_MODE) + +/// Returns the string for the prompt environment variable. +#define BC_VM_PROMPT_STR (BC_IS_BC ? "BC_PROMPT" : "DC_PROMPT") + +/// Returns the default for the prompt environment variable. +#define BC_VM_PROMPT_DEF (BC_IS_BC ? BC_DEFAULT_PROMPT : DC_DEFAULT_PROMPT) + +/// Returns the string for the SIGINT reset environment variable. +#define BC_VM_SIGINT_RESET_STR \ + (BC_IS_BC ? "BC_SIGINT_RESET" : "DC_SIGINT_RESET") + +/// Returns the string for the SIGINT reset environment variable. +#define BC_VM_SIGINT_RESET_DEF \ + (BC_IS_BC ? BC_DEFAULT_SIGINT_RESET : DC_DEFAULT_SIGINT_RESET) + +/// Returns true if the calculator should run stdin. +#define BC_VM_RUN_STDIN(has_file) (BC_IS_BC || !(has_file)) #else // DC_ENABLED @@ -241,6 +296,48 @@ /// Returns true if dc is running. #define BC_IS_DC (0) +/// Returns the correct read prompt. +#define BC_VM_READ_PROMPT ("read> ") + +/// Returns the string for the line length environment variable. +#define BC_VM_LINE_LENGTH_STR ("BC_LINE_LENGTH") + +/// Returns the string for the environment args environment variable. +#define BC_VM_ENV_ARGS_STR ("BC_ENV_ARGS") + +/// Returns the string for the expression exit environment variable. +#define BC_VM_EXPR_EXIT_STR ("BC_EXPR_EXIT") + +/// Returns the default for the expression exit environment variable. +#define BC_VM_EXPR_EXIT_DEF (BC_DEFAULT_EXPR_EXIT) + +/// Returns the string for the digit clamp environment variable. +#define BC_VM_DIGIT_CLAMP_STR ("BC_DIGIT_CLAMP") + +/// Returns the default for the digit clamp environment variable. +#define BC_VM_DIGIT_CLAMP_DEF (BC_DEFAULT_DIGIT_CLAMP) + +/// Returns the string for the TTY mode environment variable. +#define BC_VM_TTY_MODE_STR ("BC_TTY_MODE") + +/// Returns the default for the TTY mode environment variable. +#define BC_VM_TTY_MODE_DEF (BC_DEFAULT_TTY_MODE) + +/// Returns the string for the prompt environment variable. +#define BC_VM_PROMPT_STR ("BC_PROMPT") + +/// Returns the default for the SIGINT reset environment variable. +#define BC_VM_PROMPT_DEF (BC_DEFAULT_PROMPT) + +/// Returns the string for the SIGINT reset environment variable. +#define BC_VM_SIGINT_RESET_STR ("BC_SIGINT_RESET") + +/// Returns the string for the SIGINT reset environment variable. +#define BC_VM_SIGINT_RESET_DEF (BC_DEFAULT_SIGINT_RESET) + +/// Returns true if the calculator should run stdin. +#define BC_VM_RUN_STDIN(has_file) (BC_IS_BC) + #endif // DC_ENABLED #else // BC_ENABLED @@ -254,6 +351,48 @@ /// Returns true if dc is running. #define BC_IS_DC (1) +/// Returns the correct read prompt. +#define BC_VM_READ_PROMPT ("?> ") + +/// Returns the string for the line length environment variable. +#define BC_VM_LINE_LENGTH_STR ("DC_LINE_LENGTH") + +/// Returns the string for the environment args environment variable. +#define BC_VM_ENV_ARGS_STR ("DC_ENV_ARGS") + +/// Returns the string for the expression exit environment variable. +#define BC_VM_EXPR_EXIT_STR ("DC_EXPR_EXIT") + +/// Returns the default for the expression exit environment variable. +#define BC_VM_EXPR_EXIT_DEF (DC_DEFAULT_EXPR_EXIT) + +/// Returns the string for the digit clamp environment variable. +#define BC_VM_DIGIT_CLAMP_STR ("DC_DIGIT_CLAMP") + +/// Returns the default for the digit clamp environment variable. +#define BC_VM_DIGIT_CLAMP_DEF (DC_DEFAULT_DIGIT_CLAMP) + +/// Returns the string for the TTY mode environment variable. +#define BC_VM_TTY_MODE_STR ("DC_TTY_MODE") + +/// Returns the default for the TTY mode environment variable. +#define BC_VM_TTY_MODE_DEF (DC_DEFAULT_TTY_MODE) + +/// Returns the string for the prompt environment variable. +#define BC_VM_PROMPT_STR ("DC_PROMPT") + +/// Returns the default for the SIGINT reset environment variable. +#define BC_VM_PROMPT_DEF (DC_DEFAULT_PROMPT) + +/// Returns the string for the SIGINT reset environment variable. +#define BC_VM_SIGINT_RESET_STR ("DC_SIGINT_RESET") + +/// Returns the string for the SIGINT reset environment variable. +#define BC_VM_SIGINT_RESET_DEF (DC_DEFAULT_SIGINT_RESET) + +/// Returns true if the calculator should run stdin. +#define BC_VM_RUN_STDIN(has_file) (!(has_file)) + #endif // BC_ENABLED /// A convenience macro for checking if the prompt is enabled. @@ -261,7 +400,9 @@ #else // !BC_ENABLE_LIBRARY -#define BC_Z (vm.leading_zeroes) +#define BC_Z (vm->leading_zeroes) + +#define BC_DIGIT_CLAMP (vm->digit_clamp) #endif // !BC_ENABLE_LIBRARY @@ -314,18 +455,30 @@ /// Returns the max number of variables that is allowed. #define BC_MAX_VARS ((ulong) (SIZE_MAX - 1)) +#if BC_ENABLE_LINE_LIB + +/// The size of the global buffer. +#define BC_VM_BUF_SIZE (1 << 10) + +/// The amount of the global buffer allocated to stdin. +#define BC_VM_STDIN_BUF_SIZE (BC_VM_BUF_SIZE - 1) + +#else // BC_ENABLE_LINE_LIB + /// The size of the global buffer. -#define BC_VM_BUF_SIZE (1<<12) +#define BC_VM_BUF_SIZE (1 << 12) /// The amount of the global buffer allocated to stdout. -#define BC_VM_STDOUT_BUF_SIZE (1<<11) +#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) +#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) +#endif // BC_ENABLE_LINE_LIB + /// The max number of temporary BcNums that can be kept. #define BC_VM_MAX_TEMPS (1 << 9) @@ -340,7 +493,7 @@ #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) +#define BC_VM_INVALID_CATALOG ((nl_catd) - 1) /** * Returns true if the *unsigned* multiplication overflows. @@ -354,8 +507,8 @@ /// The global vm struct. This holds all of the global data besides the file /// buffers. -typedef struct BcVm { - +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 @@ -407,9 +560,13 @@ typedef struct BcVm { /// The vector for creating strings to pass to the client. BcVec out; +#if BC_ENABLE_EXTRA_MATH + /// The PRNG. BcRNG rng; +#endif // BC_ENABLE_EXTRA_MATH + /// The current error. BclError err; @@ -419,27 +576,21 @@ typedef struct BcVm { /// Whether or not to print leading zeros. bool leading_zeroes; + /// Whether or not to clamp digits that are greater than or equal to the + /// current ibase. + bool digit_clamp; + /// 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 +#else // 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 + const char* sigmsg; /// Non-zero when signals are "locked." This is volatile sig_atomic_t /// because it is also used in the signal handler. See the development @@ -454,8 +605,6 @@ typedef struct BcVm { /// information. volatile sig_atomic_t sig; -#if !BC_ENABLE_LIBRARY - /// The length of sigmsg. uchar siglen; @@ -483,8 +632,8 @@ typedef struct BcVm { /// True if EOF was encountered. bool eof; - /// True if bc is currently reading from stdin. - bool is_stdin; + /// The mode that the program is in. + uchar mode; #if BC_ENABLED @@ -494,13 +643,6 @@ typedef struct BcVm { #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; @@ -509,10 +651,10 @@ typedef struct BcVm { /// The name of the calculator under use. This is used by BC_IS_BC and /// BC_IS_DC. - const char *name; + const char* name; /// The help text for the calculator. - const char *help; + const char* help; #if BC_ENABLE_HISTORY @@ -530,19 +672,21 @@ typedef struct BcVm { /// 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]; + const char* err_ids[BC_ERR_IDX_NELEMS + BC_ENABLED]; /// The messages for each error. - const char *err_msgs[BC_ERR_NELEMS]; + const char* err_msgs[BC_ERR_NELEMS]; +#if BC_ENABLE_NLS /// The locale. - const char *locale; + const char* locale; +#endif // BC_ENABLE_NLS -#endif // !BC_ENABLE_LIBRARY +#endif // BC_ENABLE_LIBRARY + + /// An array of maxes for the globals. + BcBigDig maxes[BC_PROG_GLOBALS_LEN + BC_ENABLE_EXTRA_MATH]; /// The last base used to parse. BcBigDig last_base; @@ -560,7 +704,7 @@ typedef struct BcVm { /// A buffer of environment arguments. This is the actual value of the /// environment variable. - char *env_args_buffer; + char* env_args_buffer; /// A vector for environment arguments after parsing. BcVec env_args; @@ -607,21 +751,14 @@ typedef struct BcVm { #endif // BC_ENABLE_NLS /// A pointer to the stdin buffer. - char *buf; + 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; + /// The slabs vector for constants, strings, function names, and other + /// string-like things. + BcVec slabs; #if BC_ENABLED @@ -632,6 +769,8 @@ typedef struct BcVm { #endif // BC_ENABLED #endif // !BC_ENABLE_LIBRARY + BcDig* temps_buf[BC_VM_MAX_TEMPS]; + #if BC_DEBUG_CODE /// The depth for BC_FUNC_ENTER and BC_FUNC_EXIT. @@ -645,65 +784,88 @@ typedef struct 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); +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. + * @return A status. */ -void bc_vm_boot(int argc, char *argv[]); +BcStatus +bc_vm_boot(int argc, const char* argv[]); /** * Initializes some of the BcVm global. This is separate to make things easier * on the library code. */ -void bc_vm_init(void); +void +bc_vm_init(void); /** * Frees the BcVm global. */ -void bc_vm_shutdown(void); +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); +void +bc_vm_addTemp(BcDig* num); /** - * Dish out a temp, or NULL if there are none. + * Return the temp on the top of the temp stack, or NULL if there are none. * @return A temp, or NULL if none exist. */ -BcDig* bc_vm_takeTemp(void); +BcDig* +bc_vm_takeTemp(void); + +/** + * Gets the top temp of the temp stack. This is separate from bc_vm_takeTemp() + * to quiet a GCC warning about longjmp() clobbering in bc_num_init(). + * @return A temp, or NULL if none exist. + */ +BcDig* +bc_vm_getTemp(void); /** * Frees all temporaries. */ -void bc_vm_freeTemps(void); +void +bc_vm_freeTemps(void); -#if !BC_ENABLE_HISTORY +#if !BC_ENABLE_HISTORY || BC_ENABLE_LINE_LIB || BC_ENABLE_LIBRARY /** * 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) +#define bc_vm_putchar(c, t) bc_vm_putchar_impl(c) + +#else // !BC_ENABLE_HISTORY || BC_ENABLE_LINE_LIB || BC_ENABLE_LIBRARY + +// This is here to satisfy a clang warning about recursive macros. +#define bc_vm_putchar(c, t) bc_vm_putchar_impl(c, t) -#endif // !BC_ENABLE_HISTORY +#endif // !BC_ENABLE_HISTORY || BC_ENABLE_LINE_LIB || BC_ENABLE_LIBRARY /** * Print to stdout with limited formating. * @param fmt The format string. */ -void bc_vm_printf(const char *fmt, ...); +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); +void +bc_vm_putchar(int c, BcFlushType type); /** * Multiplies @a n and @a size and throws an allocation error if overflow @@ -712,7 +874,8 @@ void bc_vm_putchar(int c, BcFlushType type); * @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); +size_t +bc_vm_arraySize(size_t n, size_t size); /** * Adds @a a and @a b and throws an error if overflow occurs. @@ -720,14 +883,16 @@ size_t bc_vm_arraySize(size_t n, size_t size); * @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); +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); +void* +bc_vm_malloc(size_t n); /** * Reallocate @a ptr to be @a n bytes and throw an allocation error if @@ -736,41 +901,55 @@ void* bc_vm_malloc(size_t n); * @param n The bytes to allocate. * @return A pointer to the reallocated memory. */ -void* bc_vm_realloc(void *ptr, size_t n); +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); +char* +bc_vm_strdup(const char* str); /** - * Reads a line into BcVm's buffer field. + * Reads a line from stdin 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); +bool +bc_vm_readLine(bool clear); + +/** + * Reads a line from the command-line expressions 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_readBuf(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); +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); +char* +bc_vm_getenv(const char* var); /** * Frees an environment variable value. * @param val The value to free. */ -void bc_vm_getenvFree(char* val); +void +bc_vm_getenvFree(char* val); #if BC_DEBUG_CODE @@ -778,13 +957,16 @@ void bc_vm_getenvFree(char* val); * Start executing a jump series. * @param f The name of the function that started the jump series. */ -void bc_vm_jmp(const char *f); +void +bc_vm_jmp(const char* f); + #else // BC_DEBUG_CODE /** * Start executing a jump series. */ -void bc_vm_jmp(void); +void +bc_vm_jmp(void); #endif // BC_DEBUG_CODE @@ -796,29 +978,59 @@ void bc_vm_jmp(void); * or no POSIX errors are enabled. * @param e The error. */ -void bc_vm_handleError(BcErr e); +void +bc_vm_handleError(BcErr e); /** * Handle a fatal error. * @param e The error. */ -void bc_vm_fatalError(BcErr e); +void +bc_vm_fatalError(BcErr e); /** * A function to call at exit. */ -void bc_vm_atexit(void); +void +bc_vm_atexit(void); #else // BC_ENABLE_LIBRARY +/** + * Calculates the number of decimal digits in the argument. + * @param val The value to calculate the number of decimal digits in. + * @return The number of decimal digits in @a val. + */ +size_t +bc_vm_numDigits(size_t val); + +#if BC_DEBUG + +/** + * 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 file The source file where the error occurred. + * @param fline The line in the source file where the error occurred. + * @param line The bc source line where the error occurred. + */ +void +bc_vm_handleError(BcErr e, const char* file, int fline, size_t line, ...); + +#else // BC_DEBUG + /** * 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. + * @param line The bc source line where the error occurred. */ -void bc_vm_handleError(BcErr e, size_t line, ...); +void +bc_vm_handleError(BcErr e, size_t line, ...); + +#endif // BC_DEBUG /** * Handle a fatal error. @@ -827,26 +1039,23 @@ void bc_vm_handleError(BcErr e, size_t line, ...); #if !BC_ENABLE_MEMCHECK BC_NORETURN #endif // !BC_ENABLE_MEMCHECK -void bc_vm_fatalError(BcErr e); +void +bc_vm_fatalError(BcErr e); /** * A function to call at exit. * @param status The exit status. */ -int bc_vm_atexit(int status); +BcStatus +bc_vm_atexit(BcStatus 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[]; +extern const char* bc_errs[]; /// A reference to the array of error category indices for each error. extern const uchar bc_err_ids[]; @@ -867,10 +1076,17 @@ extern const char bc_pledge_end_history[]; /// A reference to the end pledge() promises when *not* using history. extern const char bc_pledge_end[]; +#if !BC_ENABLE_LIBRARY + /// A reference to the global data. -extern BcVm vm; +extern BcVm* vm; + +/// The global data. +extern BcVm vm_data; /// A reference to the global output buffers. extern char output_bufs[BC_VM_BUF_SIZE]; +#endif // !BC_ENABLE_LIBRARY + #endif // BC_VM_H diff --git a/contrib/bc/locales/de_DE.ISO8859-1.msg b/contrib/bc/locales/de_DE.ISO8859-1.msg index 76f2ac4190f..9700ab070b2 100644 --- a/contrib/bc/locales/de_DE.ISO8859-1.msg +++ b/contrib/bc/locales/de_DE.ISO8859-1.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Headers for printing errors/warnings. -$set 1 - -1 "Funktion:" - $ Error types. -$set 2 +$set 1 1 "Rechenfehler:" 2 "Analysefehler:" @@ -43,7 +38,7 @@ $set 2 5 "Warnung:" $ Math errors. -$set 3 +$set 2 1 "negative Zahl" 2 "Nicht-Ganzzahl-Wert" @@ -51,7 +46,7 @@ $set 3 4 "Division durch 0" $ Parse errors. -$set 4 +$set 3 1 "Ende der Datei" 2 "ungültiges Zeichen: '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX erlaubt keine Vergleichsoperatoren außerhalb von if-Anweisungen oder Schleifen" 23 "POSIX benötigt 0 oder 1 Vergleichsoperatoren pro Bedingung" 24 "POSIX erlaubt keinen leeren Ausdruck in einer for-Schleife" -25 "POSIX erlaubt keine exponentielle Notation" -26 "POSIX erlaubt keine Feld-Referenzen als Funktionsparameter" -27 "POSIX erfordert, dass die linke Klammer auf der gleichen Linie wie der Funktionskopf steht" -28 "POSIX erlaubt keine Zuweisung von Strings an Variablen oder Arrays" +25 "POSIX verlangt einen Zeilenumbruch zwischen einem Semikolon und einer Funktionsdefinition" +26 "POSIX erlaubt keine exponentielle Notation" +27 "POSIX erlaubt keine Feld-Referenzen als Funktionsparameter" +28 "POSIX erlaubt keine ungültigen Funktionen" +29 "POSIX erfordert, dass die linke Klammer auf der gleichen Linie wie der Funktionskopf steht" +30 "POSIX erlaubt keine Zuweisung von Strings an Variablen oder Arrays" $ Runtime errors. -$set 5 +$set 4 1 "ungültige \"ibase\": muss im Intervall [%lu, %lu] liegen" 2 "ungültige \"obase\": muss im Intervall [%lu, %lu] liegen" @@ -98,7 +95,7 @@ $set 5 11 "kann keinen ungültigen Wert in einem Ausdruck verwenden" $ Fatal errors. -$set 6 +$set 5 1 "Speicherzuweisung fehlgeschlagen" 2 "Ein-Ausgabe-Fehler" diff --git a/contrib/bc/locales/de_DE.UTF-8.msg b/contrib/bc/locales/de_DE.UTF-8.msg index c4dad4cd3a6..7b918fc6d1c 100644 --- a/contrib/bc/locales/de_DE.UTF-8.msg +++ b/contrib/bc/locales/de_DE.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Headers for printing errors/warnings. -$set 1 - -1 "Funktion:" - $ Error types. -$set 2 +$set 1 1 "Rechenfehler:" 2 "Analysefehler:" @@ -43,7 +38,7 @@ $set 2 5 "Warnung:" $ Math errors. -$set 3 +$set 2 1 "negative Zahl" 2 "Nicht-Ganzzahl-Wert" @@ -51,7 +46,7 @@ $set 3 4 "Division durch 0" $ Parse errors. -$set 4 +$set 3 1 "Ende der Datei" 2 "ungültiges Zeichen: '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX erlaubt keine Vergleichsoperatoren außerhalb von if-Anweisungen oder Schleifen" 23 "POSIX benötigt 0 oder 1 Vergleichsoperatoren pro Bedingung" 24 "POSIX erlaubt keinen leeren Ausdruck in einer for-Schleife" -25 "POSIX erlaubt keine exponentielle Notation" -26 "POSIX erlaubt keine Feld-Referenzen als Funktionsparameter" -27 "POSIX erfordert, dass die linke Klammer auf der gleichen Linie wie der Funktionskopf steht" -28 "POSIX erlaubt keine Zuweisung von Strings an Variablen oder Arrays" +25 "POSIX verlangt einen Zeilenumbruch zwischen einem Semikolon und einer Funktionsdefinition" +26 "POSIX erlaubt keine exponentielle Notation" +27 "POSIX erlaubt keine Feld-Referenzen als Funktionsparameter" +28 "POSIX erlaubt keine ungültigen Funktionen" +29 "POSIX erfordert, dass die linke Klammer auf der gleichen Linie wie der Funktionskopf steht" +30 "POSIX erlaubt keine Zuweisung von Strings an Variablen oder Arrays" $ Runtime errors. -$set 5 +$set 4 1 "ungültige \"ibase\": muss im Intervall [%lu, %lu] liegen" 2 "ungültige \"obase\": muss im Intervall [%lu, %lu] liegen" @@ -98,7 +95,7 @@ $set 5 11 "kann keinen ungültigen Wert in einem Ausdruck verwenden" $ Fatal errors. -$set 6 +$set 5 1 "Speicherzuweisung fehlgeschlagen" 2 "Ein-Ausgabe-Fehler" diff --git a/contrib/bc/locales/en_US.msg b/contrib/bc/locales/en_US.msg index 707950a5767..4afcbcd1f81 100644 --- a/contrib/bc/locales/en_US.msg +++ b/contrib/bc/locales/en_US.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Function:" - $ Error types. -$set 2 +$set 1 1 "Math error:" 2 "Parse error:" @@ -43,7 +38,7 @@ $set 2 5 "Warning:" $ Math errors. -$set 3 +$set 2 1 "negative number" 2 "non-integer number" @@ -51,7 +46,7 @@ $set 3 4 "divide by 0" $ Parse errors. -$set 4 +$set 3 1 "end of file" 2 "invalid character '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX does not allow comparison operators outside if statements or loops" 23 "POSIX requires 0 or 1 comparison operators per condition" 24 "POSIX requires all 3 parts of a for loop to be non-empty" -25 "POSIX does not allow exponential notation" -26 "POSIX does not allow array references as function parameters" -27 "POSIX requires the left brace be on the same line as the function header" -28 "POSIX does not allow strings to be assigned to variables or arrays" +25 "POSIX requires a newline between a semicolon and a function definition" +26 "POSIX does not allow exponential notation" +27 "POSIX does not allow array references as function parameters" +28 "POSIX does not allow void functions" +29 "POSIX requires the left brace be on the same line as the function header" +30 "POSIX does not allow strings to be assigned to variables or arrays" $ Runtime errors. -$set 5 +$set 4 1 "invalid ibase: must be [%lu, %lu]" 2 "invalid obase: must be [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "cannot use a void value in an expression" $ Fatal errors. -$set 6 +$set 5 1 "memory allocation failed" 2 "I/O error" diff --git a/contrib/bc/locales/es_ES.ISO8859-1.msg b/contrib/bc/locales/es_ES.ISO8859-1.msg index 8d74f884f81..4d022d9bf66 100644 --- a/contrib/bc/locales/es_ES.ISO8859-1.msg +++ b/contrib/bc/locales/es_ES.ISO8859-1.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Función:" - $ Error types. -$set 2 +$set 1 1 "Error de matemática:" 2 "Error de syntaxis:" @@ -43,7 +38,7 @@ $set 2 5 "Advertencia:" $ Math errors. -$set 3 +$set 2 1 "número negativo" 2 "número no es entero" @@ -51,7 +46,7 @@ $set 3 4 "división por cero" $ Parse errors. -$set 4 +$set 3 1 "fin de archivo" 2 "no válido '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX no permite operadores de comparación aparte de \"if\" expresión o bucles" 23 "POSIX requiere 0 o 1 operadores de comparisón para cada condición" 24 "POSIX requiere todos 3 partes de una bucla que no esta vacío" -25 "POSIX no permite una notación exponencial" -26 "POSIX no permite una referencia a una matriz como un parámetro de función" -27 "POSIX requiere el llave de la izquierda que sea en la misma línea que los parámetros de la función" -28 "POSIX no permite asignar cadenas a variables o matrices" +25 "POSIX requiere una nueva línea entre un punto y coma y una definición de función" +26 "POSIX no permite una notación exponencial" +27 "POSIX no permite una referencia a una matriz como un parámetro de función" +28 "POSIX no permite funciones void" +29 "POSIX requiere el llave de la izquierda que sea en la misma línea que los parámetros de la función" +30 "POSIX no permite asignar cadenas a variables o matrices" $ Runtime errors. -$set 5 +$set 4 1 "\"ibase\" no es válido: debe ser [%lu, %lu]" 2 "\"obase\" no es válido: debe ser [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "no puede utilizar un valor vacío en una expresión" $ Fatal errors. -$set 6 +$set 5 1 "error en la asignación de memoria" 2 "error de I/O" diff --git a/contrib/bc/locales/es_ES.UTF-8.msg b/contrib/bc/locales/es_ES.UTF-8.msg index 26559e6e9b8..364cff6ee57 100644 --- a/contrib/bc/locales/es_ES.UTF-8.msg +++ b/contrib/bc/locales/es_ES.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Función:" - $ Error types. -$set 2 +$set 1 1 "Error de matemática:" 2 "Error de syntaxis:" @@ -43,7 +38,7 @@ $set 2 5 "Advertencia:" $ Math errors. -$set 3 +$set 2 1 "número negativo" 2 "número no es entero" @@ -51,7 +46,7 @@ $set 3 4 "división por cero" $ Parse errors. -$set 4 +$set 3 1 "fin de archivo" 2 "no válido '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX no permite operadores de comparación aparte de \"if\" expresión o bucles" 23 "POSIX requiere 0 o 1 operadores de comparisón para cada condición" 24 "POSIX requiere todos 3 partes de una bucla que no esta vacío" -25 "POSIX no permite una notación exponencial" -26 "POSIX no permite una referencia a una matriz como un parámetro de función" -27 "POSIX requiere el llave de la izquierda que sea en la misma línea que los parámetros de la función" -28 "POSIX no permite asignar cadenas a variables o matrices" +25 "POSIX requiere una nueva línea entre un punto y coma y una definición de función" +26 "POSIX no permite una notación exponencial" +27 "POSIX no permite una referencia a una matriz como un parámetro de función" +28 "POSIX no permite funciones void" +29 "POSIX requiere el llave de la izquierda que sea en la misma línea que los parámetros de la función" +30 "POSIX no permite asignar cadenas a variables o matrices" $ Runtime errors. -$set 5 +$set 4 1 "\"ibase\" no es válido: debe ser [%lu, %lu]" 2 "\"obase\" no es válido: debe ser [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "no puede utilizar un valor vacío en una expresión" $ Fatal errors. -$set 6 +$set 5 1 "error en la asignación de memoria" 2 "error de I/O" diff --git a/contrib/bc/locales/fr_FR.ISO8859-1.msg b/contrib/bc/locales/fr_FR.ISO8859-1.msg index 8e894e043bb..b4b39866c96 100644 --- a/contrib/bc/locales/fr_FR.ISO8859-1.msg +++ b/contrib/bc/locales/fr_FR.ISO8859-1.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Fonction :" - $ Error types. -$set 2 +$set 1 1 "Erreur de calcul :" 2 "Erreur d'analyse syntaxique :" @@ -43,7 +38,7 @@ $set 2 5 "Avertissement :" $ Math errors. -$set 3 +$set 2 1 "nombre strictement négatif" 2 "nombre non entier" @@ -51,7 +46,7 @@ $set 3 4 "division par 0" $ Parse errors. -$set 4 +$set 3 1 "fin de fichier" 2 "caractère invalide '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX interdit les opérateurs de comparaison en dehors des expressions 'if' ou des boucles" 23 "POSIX impose 0 ou 1 opérateur de comparaison par condition" 24 "POSIX interdit une expression vide dans une boucle 'for'" -25 "POSIX interdit la notation exponentielle" -26 "POSIX interdit les références à un tableau dans les paramètres d'une fonction" -27 "POSIX impose que l'en-tête de la fonction et le '{' soient sur la même ligne" -28 "POSIX interdit pas d'assigner des chaînes de caractères à des variables ou à des tableaux" +25 "POSIX exige une nouvelle ligne entre un point-virgule et une définition de fonction" +26 "POSIX interdit la notation exponentielle" +27 "POSIX interdit les références à un tableau dans les paramètres d'une fonction" +28 "POSIX n'autorise pas les fonctions void" +29 "POSIX impose que l'en-tête de la fonction et le '{' soient sur la même ligne" +30 "POSIX interdit pas d'assigner des chaînes de caractères à des variables ou à des tableaux" $ Runtime errors. -$set 5 +$set 4 1 "ibase invalide : doit être [%lu, %lu]" 2 "obase invalide : doit être [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "une valeur 'void' est inutilisable dans une expression" $ Fatal errors. -$set 6 +$set 5 1 "échec d'allocation mémoire" 2 "erreur d'entrée-sortie" diff --git a/contrib/bc/locales/fr_FR.UTF-8.msg b/contrib/bc/locales/fr_FR.UTF-8.msg index 8e894e043bb..c3387e31ae9 100644 --- a/contrib/bc/locales/fr_FR.UTF-8.msg +++ b/contrib/bc/locales/fr_FR.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Fonction :" - $ Error types. -$set 2 +$set 1 1 "Erreur de calcul :" 2 "Erreur d'analyse syntaxique :" @@ -43,7 +38,7 @@ $set 2 5 "Avertissement :" $ Math errors. -$set 3 +$set 2 1 "nombre strictement négatif" 2 "nombre non entier" @@ -51,7 +46,7 @@ $set 3 4 "division par 0" $ Parse errors. -$set 4 +$set 3 1 "fin de fichier" 2 "caractère invalide '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX interdit les opérateurs de comparaison en dehors des expressions 'if' ou des boucles" 23 "POSIX impose 0 ou 1 opérateur de comparaison par condition" 24 "POSIX interdit une expression vide dans une boucle 'for'" -25 "POSIX interdit la notation exponentielle" -26 "POSIX interdit les références à un tableau dans les paramètres d'une fonction" -27 "POSIX impose que l'en-tête de la fonction et le '{' soient sur la même ligne" -28 "POSIX interdit pas d'assigner des chaînes de caractères à des variables ou à des tableaux" +25 "POSIX exige une nouvelle ligne entre un point-virgule et une définition de fonction." +26 "POSIX interdit la notation exponentielle" +27 "POSIX interdit les références à un tableau dans les paramètres d'une fonction" +28 "POSIX n'autorise pas les fonctions void" +29 "POSIX impose que l'en-tête de la fonction et le '{' soient sur la même ligne" +30 "POSIX interdit pas d'assigner des chaînes de caractères à des variables ou à des tableaux" $ Runtime errors. -$set 5 +$set 4 1 "ibase invalide : doit être [%lu, %lu]" 2 "obase invalide : doit être [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "une valeur 'void' est inutilisable dans une expression" $ Fatal errors. -$set 6 +$set 5 1 "échec d'allocation mémoire" 2 "erreur d'entrée-sortie" diff --git a/contrib/bc/locales/ja_JP.UTF-8.msg b/contrib/bc/locales/ja_JP.UTF-8.msg index 4477f2bc548..21640eb9f1c 100644 --- a/contrib/bc/locales/ja_JP.UTF-8.msg +++ b/contrib/bc/locales/ja_JP.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ãã®ä»–ã®ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã€‚ -$set 1 - -1 "関数:" - $ エラーã®ç¨®é¡žã€‚ -$set 2 +$set 1 1 "æ•°å­¦ã®ã‚¨ãƒ©ãƒ¼ï¼š" 2 "パースエラー:" @@ -43,7 +38,7 @@ $set 2 5 "警告:" $ æ•°å­¦ã®ã‚¨ãƒ©ãƒ¼ã§ã™ã€‚ -$set 3 +$set 2 1 "è² ã®æ•°" 2 "éžæ•´æ•°" @@ -51,7 +46,7 @@ $set 3 4 "0ã§å‰²ã‚‹" $ 構文解æžã®ã‚¨ãƒ©ãƒ¼ã€‚ -$set 4 +$set 3 1 "ファイルã®çµ‚了" 2 "無効ãªæ–‡å­— '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX 㯠if 文やループã®å¤–ã®æ¯”較演算å­ã‚’許å¯ã—ã¾ã›ã‚“。" 23 "POSIXã¯æ¡ä»¶ã”ã¨ã«0ã¾ãŸã¯1ã®æ¯”較演算å­ã‚’å¿…è¦ã¨ã—ã¾ã™ã€‚" 24 "POSIXã¯forループã®3ã¤ã®éƒ¨åˆ†ãŒã™ã¹ã¦ç©ºã§ãªã„ã“ã¨ã‚’è¦æ±‚ã—ã¾ã™ã€‚" -25 "POSIXã¯æŒ‡æ•°è¡¨è¨˜ã‚’許å¯ã—ã¾ã›ã‚“。" -26 "POSIX ã¯é–¢æ•°ãƒ‘ラメータã¨ã—ã¦é…列å‚照を許å¯ã—ã¾ã›ã‚“。" -27 "POSIXã§ã¯ã€é–¢æ•°ãƒ˜ãƒƒãƒ€ã¨åŒã˜è¡Œã«å·¦ä¸­æ‹¬å¼§ãŒã‚ã‚‹ã“ã¨ãŒå¿…è¦ã§ã™ã€‚" -28 "POSIXã§ã¯ã€å¤‰æ•°ã‚„é…列ã«æ–‡å­—列を割り当ã¦ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“。" +25 "POSIXã§ã¯ã€ã‚»ãƒŸã‚³ãƒ­ãƒ³ã¨é–¢æ•°å®šç¾©ã®é–“ã«æ”¹è¡Œã‚’入れる必è¦ãŒã‚ã‚Šã¾ã™ã€‚" +26 "POSIXã¯æŒ‡æ•°è¡¨è¨˜ã‚’許å¯ã—ã¾ã›ã‚“。" +27 "POSIX ã¯é–¢æ•°ãƒ‘ラメータã¨ã—ã¦é…列å‚照を許å¯ã—ã¾ã›ã‚“。" +28 "POSIXã§ã¯void関数をèªã‚ã¦ã„ã¾ã›ã‚“。" +29 "POSIXã§ã¯ã€é–¢æ•°ãƒ˜ãƒƒãƒ€ã¨åŒã˜è¡Œã«å·¦ä¸­æ‹¬å¼§ãŒã‚ã‚‹ã“ã¨ãŒå¿…è¦ã§ã™ã€‚" +30 "POSIXã§ã¯ã€å¤‰æ•°ã‚„é…列ã«æ–‡å­—列を割り当ã¦ã‚‹ã“ã¨ã¯ã§ãã¾ã›ã‚“。" $ ランタイムエラー。 -$set 5 +$set 4 1 "無効ãªibase:ã¯[%luã€%lu]ã§ãªã‘ã‚Œã°ãªã‚Šã¾ã›ã‚“" 2 "無効ãªobase:ã¯[%luã€%lu]ã§ãªã‘ã‚Œã°ãªã‚Šã¾ã›ã‚“" @@ -98,7 +95,7 @@ $set 5 11 "å¼ã§ã¯ void 値を使用ã§ãã¾ã›ã‚“" $ 致命的ãªã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ã¾ã—ãŸã€‚ -$set 6 +$set 5 1 "メモリã®å‰²ã‚Šå½“ã¦ã«å¤±æ•—ã—ã¾ã—ãŸ" 2 "I/Oエラー" diff --git a/contrib/bc/locales/ja_JP.eucJP.msg b/contrib/bc/locales/ja_JP.eucJP.msg index a907cd7cf0e..3e3b73d20f4 100644 --- a/contrib/bc/locales/ja_JP.eucJP.msg +++ b/contrib/bc/locales/ja_JP.eucJP.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ¤½¤Î¾¤Î¥á¥Ã¥»¡¼¥¸¡£ -$set 1 - -1 "´Ø¿ô¡§" - $ ¥¨¥é¡¼¤Î¼ïÎà¡£ -$set 2 +$set 1 1 "¿ô³Ø¤Î¥¨¥é¡¼¡§" 2 "¥Ñ¡¼¥¹¥¨¥é¡¼¡§" @@ -43,7 +38,7 @@ $set 2 5 "·Ù¹ð¡§" $ ¿ô³Ø¤Î¥¨¥é¡¼¤Ç¤¹¡£ -$set 3 +$set 2 1 "Éé¤Î¿ô" 2 "ÈóÀ°¿ô" @@ -51,7 +46,7 @@ $set 3 4 "0¤Ç³ä¤ë" $ ¹½Ê¸²òÀϤΥ¨¥é¡¼¡£ -$set 4 +$set 3 1 "¥Õ¥¡¥¤¥ë¤Î½ªÎ»" 2 "̵¸ú¤Êʸ»ú '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX ¤Ï if ʸ¤ä¥ë¡¼¥×¤Î³°¤ÎÈæ³Ó±é»»»Ò¤òµö²Ä¤·¤Þ¤»¤ó¡£" 23 "POSIX¤Ï¾ò·ï¤´¤È¤Ë0¤Þ¤¿¤Ï1¤ÎÈæ³Ó±é»»»Ò¤òɬÍפȤ·¤Þ¤¹¡£" 24 "POSIX¤Ïfor¥ë¡¼¥×¤Î3¤Ä¤ÎÉôʬ¤¬¤¹¤Ù¤Æ¶õ¤Ç¤Ê¤¤¤³¤È¤òÍ׵ᤷ¤Þ¤¹¡£" -25 "POSIX¤Ï»Ø¿ôɽµ­¤òµö²Ä¤·¤Þ¤»¤ó¡£" -26 "POSIX ¤Ï´Ø¿ô¥Ñ¥é¥á¡¼¥¿¤È¤·¤ÆÇÛÎ󻲾Ȥòµö²Ä¤·¤Þ¤»¤ó¡£" -27 "POSIX¤Ç¤Ï¡¢´Ø¿ô¥Ø¥Ã¥À¤ÈƱ¤¸¹Ô¤Ëº¸Ãæ³ç¸Ì¤¬¤¢¤ë¤³¤È¤¬É¬ÍפǤ¹¡£" -28 "POSIX¤Ç¤Ï¡¢ÊÑ¿ô¤äÇÛÎó¤Ëʸ»úÎó¤ò³ä¤êÅö¤Æ¤ë¤³¤È¤Ï¤Ç¤­¤Þ¤»¤ó¡£" +25 "POSIX¤Ç¤Ï¡¢¥»¥ß¥³¥í¥ó¤È´Ø¿ôÄêµÁ¤Î´Ö¤Ë²þ¹Ô¤òÆþ¤ì¤ëɬÍפ¬¤¢¤ê¤Þ¤¹¡£" +26 "POSIX¤Ï»Ø¿ôɽµ­¤òµö²Ä¤·¤Þ¤»¤ó¡£" +27 "POSIX ¤Ï´Ø¿ô¥Ñ¥é¥á¡¼¥¿¤È¤·¤ÆÇÛÎ󻲾Ȥòµö²Ä¤·¤Þ¤»¤ó¡£" +28 "POSIX¤Ç¤Ïvoid´Ø¿ô¤òǧ¤á¤Æ¤¤¤Þ¤»¤ó¡£" +29 "POSIX¤Ç¤Ï¡¢´Ø¿ô¥Ø¥Ã¥À¤ÈƱ¤¸¹Ô¤Ëº¸Ãæ³ç¸Ì¤¬¤¢¤ë¤³¤È¤¬É¬ÍפǤ¹¡£" +30 "POSIX¤Ç¤Ï¡¢ÊÑ¿ô¤äÇÛÎó¤Ëʸ»úÎó¤ò³ä¤êÅö¤Æ¤ë¤³¤È¤Ï¤Ç¤­¤Þ¤»¤ó¡£" $ ¥é¥ó¥¿¥¤¥à¥¨¥é¡¼¡£ -$set 5 +$set 4 1 "̵¸ú¤Êibase¡§¤Ï[%lu¡¢%lu]¤Ç¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó" 2 "̵¸ú¤Êobase¡§¤Ï[%lu¡¢%lu]¤Ç¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó" @@ -98,7 +95,7 @@ $set 5 11 "¼°¤Ç¤Ï void Ãͤò»ÈÍѤǤ­¤Þ¤»¤ó" $ Ã×̿Ū¤Ê¥¨¥é¡¼¤¬È¯À¸¤·¤Þ¤·¤¿¡£ -$set 6 +$set 5 1 "¥á¥â¥ê¤Î³ä¤êÅö¤Æ¤Ë¼ºÇÔ¤·¤Þ¤·¤¿" 2 "I/O¥¨¥é¡¼" diff --git a/contrib/bc/locales/nl_NL.ISO8859-1.msg b/contrib/bc/locales/nl_NL.ISO8859-1.msg index 76b8577108e..aaf41c65b04 100644 --- a/contrib/bc/locales/nl_NL.ISO8859-1.msg +++ b/contrib/bc/locales/nl_NL.ISO8859-1.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Diversen berichten. -$set 1 - -1 "Functie:" - $ Fouttypes. -$set 2 +$set 1 1 "Rekenfout:" 2 "Parse error:" @@ -43,7 +38,7 @@ $set 2 5 "Waarschuwing:" $ Math error. -$set 3 +$set 2 1 "negatief getal" 2 "niet-integraal getal" @@ -51,7 +46,7 @@ $set 3 4 "delen door 0" $ Parsefouten. -$set 4 +$set 3 1 "einde van het file" 2 "ongeldig teken '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX laat geen vergelijking toe tussen operatoren buiten als verklaringen of lussen" 23 "POSIX vereist 0 of 1 vergelijkingsoperator per conditie" 24 "POSIX vereist dat alle 3 de delen van een lus niet leeg zijn" -25 "POSIX laat geen exponentiële notatie toe" -26 "POSIX staat geen arrayreferenties toe als functieparameters" -27 "POSIX vereist dat de linkse beugel op dezelfde regel staat als de functiehoofding" -28 "POSIX staat niet toe dat strings worden toegewezen aan variabelen of arrays" +25 "POSIX vereist een nieuwe regel tussen een puntkomma en een functiedefinitie" +26 "POSIX laat geen exponentiële notatie toe" +27 "POSIX staat geen arrayreferenties toe als functieparameters" +28 "POSIX staat geen lege functies toe" +29 "POSIX vereist dat de linkse beugel op dezelfde regel staat als de functiehoofding" +30 "POSIX staat niet toe dat strings worden toegewezen aan variabelen of arrays" $ Runtime fouten. -$set 5 +$set 4 1 "ongeldige ibase: moet [%lu, %lu] zijn" 2 "ongeldige obase: moet [%lu, %lu] zijn" @@ -98,7 +95,7 @@ $set 5 11 "kan geen nietige waarde in een uitdrukking gebruiken" $ Fatale fouten. -$set 6 +$set 5 1 "geheugentoewijzing mislukt" 2 "I/O-fout" diff --git a/contrib/bc/locales/nl_NL.UTF-8.msg b/contrib/bc/locales/nl_NL.UTF-8.msg index 51acb9867e2..0ab0b9c3dc6 100644 --- a/contrib/bc/locales/nl_NL.UTF-8.msg +++ b/contrib/bc/locales/nl_NL.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Diversen berichten. -$set 1 - -1 "Functie:" - $ Fouttypes. -$set 2 +$set 1 1 "Rekenfout:" 2 "Parse error:" @@ -43,7 +38,7 @@ $set 2 5 "Waarschuwing:" $ Math error. -$set 3 +$set 2 1 "negatief getal" 2 "niet-integraal getal" @@ -51,7 +46,7 @@ $set 3 4 "delen door 0" $ Parsefouten. -$set 4 +$set 3 1 "einde van het file" 2 "ongeldig teken '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX laat geen vergelijking toe tussen operatoren buiten als verklaringen of lussen" 23 "POSIX vereist 0 of 1 vergelijkingsoperator per conditie" 24 "POSIX vereist dat alle 3 de delen van een lus niet leeg zijn" -25 "POSIX laat geen exponentiële notatie toe" -26 "POSIX staat geen arrayreferenties toe als functieparameters" -27 "POSIX vereist dat de linkse beugel op dezelfde regel staat als de functiehoofding" -28 "POSIX staat niet toe dat strings worden toegewezen aan variabelen of arrays" +25 "POSIX vereist een nieuwe regel tussen een puntkomma en een functiedefinitie" +26 "POSIX laat geen exponentiële notatie toe" +27 "POSIX staat geen arrayreferenties toe als functieparameters" +28 "POSIX staat geen lege functies toe" +29 "POSIX vereist dat de linkse beugel op dezelfde regel staat als de functiehoofding" +30 "POSIX staat niet toe dat strings worden toegewezen aan variabelen of arrays" $ Runtime fouten. -$set 5 +$set 4 1 "ongeldige ibase: moet [%lu, %lu] zijn" 2 "ongeldige obase: moet [%lu, %lu] zijn" @@ -98,7 +95,7 @@ $set 5 11 "kan geen nietige waarde in een uitdrukking gebruiken" $ Fatale fouten. -$set 6 +$set 5 1 "geheugentoewijzing mislukt" 2 "I/O-fout" diff --git a/contrib/bc/locales/pl_PL.ISO8859-2.msg b/contrib/bc/locales/pl_PL.ISO8859-2.msg index d1d77d7e0b5..5b427c808fd 100644 --- a/contrib/bc/locales/pl_PL.ISO8859-2.msg +++ b/contrib/bc/locales/pl_PL.ISO8859-2.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Ró¿ne wiadomo¶ci. -$set 1 - -1 "Funkcja:" - $ Typy b³êdów. -$set 2 +$set 1 1 "B³±d matematyczny:" 2 "B³±d parse'a:" @@ -43,7 +38,7 @@ $set 2 5 "Ostrze¿enie:" $ B³êdy matematyczne. -$set 3 +$set 2 1 "liczba ujemna" 2 "numer nieintegracyjny" @@ -51,7 +46,7 @@ $set 3 4 "dzielenie przez 0" $ B³êdy Parse'a. -$set 4 +$set 3 1 "koniec akt" 2 "niewa¿ny znak '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX nie pozwala na porównywanie operatorów na zewn±trz, je¶li deklaracje lub pêtle" 23 "POSIX wymaga 0 lub 1 operatora porównawczego na jeden warunek" 24 "POSIX wymaga, aby wszystkie 3 czê¶ci pêtli nie by³y puste" -25 "POSIX nie pozwala na notacjê wyk³adnicz±" -26 "POSIX nie zezwala na odniesienia do tablicy jako parametrów funkcji" -27 "POSIX wymaga, aby lewe usztywnienie znajdowa³o siê na tej samej linii co nag³ówek funkcji" -28 "POSIX nie pozwala na przypisywanie ci±gów znaków do zmiennych lub tablic" +25 "POSIX wymaga nowej linii pomiêdzy ¶rednikiem a definicj± funkcji" +26 "POSIX nie pozwala na notacjê wyk³adnicz±" +27 "POSIX nie zezwala na odniesienia do tablicy jako parametrów funkcji" +28 "POSIX nie dopuszcza funkcji void" +29 "POSIX wymaga, aby lewe usztywnienie znajdowa³o siê na tej samej linii co nag³ówek funkcji" +30 "POSIX nie pozwala na przypisywanie ci±gów znaków do zmiennych lub tablic" $ B³êdy Runtime'u. -$set 5 +$set 4 1 "nieprawid³owa ibase: musi byæ [%lu, %lu]" 2 "nieprawid³owa obase: musi byæ [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "nie mo¿e u¿yæ warto¶ci pustej w wyra¿eniu" $ Fatalne b³êdy. -$set 6 +$set 5 1 "Alokacja pamiêci nie powiod³a siê" 2 "B³±d we/wy" diff --git a/contrib/bc/locales/pl_PL.UTF-8.msg b/contrib/bc/locales/pl_PL.UTF-8.msg index a23a98edd1d..fd0f85b5f76 100644 --- a/contrib/bc/locales/pl_PL.UTF-8.msg +++ b/contrib/bc/locales/pl_PL.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Różne wiadomoÅ›ci. -$set 1 - -1 "Funkcja:" - $ Typy bÅ‚Ä™dów. -$set 2 +$set 1 1 "BÅ‚Ä…d matematyczny:" 2 "BÅ‚Ä…d parse'a:" @@ -43,7 +38,7 @@ $set 2 5 "Ostrzeżenie:" $ BÅ‚Ä™dy matematyczne. -$set 3 +$set 2 1 "liczba ujemna" 2 "numer nieintegracyjny" @@ -51,7 +46,7 @@ $set 3 4 "dzielenie przez 0" $ BÅ‚Ä™dy Parse'a. -$set 4 +$set 3 1 "koniec akt" 2 "nieważny znak '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX nie pozwala na porównywanie operatorów na zewnÄ…trz, jeÅ›li deklaracje lub pÄ™tle" 23 "POSIX wymaga 0 lub 1 operatora porównawczego na jeden warunek" 24 "POSIX wymaga, aby wszystkie 3 części pÄ™tli nie byÅ‚y puste" -25 "POSIX nie pozwala na notacjÄ™ wykÅ‚adniczÄ…" -26 "POSIX nie zezwala na odniesienia do tablicy jako parametrów funkcji" -27 "POSIX wymaga, aby lewe usztywnienie znajdowaÅ‚o siÄ™ na tej samej linii co nagłówek funkcji" -28 "POSIX nie pozwala na przypisywanie ciÄ…gów znaków do zmiennych lub tablic" +25 "POSIX wymaga nowej linii pomiÄ™dzy Å›rednikiem a definicjÄ… funkcji" +26 "POSIX nie pozwala na notacjÄ™ wykÅ‚adniczÄ…" +27 "POSIX nie zezwala na odniesienia do tablicy jako parametrów funkcji" +28 "POSIX nie dopuszcza funkcji void" +29 "POSIX wymaga, aby lewe usztywnienie znajdowaÅ‚o siÄ™ na tej samej linii co nagłówek funkcji" +30 "POSIX nie pozwala na przypisywanie ciÄ…gów znaków do zmiennych lub tablic" $ BÅ‚Ä™dy Runtime'u. -$set 5 +$set 4 1 "nieprawidÅ‚owa ibase: musi być [%lu, %lu]" 2 "nieprawidÅ‚owa obase: musi być [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "nie może użyć wartoÅ›ci pustej w wyrażeniu" $ Fatalne bÅ‚Ä™dy. -$set 6 +$set 5 1 "Alokacja pamiÄ™ci nie powiodÅ‚a siÄ™" 2 "BÅ‚Ä…d we/wy" diff --git a/contrib/bc/locales/pt_PT.ISO8859-1.msg b/contrib/bc/locales/pt_PT.ISO8859-1.msg index 7a17f0642cc..9b365b4a7bd 100644 --- a/contrib/bc/locales/pt_PT.ISO8859-1.msg +++ b/contrib/bc/locales/pt_PT.ISO8859-1.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Função:" - $ Error types. -$set 2 +$set 1 1 "Erro de cálculo:" 2 "Erro de análise de sintaxe:" @@ -43,7 +38,7 @@ $set 2 5 "Aviso:" $ Math errors. -$set 3 +$set 2 1 "número negativo" 2 "número não inteiro" @@ -51,7 +46,7 @@ $set 3 4 "dividir por 0" $ Parse errors. -$set 4 +$set 3 1 "fim do arquivo" 2 "caractere inválido '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX não permite operadores de comparação fora das expressões 'if' ou loops" 23 "POSIX requer operadores 0 ou 1 de comparação por condição" 24 "POSIX não permite uma expressão vazia em um loop 'for'" -25 "POSIX não permite notação exponencial" -26 "POSIX não permite referências de matriz como parâmetros de função" -27 "POSIX requer que o cabeçalho da função '{' estejam na mesma linha" -28 "POSIX não permite a atribuição de cadeias de caracteres a variáveis ou matrizes" +25 "POSIX requer uma nova linha entre um ponto-e-vírgula e uma definição de função" +26 "POSIX não permite notação exponencial" +27 "POSIX não permite referências de matriz como parâmetros de função" +28 "POSIX não permite funções nulas" +29 "POSIX requer que o cabeçalho da função '{' estejam na mesma linha" +30 "POSIX não permite a atribuição de cadeias de caracteres a variáveis ou matrizes" $ Runtime errors. -$set 5 +$set 4 1 "ibase inválido: deve ser [%lu, %lu]" 2 "obase inválido: deve ser [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "um valor 'void' não pode ser usado em uma expressão" $ Fatal errors. -$set 6 +$set 5 1 "falha na alocação de memória" 2 "erro de entrada-saída" diff --git a/contrib/bc/locales/pt_PT.UTF-8.msg b/contrib/bc/locales/pt_PT.UTF-8.msg index 2f6a4683a37..f5054a178cf 100644 --- a/contrib/bc/locales/pt_PT.UTF-8.msg +++ b/contrib/bc/locales/pt_PT.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Miscellaneous messages. -$set 1 - -1 "Função:" - $ Error types. -$set 2 +$set 1 1 "Erro de cálculo:" 2 "Erro de análise de sintaxe:" @@ -43,7 +38,7 @@ $set 2 5 "Aviso:" $ Math errors. -$set 3 +$set 2 1 "número negativo" 2 "número não inteiro" @@ -51,7 +46,7 @@ $set 3 4 "dividir por 0" $ Parse errors. -$set 4 +$set 3 1 "fim do arquivo" 2 "caractere inválido '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX não permite operadores de comparação fora das expressões 'if' ou loops" 23 "POSIX requer operadores 0 ou 1 de comparação por condição" 24 "POSIX não permite uma expressão vazia em um loop 'for'" -25 "POSIX não permite notação exponencial" -26 "POSIX não permite referências de matriz como parâmetros de função" -27 "POSIX requer que o cabeçalho da função '{' estejam na mesma linha" -28 "POSIX não permite a atribuição de cadeias de caracteres a variáveis ou matrizes" +25 "POSIX requer uma nova linha entre um ponto-e-vírgula e uma definição de função" +26 "POSIX não permite notação exponencial" +27 "POSIX não permite referências de matriz como parâmetros de função" +28 "POSIX não permite funções nulas" +29 "POSIX requer que o cabeçalho da função '{' estejam na mesma linha" +30 "POSIX não permite a atribuição de cadeias de caracteres a variáveis ou matrizes" $ Runtime errors. -$set 5 +$set 4 1 "ibase inválido: deve ser [%lu, %lu]" 2 "obase inválido: deve ser [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "um valor 'void' não pode ser usado em uma expressão" $ Fatal errors. -$set 6 +$set 5 1 "falha na alocação de memória" 2 "erro de entrada-saída" diff --git a/contrib/bc/locales/ru_RU.CP1251.msg b/contrib/bc/locales/ru_RU.CP1251.msg index 6b1d93aa211..ac8957cc6aa 100644 --- a/contrib/bc/locales/ru_RU.CP1251.msg +++ b/contrib/bc/locales/ru_RU.CP1251.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Ðàçíûå ñîîáùåíèÿ. -$set 1 - -1 "Ôóíêöèÿ:" - $ Òèïû îøèáîê. -$set 2 +$set 1 1 "Ìàòåìàòè÷åñêàÿ îøèáêà:" 2 "Îøèáêà ïðè ðàçáîðå:" @@ -43,7 +38,7 @@ $set 2 5 "Ïðåäóïðåæäåíèå:" $ Ìàòåìàòè÷åñêèå îøèáêè. -$set 3 +$set 2 1 "îòðèöàòåëüíîå ÷èñëî" 2 "íåèíòåãðèðîâàííîå ÷èñëî" @@ -51,7 +46,7 @@ $set 3 4 "äåëèòü íà 0" $ Îøèáêè ïðè ðàçáîðå. -$set 4 +$set 3 1 "êîíåö ôàéëà" 2 "íåäîïóñòèìûé ñèìâîë '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX íå ðàçðåøàåò îïåðàòîðàì ñðàâíåíèÿ âûõîäèòü çà ïðåäåëû, åñëè óòâåðæäåíèÿ èëè öèêëû" 23 "POSIX òðåáóåò 0 èëè 1 îïåðàòîðà ñðàâíåíèÿ íà óñëîâèå" 24 "POSIX òðåáóåò, ÷òîáû âñå 3 ÷àñòè ïåòëè áûëè íåïóñòûìè" -25 "POSIX íå äîïóñêàåò ýêñïîíåíöèàëüíîé íîòàöèè" -26 "POSIX íå äîïóñêàåò ññûëêè íà ìàññèâ â êà÷åñòâå ïàðàìåòðîâ ôóíêöèè" -27 "POSIX òðåáóåò, ÷òîáû ëåâàÿ ñêîáêà áûëà íà òîé æå ëèíèè, ÷òî è çàãîëîâîê ôóíêöèè" -28 "POSIX íå ïîçâîëÿåò ïðèñâàèâàòü ñòðîêè ïåðåìåííûì èëè ìàññèâàì" +25 "POSIX òðåáóåò íàëè÷èÿ íîâîé ñòðîêè ìåæäó òî÷êîé ñ çàïÿòîé è îïðåäåëåíèåì ôóíêöèè" +26 "POSIX íå äîïóñêàåò ýêñïîíåíöèàëüíîé íîòàöèè" +27 "POSIX íå äîïóñêàåò ññûëêè íà ìàññèâ â êà÷åñòâå ïàðàìåòðîâ ôóíêöèè" +28 "POSIX íå ðàçðåøàåò ôóíêöèè ïóñòîòû" +29 "POSIX òðåáóåò, ÷òîáû ëåâàÿ ñêîáêà áûëà íà òîé æå ëèíèè, ÷òî è çàãîëîâîê ôóíêöèè" +30 "POSIX íå ïîçâîëÿåò ïðèñâàèâàòü ñòðîêè ïåðåìåííûì èëè ìàññèâàì" $ Îøèáêè âûïîëíåíèÿ. -$set 5 +$set 4 1 "Íåäåéñòâèòåëüíûé ibase: äîëæåí áûòü [%lu, %lu]" 2 "Íåäåéñòâèòåëüíûé obase: äîëæåí áûòü [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "íå ìîæåò èñïîëüçîâàòü ïóñòîå çíà÷åíèå â âûðàæåíèè" $ Ôàòàëüíûå îøèáêè. -$set 6 +$set 5 1 "Íå óäàëîñü âûäåëèòü ïàìÿòü" 2 "Îøèáêà ââîäà/âûâîäà" diff --git a/contrib/bc/locales/ru_RU.CP866.msg b/contrib/bc/locales/ru_RU.CP866.msg index b693428b9a3..763fd55a365 100644 --- a/contrib/bc/locales/ru_RU.CP866.msg +++ b/contrib/bc/locales/ru_RU.CP866.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$  §­ë¥ á®®¡é¥­¨ï. -$set 1 - -1 "”ã­ªæ¨ï:" - $ ’¨¯ë ®è¨¡®ª. -$set 2 +$set 1 1 "Œ â¥¬ â¨ç¥áª ï ®è¨¡ª :" 2 "Žè¨¡ª  ¯à¨ à §¡®à¥:" @@ -43,7 +38,7 @@ $set 2 5 "।ã¯à¥¦¤¥­¨¥:" $ Œ â¥¬ â¨ç¥áª¨¥ ®è¨¡ª¨. -$set 3 +$set 2 1 "®âà¨æ â¥«ì­®¥ ç¨á«®" 2 "­¥¨­â¥£à¨à®¢ ­­®¥ ç¨á«®" @@ -51,7 +46,7 @@ $set 3 4 "¤¥«¨âì ­  0" $ Žè¨¡ª¨ ¯à¨ à §¡®à¥. -$set 4 +$set 3 1 "ª®­¥æ ä ©« " 2 "­¥¤®¯ãáâ¨¬ë© á¨¬¢®« '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX ­¥ à §à¥è ¥â ®¯¥à â®à ¬ áà ¢­¥­¨ï ¢ë室¨âì §  ¯à¥¤¥«ë, ¥á«¨ ã⢥ত¥­¨ï ¨«¨ 横«ë" 23 "POSIX âॡã¥â 0 ¨«¨ 1 ®¯¥à â®à  áà ¢­¥­¨ï ­  ãá«®¢¨¥" 24 "POSIX âॡã¥â, çâ®¡ë ¢á¥ 3 ç á⨠¯¥â«¨ ¡ë«¨ ­¥¯ãáâ묨" -25 "POSIX ­¥ ¤®¯ã᪠¥â íªá¯®­¥­æ¨ «ì­®© ­®â æ¨¨" -26 "POSIX ­¥ ¤®¯ã᪠¥â áá뫪¨ ­  ¬ áᨢ ¢ ª ç¥á⢥ ¯ à ¬¥â஢ ä㭪樨" -27 "POSIX âॡã¥â, çâ®¡ë «¥¢ ï ᪮¡ª  ¡ë«  ­  ⮩ ¦¥ «¨­¨¨, çâ® ¨ § £®«®¢®ª ä㭪樨" -28 "POSIX ­¥ ¯®§¢®«ï¥â ¯à¨á¢ ¨¢ âì áâப¨ ¯¥à¥¬¥­­ë¬ ¨«¨ ¬ áᨢ ¬" +25 "POSIX âॡã¥â ­ «¨ç¨ï ­®¢®© áâப¨ ¬¥¦¤ã â®çª®© á § ¯ï⮩ ¨ ®¯à¥¤¥«¥­¨¥¬ ä㭪樨" +26 "POSIX ­¥ ¤®¯ã᪠¥â íªá¯®­¥­æ¨ «ì­®© ­®â æ¨¨" +27 "POSIX ­¥ ¤®¯ã᪠¥â áá뫪¨ ­  ¬ áᨢ ¢ ª ç¥á⢥ ¯ à ¬¥â஢ ä㭪樨" +28 "POSIX ­¥ à §à¥è ¥â ä㭪樨 ¯ãáâ®âë" +29 "POSIX âॡã¥â, çâ®¡ë «¥¢ ï ᪮¡ª  ¡ë«  ­  ⮩ ¦¥ «¨­¨¨, çâ® ¨ § £®«®¢®ª ä㭪樨" +30 "POSIX ­¥ ¯®§¢®«ï¥â ¯à¨á¢ ¨¢ âì áâப¨ ¯¥à¥¬¥­­ë¬ ¨«¨ ¬ áᨢ ¬" $ Žè¨¡ª¨ ¢ë¯®«­¥­¨ï. -$set 5 +$set 4 1 "¥¤¥©á⢨⥫ì­ë© ibase: ¤®«¦¥­ ¡ëâì [%lu, %lu]" 2 "¥¤¥©á⢨⥫ì­ë© obase: ¤®«¦¥­ ¡ëâì [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "­¥ ¬®¦¥â ¨á¯®«ì§®¢ âì ¯ãá⮥ §­ ç¥­¨¥ ¢ ¢ëà ¦¥­¨¨" $ ” â «ì­ë¥ ®è¨¡ª¨. -$set 6 +$set 5 1 "¥ 㤠«®áì ¢ë¤¥«¨âì ¯ ¬ïâì" 2 "Žè¨¡ª  ¢¢®¤ /¢ë¢®¤ " diff --git a/contrib/bc/locales/ru_RU.ISO8859-5.msg b/contrib/bc/locales/ru_RU.ISO8859-5.msg index 35af400c583..bbb1f418c3a 100644 --- a/contrib/bc/locales/ru_RU.ISO8859-5.msg +++ b/contrib/bc/locales/ru_RU.ISO8859-5.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ÀÐ×ÝëÕ áÞÞÑéÕÝØï. -$set 1 - -1 "ÄãÝÚæØï:" - $ ÂØßë ÞèØÑÞÚ. -$set 2 +$set 1 1 "¼ÐâÕÜÐâØçÕáÚÐï ÞèØÑÚÐ:" 2 "¾èØÑÚÐ ßàØ àÐ×ÑÞàÕ:" @@ -43,7 +38,7 @@ $set 2 5 "¿àÕÔãßàÕÖÔÕÝØÕ:" $ ¼ÐâÕÜÐâØçÕáÚØÕ ÞèØÑÚØ. -$set 3 +$set 2 1 "ÞâàØæÐâÕÛìÝÞÕ çØáÛÞ" 2 "ÝÕØÝâÕÓàØàÞÒÐÝÝÞÕ çØáÛÞ" @@ -51,7 +46,7 @@ $set 3 4 "ÔÕÛØâì ÝÐ 0" $ ¾èØÑÚØ ßàØ àÐ×ÑÞàÕ. -$set 4 +$set 3 1 "ÚÞÝÕæ äÐÙÛÐ" 2 "ÝÕÔÞßãáâØÜëÙ áØÜÒÞÛ '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX ÝÕ àÐ×àÕèÐÕâ ÞßÕàÐâÞàÐÜ áàÐÒÝÕÝØï ÒëåÞÔØâì ×Ð ßàÕÔÕÛë, ÕáÛØ ãâÒÕàÖÔÕÝØï ØÛØ æØÚÛë" 23 "POSIX âàÕÑãÕâ 0 ØÛØ 1 ÞßÕàÐâÞàÐ áàÐÒÝÕÝØï ÝÐ ãáÛÞÒØÕ" 24 "POSIX âàÕÑãÕâ, çâÞÑë ÒáÕ 3 çÐáâØ ßÕâÛØ ÑëÛØ ÝÕßãáâëÜØ" -25 "POSIX ÝÕ ÔÞßãáÚÐÕâ íÚáßÞÝÕÝæØÐÛìÝÞÙ ÝÞâÐæØØ" -26 "POSIX ÝÕ ÔÞßãáÚÐÕâ ááëÛÚØ ÝÐ ÜÐááØÒ Ò ÚÐçÕáâÒÕ ßÐàÐÜÕâàÞÒ äãÝÚæØØ" -27 "POSIX âàÕÑãÕâ, çâÞÑë ÛÕÒÐï áÚÞÑÚÐ ÑëÛÐ ÝÐ âÞÙ ÖÕ ÛØÝØØ, çâÞ Ø ×ÐÓÞÛÞÒÞÚ äãÝÚæØØ" -28 "POSIX ÝÕ ßÞ×ÒÞÛïÕâ ßàØáÒÐØÒÐâì áâàÞÚØ ßÕàÕÜÕÝÝëÜ ØÛØ ÜÐááØÒÐÜ" +25 "POSIX âàÕÑãÕâ ÝÐÛØçØï ÝÞÒÞÙ áâàÞÚØ ÜÕÖÔã âÞçÚÞÙ á ×ÐßïâÞÙ Ø ÞßàÕÔÕÛÕÝØÕÜ äãÝÚæØØ" +26 "POSIX ÝÕ ÔÞßãáÚÐÕâ íÚáßÞÝÕÝæØÐÛìÝÞÙ ÝÞâÐæØØ" +27 "POSIX ÝÕ ÔÞßãáÚÐÕâ ááëÛÚØ ÝÐ ÜÐááØÒ Ò ÚÐçÕáâÒÕ ßÐàÐÜÕâàÞÒ äãÝÚæØØ" +28 "POSIX ÝÕ àÐ×àÕèÐÕâ äãÝÚæØØ ßãáâÞâë" +29 "POSIX âàÕÑãÕâ, çâÞÑë ÛÕÒÐï áÚÞÑÚÐ ÑëÛÐ ÝÐ âÞÙ ÖÕ ÛØÝØØ, çâÞ Ø ×ÐÓÞÛÞÒÞÚ äãÝÚæØØ" +30 "POSIX ÝÕ ßÞ×ÒÞÛïÕâ ßàØáÒÐØÒÐâì áâàÞÚØ ßÕàÕÜÕÝÝëÜ ØÛØ ÜÐááØÒÐÜ" $ ¾èØÑÚØ ÒëßÞÛÝÕÝØï. -$set 5 +$set 4 1 "½ÕÔÕÙáâÒØâÕÛìÝëÙ ibase: ÔÞÛÖÕÝ Ñëâì [%lu, %lu]" 2 "½ÕÔÕÙáâÒØâÕÛìÝëÙ obase: ÔÞÛÖÕÝ Ñëâì [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "ÝÕ ÜÞÖÕâ ØáßÞÛì×ÞÒÐâì ßãáâÞÕ ×ÝÐçÕÝØÕ Ò ÒëàÐÖÕÝØØ" $ ÄÐâÐÛìÝëÕ ÞèØÑÚØ. -$set 6 +$set 5 1 "½Õ ãÔÐÛÞáì ÒëÔÕÛØâì ßÐÜïâì" 2 "¾èØÑÚÐ ÒÒÞÔÐ/ÒëÒÞÔÐ" diff --git a/contrib/bc/locales/ru_RU.KOI8-R.msg b/contrib/bc/locales/ru_RU.KOI8-R.msg index 98c66709585..d1e2bdc014d 100644 --- a/contrib/bc/locales/ru_RU.KOI8-R.msg +++ b/contrib/bc/locales/ru_RU.KOI8-R.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ òÁÚÎÙÅ ÓÏÏÂÝÅÎÉÑ. -$set 1 - -1 "æÕÎËÃÉÑ:" - $ ôÉÐÙ ÏÛÉÂÏË. -$set 2 +$set 1 1 "íÁÔÅÍÁÔÉÞÅÓËÁÑ ÏÛÉÂËÁ:" 2 "ïÛÉÂËÁ ÐÒÉ ÒÁÚÂÏÒÅ:" @@ -43,7 +38,7 @@ $set 2 5 "ðÒÅÄÕÐÒÅÖÄÅÎÉÅ:" $ íÁÔÅÍÁÔÉÞÅÓËÉÅ ÏÛÉÂËÉ. -$set 3 +$set 2 1 "ÏÔÒÉÃÁÔÅÌØÎÏÅ ÞÉÓÌÏ" 2 "ÎÅÉÎÔÅÇÒÉÒÏ×ÁÎÎÏÅ ÞÉÓÌÏ" @@ -51,7 +46,7 @@ $set 3 4 "ÄÅÌÉÔØ ÎÁ 0" $ ïÛÉÂËÉ ÐÒÉ ÒÁÚÂÏÒÅ. -$set 4 +$set 3 1 "ËÏÎÅà ÆÁÊÌÁ" 2 "ÎÅÄÏÐÕÓÔÉÍÙÊ ÓÉÍ×ÏÌ '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX ÎÅ ÒÁÚÒÅÛÁÅÔ ÏÐÅÒÁÔÏÒÁÍ ÓÒÁ×ÎÅÎÉÑ ×ÙÈÏÄÉÔØ ÚÁ ÐÒÅÄÅÌÙ, ÅÓÌÉ ÕÔ×ÅÒÖÄÅÎÉÑ ÉÌÉ ÃÉËÌÙ" 23 "POSIX ÔÒÅÂÕÅÔ 0 ÉÌÉ 1 ÏÐÅÒÁÔÏÒÁ ÓÒÁ×ÎÅÎÉÑ ÎÁ ÕÓÌÏ×ÉÅ" 24 "POSIX ÔÒÅÂÕÅÔ, ÞÔÏÂÙ ×ÓÅ 3 ÞÁÓÔÉ ÐÅÔÌÉ ÂÙÌÉ ÎÅÐÕÓÔÙÍÉ" -25 "POSIX ÎÅ ÄÏÐÕÓËÁÅÔ ÜËÓÐÏÎÅÎÃÉÁÌØÎÏÊ ÎÏÔÁÃÉÉ" -26 "POSIX ÎÅ ÄÏÐÕÓËÁÅÔ ÓÓÙÌËÉ ÎÁ ÍÁÓÓÉ× × ËÁÞÅÓÔ×Å ÐÁÒÁÍÅÔÒÏ× ÆÕÎËÃÉÉ" -27 "POSIX ÔÒÅÂÕÅÔ, ÞÔÏÂÙ ÌÅ×ÁÑ ÓËÏÂËÁ ÂÙÌÁ ÎÁ ÔÏÊ ÖÅ ÌÉÎÉÉ, ÞÔÏ É ÚÁÇÏÌÏ×ÏË ÆÕÎËÃÉÉ" -28 "POSIX ÎÅ ÐÏÚ×ÏÌÑÅÔ ÐÒÉÓ×ÁÉ×ÁÔØ ÓÔÒÏËÉ ÐÅÒÅÍÅÎÎÙÍ ÉÌÉ ÍÁÓÓÉ×ÁÍ" +25 "POSIX ÔÒÅÂÕÅÔ ÎÁÌÉÞÉÑ ÎÏ×ÏÊ ÓÔÒÏËÉ ÍÅÖÄÕ ÔÏÞËÏÊ Ó ÚÁÐÑÔÏÊ É ÏÐÒÅÄÅÌÅÎÉÅÍ ÆÕÎËÃÉÉ" +26 "POSIX ÎÅ ÄÏÐÕÓËÁÅÔ ÜËÓÐÏÎÅÎÃÉÁÌØÎÏÊ ÎÏÔÁÃÉÉ" +27 "POSIX ÎÅ ÄÏÐÕÓËÁÅÔ ÓÓÙÌËÉ ÎÁ ÍÁÓÓÉ× × ËÁÞÅÓÔ×Å ÐÁÒÁÍÅÔÒÏ× ÆÕÎËÃÉÉ" +28 "POSIX ÎÅ ÒÁÚÒÅÛÁÅÔ ÆÕÎËÃÉÉ ÐÕÓÔÏÔÙ" +29 "POSIX ÔÒÅÂÕÅÔ, ÞÔÏÂÙ ÌÅ×ÁÑ ÓËÏÂËÁ ÂÙÌÁ ÎÁ ÔÏÊ ÖÅ ÌÉÎÉÉ, ÞÔÏ É ÚÁÇÏÌÏ×ÏË ÆÕÎËÃÉÉ" +30 "POSIX ÎÅ ÐÏÚ×ÏÌÑÅÔ ÐÒÉÓ×ÁÉ×ÁÔØ ÓÔÒÏËÉ ÐÅÒÅÍÅÎÎÙÍ ÉÌÉ ÍÁÓÓÉ×ÁÍ" $ ïÛÉÂËÉ ×ÙÐÏÌÎÅÎÉÑ. -$set 5 +$set 4 1 "îÅÄÅÊÓÔ×ÉÔÅÌØÎÙÊ ibase: ÄÏÌÖÅÎ ÂÙÔØ [%lu, %lu]" 2 "îÅÄÅÊÓÔ×ÉÔÅÌØÎÙÊ obase: ÄÏÌÖÅÎ ÂÙÔØ [%lu, %lu]" @@ -97,7 +94,7 @@ $set 5 10 "ÎÅ ÍÏÖÅÔ ÉÓÐÏÌØÚÏ×ÁÔØ ÐÕÓÔÏÅ ÚÎÁÞÅÎÉÅ × ×ÙÒÁÖÅÎÉÉ" $ æÁÔÁÌØÎÙÅ ÏÛÉÂËÉ. -$set 6 +$set 5 1 "îÅ ÕÄÁÌÏÓØ ×ÙÄÅÌÉÔØ ÐÁÍÑÔØ" 2 "ïÛÉÂËÁ ××ÏÄÁ/×Ù×ÏÄÁ" diff --git a/contrib/bc/locales/ru_RU.UTF-8.msg b/contrib/bc/locales/ru_RU.UTF-8.msg index f7c1dc58c4d..b45b3634a76 100644 --- a/contrib/bc/locales/ru_RU.UTF-8.msg +++ b/contrib/bc/locales/ru_RU.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ Разные ÑообщениÑ. -$set 1 - -1 "ФункциÑ:" - $ Типы ошибок. -$set 2 +$set 1 1 "МатематичеÑÐºÐ°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ°:" 2 "Ошибка при разборе:" @@ -43,7 +38,7 @@ $set 2 5 "Предупреждение:" $ МатематичеÑкие ошибки. -$set 3 +$set 2 1 "отрицательное чиÑло" 2 "неинтегрированное чиÑло" @@ -51,7 +46,7 @@ $set 3 4 "делить на 0" $ Ошибки при разборе. -$set 4 +$set 3 1 "конец файла" 2 "недопуÑтимый Ñимвол '%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX не разрешает операторам ÑÑ€Ð°Ð²Ð½ÐµÐ½Ð¸Ñ Ð²Ñ‹Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒ за пределы, еÑли ÑƒÑ‚Ð²ÐµÑ€Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¸Ð»Ð¸ циклы" 23 "POSIX требует 0 или 1 оператора ÑÑ€Ð°Ð²Ð½ÐµÐ½Ð¸Ñ Ð½Ð° уÑловие" 24 "POSIX требует, чтобы вÑе 3 чаÑти петли были непуÑтыми" -25 "POSIX не допуÑкает ÑкÑпоненциальной нотации" -26 "POSIX не допуÑкает ÑÑылки на маÑÑив в качеÑтве параметров функции" -27 "POSIX требует, чтобы Ð»ÐµÐ²Ð°Ñ Ñкобка была на той же линии, что и заголовок функции" -28 "POSIX не позволÑет приÑваивать Ñтроки переменным или маÑÑивам" +25 "POSIX требует Ð½Ð°Ð»Ð¸Ñ‡Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð¹ Ñтроки между точкой Ñ Ð·Ð°Ð¿Ñтой и определением функции" +26 "POSIX не допуÑкает ÑкÑпоненциальной нотации" +27 "POSIX не допуÑкает ÑÑылки на маÑÑив в качеÑтве параметров функции" +28 "POSIX не разрешает функции пуÑтоты" +29 "POSIX требует, чтобы Ð»ÐµÐ²Ð°Ñ Ñкобка была на той же линии, что и заголовок функции" +30 "POSIX не позволÑет приÑваивать Ñтроки переменным или маÑÑивам" $ Ошибки выполнениÑ. -$set 5 +$set 4 1 "ÐедейÑтвительный ibase: должен быть [%lu, %lu]" 2 "ÐедейÑтвительный obase: должен быть [%lu, %lu]" @@ -98,7 +95,7 @@ $set 5 11 "не может иÑпользовать пуÑтое значение в выражении" $ Фатальные ошибки. -$set 6 +$set 5 1 "Ðе удалоÑÑŒ выделить памÑÑ‚ÑŒ" 2 "Ошибка ввода/вывода" diff --git a/contrib/bc/locales/zh_CN.GB18030.msg b/contrib/bc/locales/zh_CN.GB18030.msg index fb80db7de55..3625c5b40fd 100644 --- a/contrib/bc/locales/zh_CN.GB18030.msg +++ b/contrib/bc/locales/zh_CN.GB18030.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ÔÓÏîÐÅÏ¢¡£ -$set 1 - -1 "º¯Êý£º" - $ ´íÎóÀàÐÍ¡£ -$set 2 +$set 1 1 "Êýѧ´íÎó£º" 2 "½âÎö´íÎó£º" @@ -43,7 +38,7 @@ $set 2 5 "¾¯¸æ£º" $ Êýѧ´íÎó¡£ -$set 3 +$set 2 1 "¸ºÊý" 2 "·ÇÕûÊý" @@ -51,7 +46,7 @@ $set 3 4 "³ýÒÔ0" $ ½âÎö´íÎó¡£ -$set 4 +$set 3 1 "Îļþ½áÊø" 2 "ÎÞЧ×Ö·û'%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX²»ÔÊÐíÔÚifÓï¾ä»òÑ­»·Ö®ÍâµÄ±È½ÏÔËËã·û" 23 "POSIXÒªÇóÿ¸öÌõ¼þµÄ±È½ÏÔËËã·ûΪ0»ò1¸ö" 24 "POSIXÒªÇóforÑ­»·µÄËùÓÐ3¸ö²¿·Ö±ØÐëÊÇ·Ç¿ÕµÄ" -25 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" -26 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" -27 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" -28 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" +25 "POSIXÒªÇóÔڷֺźͺ¯Êý¶¨ÒåÖ®¼äʹÓû»Ðзû" +26 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" +27 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" +28 "POSIX²»ÔÊÐíÎÞЧº¯Êý" +29 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" +30 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" $ ÔËÐÐʱ´íÎó¡£ -$set 5 +$set 4 1 "ÎÞЧµÄibase: ±ØÐëÊÇ[%lu, %lu]" 2 "ÎÞЧµÄobase£º±ØÐëÊÇ[%lu£¬%lu]" @@ -98,7 +95,7 @@ $set 5 11 ¡°²»ÄÜÔÚ±í´ïʽÖÐʹÓÿÕÖµ¡± $ ÖÂÃü´íÎó¡£ -$set 6 +$set 5 1 "ÄÚ´æ·ÖÅäʧ°Ü" 2 "I/O´íÎó" diff --git a/contrib/bc/locales/zh_CN.GB2312.msg b/contrib/bc/locales/zh_CN.GB2312.msg index fb80db7de55..3625c5b40fd 100644 --- a/contrib/bc/locales/zh_CN.GB2312.msg +++ b/contrib/bc/locales/zh_CN.GB2312.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ÔÓÏîÐÅÏ¢¡£ -$set 1 - -1 "º¯Êý£º" - $ ´íÎóÀàÐÍ¡£ -$set 2 +$set 1 1 "Êýѧ´íÎó£º" 2 "½âÎö´íÎó£º" @@ -43,7 +38,7 @@ $set 2 5 "¾¯¸æ£º" $ Êýѧ´íÎó¡£ -$set 3 +$set 2 1 "¸ºÊý" 2 "·ÇÕûÊý" @@ -51,7 +46,7 @@ $set 3 4 "³ýÒÔ0" $ ½âÎö´íÎó¡£ -$set 4 +$set 3 1 "Îļþ½áÊø" 2 "ÎÞЧ×Ö·û'%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX²»ÔÊÐíÔÚifÓï¾ä»òÑ­»·Ö®ÍâµÄ±È½ÏÔËËã·û" 23 "POSIXÒªÇóÿ¸öÌõ¼þµÄ±È½ÏÔËËã·ûΪ0»ò1¸ö" 24 "POSIXÒªÇóforÑ­»·µÄËùÓÐ3¸ö²¿·Ö±ØÐëÊÇ·Ç¿ÕµÄ" -25 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" -26 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" -27 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" -28 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" +25 "POSIXÒªÇóÔڷֺźͺ¯Êý¶¨ÒåÖ®¼äʹÓû»Ðзû" +26 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" +27 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" +28 "POSIX²»ÔÊÐíÎÞЧº¯Êý" +29 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" +30 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" $ ÔËÐÐʱ´íÎó¡£ -$set 5 +$set 4 1 "ÎÞЧµÄibase: ±ØÐëÊÇ[%lu, %lu]" 2 "ÎÞЧµÄobase£º±ØÐëÊÇ[%lu£¬%lu]" @@ -98,7 +95,7 @@ $set 5 11 ¡°²»ÄÜÔÚ±í´ïʽÖÐʹÓÿÕÖµ¡± $ ÖÂÃü´íÎó¡£ -$set 6 +$set 5 1 "ÄÚ´æ·ÖÅäʧ°Ü" 2 "I/O´íÎó" diff --git a/contrib/bc/locales/zh_CN.GBK.msg b/contrib/bc/locales/zh_CN.GBK.msg index fb80db7de55..3625c5b40fd 100644 --- a/contrib/bc/locales/zh_CN.GBK.msg +++ b/contrib/bc/locales/zh_CN.GBK.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ÔÓÏîÐÅÏ¢¡£ -$set 1 - -1 "º¯Êý£º" - $ ´íÎóÀàÐÍ¡£ -$set 2 +$set 1 1 "Êýѧ´íÎó£º" 2 "½âÎö´íÎó£º" @@ -43,7 +38,7 @@ $set 2 5 "¾¯¸æ£º" $ Êýѧ´íÎó¡£ -$set 3 +$set 2 1 "¸ºÊý" 2 "·ÇÕûÊý" @@ -51,7 +46,7 @@ $set 3 4 "³ýÒÔ0" $ ½âÎö´íÎó¡£ -$set 4 +$set 3 1 "Îļþ½áÊø" 2 "ÎÞЧ×Ö·û'%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX²»ÔÊÐíÔÚifÓï¾ä»òÑ­»·Ö®ÍâµÄ±È½ÏÔËËã·û" 23 "POSIXÒªÇóÿ¸öÌõ¼þµÄ±È½ÏÔËËã·ûΪ0»ò1¸ö" 24 "POSIXÒªÇóforÑ­»·µÄËùÓÐ3¸ö²¿·Ö±ØÐëÊÇ·Ç¿ÕµÄ" -25 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" -26 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" -27 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" -28 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" +25 "POSIXÒªÇóÔڷֺźͺ¯Êý¶¨ÒåÖ®¼äʹÓû»Ðзû" +26 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" +27 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" +28 "POSIX²»ÔÊÐíÎÞЧº¯Êý" +29 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" +30 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" $ ÔËÐÐʱ´íÎó¡£ -$set 5 +$set 4 1 "ÎÞЧµÄibase: ±ØÐëÊÇ[%lu, %lu]" 2 "ÎÞЧµÄobase£º±ØÐëÊÇ[%lu£¬%lu]" @@ -98,7 +95,7 @@ $set 5 11 ¡°²»ÄÜÔÚ±í´ïʽÖÐʹÓÿÕÖµ¡± $ ÖÂÃü´íÎó¡£ -$set 6 +$set 5 1 "ÄÚ´æ·ÖÅäʧ°Ü" 2 "I/O´íÎó" diff --git a/contrib/bc/locales/zh_CN.UTF-8.msg b/contrib/bc/locales/zh_CN.UTF-8.msg index c327c0b1b98..95813f41169 100644 --- a/contrib/bc/locales/zh_CN.UTF-8.msg +++ b/contrib/bc/locales/zh_CN.UTF-8.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ æ‚项信æ¯ã€‚ -$set 1 - -1 "函数:" - $ 错误类型。 -$set 2 +$set 1 1 "数学错误:" 2 "解æžé”™è¯¯ï¼š" @@ -43,7 +38,7 @@ $set 2 5 "警告:" $ 数学错误。 -$set 3 +$set 2 1 "è´Ÿæ•°" 2 "éžæ•´æ•°" @@ -51,7 +46,7 @@ $set 3 4 "除以0" $ 解æžé”™è¯¯ã€‚ -$set 4 +$set 3 1 "文件结æŸ" 2 "无效字符'%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIXä¸å…许在if语å¥æˆ–循环之外的比较è¿ç®—符" 23 "POSIXè¦æ±‚æ¯ä¸ªæ¡ä»¶çš„比较è¿ç®—符为0或1个" 24 "POSIXè¦æ±‚for循环的所有3个部分必须是éžç©ºçš„" -25 "POSIXä¸å…许使用指数符å·" -26 "POSIXä¸å…许数组引用作为函数å‚æ•°" -27 "POSIXè¦æ±‚左边的括å·å’Œå‡½æ•°å¤´åœ¨åŒä¸€è¡Œä¸Š" -28 "POSIXä¸å…许将字符串分é…ç»™å˜é‡æˆ–数组" +25 "POSIXè¦æ±‚在分å·å’Œå‡½æ•°å®šä¹‰ä¹‹é—´ä½¿ç”¨æ¢è¡Œç¬¦" +26 "POSIXä¸å…许使用指数符å·" +27 "POSIXä¸å…许数组引用作为函数å‚æ•°" +28 "POSIXä¸å…许无效函数" +29 "POSIXè¦æ±‚左边的括å·å’Œå‡½æ•°å¤´åœ¨åŒä¸€è¡Œä¸Š" +30 "POSIXä¸å…许将字符串分é…ç»™å˜é‡æˆ–数组" $ è¿è¡Œæ—¶é”™è¯¯ã€‚ -$set 5 +$set 4 1 "无效的ibase: 必须是[%lu, %lu]" 2 "无效的obase:必须是[%lu,%lu]" @@ -98,7 +95,7 @@ $set 5 11 “ä¸èƒ½åœ¨è¡¨è¾¾å¼ä¸­ä½¿ç”¨ç©ºå€¼â€ $ 致命错误。 -$set 6 +$set 5 1 "内存分é…失败" 2 "I/O错误" diff --git a/contrib/bc/locales/zh_CN.eucCN.msg b/contrib/bc/locales/zh_CN.eucCN.msg index fb80db7de55..3625c5b40fd 100644 --- a/contrib/bc/locales/zh_CN.eucCN.msg +++ b/contrib/bc/locales/zh_CN.eucCN.msg @@ -1,7 +1,7 @@ $ $ $ SPDX-License-Identifier: BSD-2-Clause $ $ -$ Copyright (c) 2018-2021 Gavin D. Howard and contributors. +$ Copyright (c) 2018-2024 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: @@ -28,13 +28,8 @@ $ $ $quote " -$ ÔÓÏîÐÅÏ¢¡£ -$set 1 - -1 "º¯Êý£º" - $ ´íÎóÀàÐÍ¡£ -$set 2 +$set 1 1 "Êýѧ´íÎó£º" 2 "½âÎö´íÎó£º" @@ -43,7 +38,7 @@ $set 2 5 "¾¯¸æ£º" $ Êýѧ´íÎó¡£ -$set 3 +$set 2 1 "¸ºÊý" 2 "·ÇÕûÊý" @@ -51,7 +46,7 @@ $set 3 4 "³ýÒÔ0" $ ½âÎö´íÎó¡£ -$set 4 +$set 3 1 "Îļþ½áÊø" 2 "ÎÞЧ×Ö·û'%c'" @@ -77,13 +72,15 @@ $set 4 22 "POSIX²»ÔÊÐíÔÚifÓï¾ä»òÑ­»·Ö®ÍâµÄ±È½ÏÔËËã·û" 23 "POSIXÒªÇóÿ¸öÌõ¼þµÄ±È½ÏÔËËã·ûΪ0»ò1¸ö" 24 "POSIXÒªÇóforÑ­»·µÄËùÓÐ3¸ö²¿·Ö±ØÐëÊÇ·Ç¿ÕµÄ" -25 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" -26 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" -27 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" -28 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" +25 "POSIXÒªÇóÔڷֺźͺ¯Êý¶¨ÒåÖ®¼äʹÓû»Ðзû" +26 "POSIX²»ÔÊÐíʹÓÃÖ¸Êý·ûºÅ" +27 "POSIX²»ÔÊÐíÊý×éÒýÓÃ×÷Ϊº¯Êý²ÎÊý" +28 "POSIX²»ÔÊÐíÎÞЧº¯Êý" +29 "POSIXÒªÇó×ó±ßµÄÀ¨ºÅºÍº¯ÊýÍ·ÔÚͬһÐÐÉÏ" +30 "POSIX²»ÔÊÐí½«×Ö·û´®·ÖÅä¸ø±äÁ¿»òÊý×é" $ ÔËÐÐʱ´íÎó¡£ -$set 5 +$set 4 1 "ÎÞЧµÄibase: ±ØÐëÊÇ[%lu, %lu]" 2 "ÎÞЧµÄobase£º±ØÐëÊÇ[%lu£¬%lu]" @@ -98,7 +95,7 @@ $set 5 11 ¡°²»ÄÜÔÚ±í´ïʽÖÐʹÓÿÕÖµ¡± $ ÖÂÃü´íÎó¡£ -$set 6 +$set 5 1 "ÄÚ´æ·ÖÅäʧ°Ü" 2 "I/O´íÎó" diff --git a/contrib/bc/manuals/algorithms.md b/contrib/bc/manuals/algorithms.md index ef6b6d99a65..ce27bf026b6 100644 --- a/contrib/bc/manuals/algorithms.md +++ b/contrib/bc/manuals/algorithms.md @@ -178,7 +178,7 @@ to calculate the bessel when `x < 0`, It has a complexity of `O(n^3)`. their calculations with the precision (`scale`) set to at least 1 greater than is needed. -### Modular Exponentiation (`dc` Only) +### Modular Exponentiation This `dc` uses the [Memory-efficient method][8] to compute modular exponentiation. The complexity is `O(e*n^2)`, which may initially seem @@ -193,6 +193,74 @@ The algorithm used is to use the formula `e(y*l(x))`. It has a complexity of `O(n^3)` because both `e()` and `l()` do. +However, there are details to this algorithm, described by the author, +TediusTimmy, in GitHub issue [#69][12]. + +First, check if the exponent is 0. If it is, return 1 at the appropriate +`scale`. + +Next, check if the number is 0. If so, check if the exponent is greater than +zero; if it is, return 0. If the exponent is less than 0, error (with a divide +by 0) because that is undefined. + +Next, check if the exponent is actually an integer, and if it is, use the +exponentiation operator. + +At the `z=0` line is the start of the meat of the new code. + +`z` is set to zero as a flag and as a value. What I mean by that will be clear +later. + +Then we check if the number is less than 0. If it is, we negate the exponent +(and the integer version of the exponent, which we calculated earlier to check +if it was an integer). We also save the number in `z`; being non-zero is a flag +for later and a value to be used. Then we store the reciprocal of the number in +itself. + +All of the above paragraph will not make sense unless you remember the +relationship `l(x) == -l(1/x)`; we negated the exponent, which is equivalent to +the negative sign in that relationship, and we took the reciprocal of the +number, which is equivalent to the reciprocal in the relationship. + +But what if the number is negative? We ignore that for now because we eventually +call `l(x)`, which will raise an error if `x` is negative. + +Now, we can keep going. + +If at this point, the exponent is negative, we need to use the original formula +(`e(y * l(x))`) and return that result because the result will go to zero +anyway. + +But if we did *not* return, we know the exponent is *not* negative, so we can +get clever. + +We then compute the integral portion of the power by computing the number to +power of the integral portion of the exponent. + +Then we have the most clever trick: we add the length of that integer power (and +a little extra) to the `scale`. Why? Because this will ensure that the next part +is calculated to at least as many digits as should be in the integer *plus* any +extra `scale` that was wanted. + +Then we check `z`, which, if it is not zero, is the original value of the +number. If it is not zero, we need to take the take the reciprocal *again* +because now we have the correct `scale`. And we *also* have to calculate the +integer portion of the power again. + +Then we need to calculate the fractional portion of the number. We do this by +using the original formula, but we instead of calculating `e(y * l(x))`, we +calculate `e((y - a) * l(x))`, where `a` is the integer portion of `y`. It's +easy to see that `y - a` will be just the fractional portion of `y` (the +exponent), so this makes sense. + +But then we *multiply* it into the integer portion of the power. Why? Because +remember: we're dealing with an exponent and a power; the relationship is +`x^(y+z) == (x^y)*(x^z)`. + +So we multiply it into the integer portion of the power. + +Finally, we set the result to the `scale`. + ### Rounding (`bc` Math Library 2 Only) This is implemented in the function `r(x,p)`. @@ -327,3 +395,4 @@ It has a complexity of `O(n^3)` because of arctangent. [9]: https://en.wikipedia.org/wiki/Root-finding_algorithms#Newton's_method_(and_similar_derivative-based_methods) [10]: https://en.wikipedia.org/wiki/Euclidean_algorithm [11]: https://en.wikipedia.org/wiki/Atan2#Definition_and_computation +[12]: https://github.com/gavinhoward/bc/issues/69 diff --git a/contrib/bc/manuals/bc/A.1 b/contrib/bc/manuals/bc/A.1 index bf6c9108456..adeb62f82e6 100644 --- a/contrib/bc/manuals/bc/A.1 +++ b/contrib/bc/manuals/bc/A.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,34 +25,38 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. @@ -61,19 +65,114 @@ implementations. 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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -86,19 +185,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -106,8 +202,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -125,12 +220,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -140,53 +233,63 @@ 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 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 +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] +.EX seed = seed -\f[R] -.fi +.EE .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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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 @@ -196,11 +299,23 @@ command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -208,14 +323,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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). +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 @@ -223,16 +355,16 @@ 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. +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]. +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] +\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 @@ -287,108 +419,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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. +\f[B]plznl(x)\f[R], \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]. +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]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -402,8 +490,7 @@ 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]. +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]. @@ -411,7 +498,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -419,13 +506,12 @@ 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. +\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 @@ -433,12 +519,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -446,32 +530,32 @@ 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 +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]. +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]. +\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 +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. +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 +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 @@ -479,8 +563,8 @@ 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]. +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] @@ -490,7 +574,7 @@ exceptions. \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. +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 @@ -515,20 +599,18 @@ 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]. +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]. +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] @@ -545,26 +627,26 @@ Array Elements: \f[B]I[E]\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]. +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 +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 +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. +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. +\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 @@ -585,7 +667,6 @@ Named expressions are required as the operand of 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). @@ -595,99 +676,113 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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] +This is a \f[B]non\-portable extension\f[R]. +.IP "23." 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 "21." 4 -\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] +This is a \f[B]non\-portable extension\f[R]. +.IP "24." 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 +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 +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 @@ -696,52 +791,83 @@ 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 "22." 4 +This is a \f[B]non\-portable extension\f[R]. +.IP "25." 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]. +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. +the pseudo\-random number generator. .PP -\f[B]Note\f[R]: The values returned by the pseudo-random number +\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. +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 +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. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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 +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 +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 @@ -751,17 +877,16 @@ 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]. +\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 +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] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -770,7 +895,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -815,7 +940,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -833,7 +958,7 @@ Associativity: Left 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] +\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 @@ -871,18 +996,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -892,7 +1017,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -900,7 +1029,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -914,9 +1043,9 @@ more). .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -927,7 +1056,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -945,18 +1074,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -964,7 +1093,7 @@ 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] +\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]. @@ -976,9 +1105,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]>>\f[R] @@ -988,12 +1117,12 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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). @@ -1006,7 +1135,7 @@ 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]. +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] @@ -1020,41 +1149,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -1080,9 +1207,11 @@ An empty statement .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] +\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] +\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 @@ -1093,10 +1222,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -1113,7 +1242,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -1121,7 +1267,7 @@ 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 +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. @@ -1134,13 +1280,12 @@ Scientific notation is activated by assigning \f[B]0\f[R] to 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 +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]. +\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 @@ -1157,9 +1302,8 @@ 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]. +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 @@ -1186,14 +1330,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -1203,20 +1345,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1225,28 +1364,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1257,10 +1391,10 @@ 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 +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 +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] @@ -1274,18 +1408,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1299,17 +1430,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1317,20 +1445,17 @@ 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]. +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 +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 +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1381,13 +1506,12 @@ 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] +\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). +standard (see the \f[B]STANDARDS\f[R] section). .PP -The extended library is a \f[B]non-portable extension\f[R]. +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] @@ -1404,17 +1528,25 @@ Functions\f[R] subsection below). .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). +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). +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]max(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is greater than \f[B]b\f[R]; +otherwise, returns \f[B]b\f[R]. +.TP +\f[B]min(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is less than \f[B]b\f[R]; otherwise, +returns \f[B]b\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]. @@ -1425,6 +1557,10 @@ 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]fib(n)\f[R] +Returns the Fibonacci number of the truncated absolute value of +\f[B]n\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 @@ -1496,11 +1632,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1534,7 +1670,7 @@ Functions\f[R] subsection below). 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 +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]. @@ -1562,11 +1698,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1595,7 +1731,7 @@ 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 +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 @@ -1604,14 +1740,22 @@ 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]. +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. +is returned, and \f[B]seed\f[R] is not changed. +.TP +\f[B]i2rand(a, b)\f[R] +Takes the truncated value of \f[B]a\f[R] and \f[B]b\f[R] and uses them +as inclusive bounds to enerate a pseudo\-random integer. +If the difference of the truncated values of \f[B]a\f[R] and \f[B]b\f[R] +is \f[B]0\f[R], then the truncated value is returned, and \f[B]seed\f[R] +is \f[I]not\f[R] changed. +Otherwise, this function will change the value of \f[B]seed\f[R]. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability @@ -1653,8 +1797,8 @@ If you want to use signed two\[cq]s complement arguments, use .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. +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 @@ -1664,7 +1808,7 @@ If you want to use signed two\[cq]s complement arguments, use \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. +bit\-shifted right by \f[B]b\f[R] places. .RS .PP If you want to use signed two\[cq]s complement arguments, use @@ -1683,7 +1827,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]8\f[R] binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1692,7 +1836,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]16\f[R] binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1701,7 +1845,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]32\f[R] binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1710,7 +1854,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]64\f[R] binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1728,7 +1872,7 @@ If you want to a use signed two\[cq]s complement argument, use .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 +though it has the same number of 8\-bit bytes as the truncated absolute value of \f[B]n\f[R]. .RS .PP @@ -1738,7 +1882,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 8 binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1747,7 +1891,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 16 binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1756,7 +1900,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 32 binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1765,7 +1909,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 64 binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1783,11 +1927,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1818,7 +1962,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]4\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 @@ -1829,7 +1973,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]8\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 @@ -1841,9 +1985,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1852,11 +1996,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1910,9 +2054,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1966,7 +2110,7 @@ If you want to a use signed two\[cq]s complement argument, use .RE .TP \f[B]bunrev(t)\f[R] -Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit +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. @@ -1977,29 +2121,29 @@ 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. +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. +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 +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 @@ -2007,9 +2151,9 @@ 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 +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 @@ -2021,22 +2165,22 @@ 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 +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. +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 +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. +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 +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] @@ -2080,7 +2224,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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 +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 @@ -2108,7 +2252,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2136,7 +2280,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2164,7 +2308,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2192,7 +2336,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2220,7 +2364,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2267,19 +2411,18 @@ subsection of the \f[B]FUNCTIONS\f[R] section). \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. +\- 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -2330,8 +2473,7 @@ The transcendental functions in the extended math library are: .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 +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 @@ -2351,7 +2493,6 @@ 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. @@ -2374,7 +2515,6 @@ 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] @@ -2404,29 +2544,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]BC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -2434,28 +2574,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -2476,14 +2616,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -2495,7 +2635,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -2504,7 +2644,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -2514,13 +2654,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -2529,11 +2669,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -2542,18 +2682,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -2567,10 +2735,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -2592,7 +2760,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -2615,7 +2783,7 @@ 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. +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) @@ -2626,19 +2794,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -2647,7 +2814,6 @@ 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 @@ -2655,53 +2821,49 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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 +.SS Command\-Line History +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], +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. +\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. +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. +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] @@ -2710,7 +2872,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -2736,12 +2898,11 @@ 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. +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 +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 @@ -2754,20 +2915,23 @@ 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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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]. @@ -2775,10 +2939,13 @@ the value of \f[B]LC_NUMERIC\f[R]. This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/A.1.md b/contrib/bc/manuals/bc/A.1.md index e773d967284..e89305b1af4 100644 --- a/contrib/bc/manuals/bc/A.1.md +++ b/contrib/bc/manuals/bc/A.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,12 +34,12 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # 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 +POSIX. (See the **STANDARDS** section.) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. @@ -63,6 +63,86 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. @@ -133,7 +213,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -157,6 +246,15 @@ The following are the options that bc(1) accepts. To learn what is in the libraries, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -170,6 +268,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -223,29 +334,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* + +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. -: 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. + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -261,50 +372,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -350,9 +429,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -479,46 +558,54 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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 +22. **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**. -21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the +23. **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 @@ -529,7 +616,7 @@ The following are valid operands in bc(1): 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**. -22. **maxrand()**: The max integer returned by **rand()**. This is a +24. **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 @@ -548,14 +635,40 @@ use a non-seeded pseudo-random number generator. 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -698,6 +811,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\$** @@ -805,9 +921,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -871,6 +987,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -942,7 +1071,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -1054,7 +1183,8 @@ equivalents are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -1102,7 +1232,7 @@ The [standard][1] defines the following functions for the math 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]. +defined by the standard (see the **STANDARDS** section). The extended library is a **non-portable extension**. @@ -1119,17 +1249,27 @@ The extended library is a **non-portable extension**. **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round half away from **0**][3]. + round half away from **0** + (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round away from **0**][6]. + round away from **0** + (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). **f(x)** : Returns the factorial of the truncated absolute value of **x**. +**max(a, b)** + +: Returns **a** if **a** is greater than **b**; otherwise, returns **b**. + +**min(a, b)** + +: Returns **a** if **a** is less than **b**; otherwise, returns **b**. + **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the @@ -1140,6 +1280,10 @@ The extended library is a **non-portable extension**. : 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**. +**fib(n)** + +: Returns the Fibonacci number of the truncated absolute value of **n**. + **l2(x)** : Returns the logarithm base **2** of **x**. @@ -1302,7 +1446,15 @@ The extended library is a **non-portable extension**. 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. + **seed**; otherwise, **0** is returned, and **seed** is not changed. + +**i2rand(a, b)** + +: Takes the truncated value of **a** and **b** and uses them as inclusive + bounds to enerate a pseudo-random integer. If the difference of the + truncated values of **a** and **b** is **0**, then the truncated value is + returned, and **seed** is *not* changed. Otherwise, this function will + change the value of **seed**. **srand(x)** @@ -1364,7 +1516,7 @@ The extended library is a **non-portable extension**. **bnot8(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **8** binary digits (1 unsigned byte). + **8** binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1372,7 +1524,7 @@ The extended library is a **non-portable extension**. **bnot16(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **16** binary digits (2 unsigned bytes). + **16** binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1380,7 +1532,7 @@ The extended library is a **non-portable extension**. **bnot32(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **32** binary digits (4 unsigned bytes). + **32** binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1388,7 +1540,7 @@ The extended library is a **non-portable extension**. **bnot64(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **64** binary digits (8 unsigned bytes). + **64** binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1412,7 +1564,7 @@ The extended library is a **non-portable extension**. **brev8(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 8 binary digits (1 unsigned byte). + has 8 binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1420,7 +1572,7 @@ The extended library is a **non-portable extension**. **brev16(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 16 binary digits (2 unsigned bytes). + has 16 binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1428,7 +1580,7 @@ The extended library is a **non-portable extension**. **brev32(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 32 binary digits (4 unsigned bytes). + has 32 binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1436,7 +1588,7 @@ The extended library is a **non-portable extension**. **brev64(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 64 binary digits (8 unsigned bytes). + has 64 binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1483,7 +1635,7 @@ The extended library is a **non-portable extension**. **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 + though it has **32** binary digits (**4** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **32**. @@ -1493,7 +1645,7 @@ The extended library is a **non-portable extension**. **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 + though it has **64** binary digits (**8** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **64**. @@ -1888,10 +2040,11 @@ The extended library is a **non-portable extension**. ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -2034,7 +2187,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -2129,6 +2283,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -2204,10 +2384,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -2233,8 +2413,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -2320,9 +2500,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -2333,15 +2518,11 @@ This bc(1) supports error messages for different locales, and thus, it supports # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/E.1 b/contrib/bc/manuals/bc/E.1 index bb563f5c96f..e2f1b034e69 100644 --- a/contrib/bc/manuals/bc/E.1 +++ b/contrib/bc/manuals/bc/E.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,53 +25,139 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -84,19 +170,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -104,8 +187,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -119,12 +201,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -137,34 +217,45 @@ 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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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. @@ -173,11 +264,23 @@ any expressions or files specified on the command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -185,14 +288,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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). +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 @@ -200,16 +320,16 @@ 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. +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]. +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] +\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 @@ -256,108 +376,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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). +\f[B]plznl(x)\f[R], \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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -371,8 +447,7 @@ 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]. +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]. @@ -380,7 +455,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -388,13 +463,12 @@ 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. +\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 @@ -402,12 +476,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -415,32 +487,32 @@ 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 +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]. +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]. +\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 +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. +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 +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. @@ -453,7 +525,7 @@ exceptions. \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. +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 @@ -478,20 +550,18 @@ 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]. +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]. +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] @@ -506,7 +576,7 @@ Array Elements: \f[B]I[E]\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]. +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. @@ -520,7 +590,6 @@ Named expressions are required as the operand of 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). @@ -530,108 +599,152 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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]. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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 +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. .PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. +.SS 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. .TP -\f[B]++\f[R] \f[B]--\f[R] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -640,7 +753,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -667,7 +780,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -676,7 +789,7 @@ Associativity: Left 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] +\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 @@ -714,18 +827,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -735,7 +848,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -746,7 +863,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -764,18 +881,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -783,12 +900,12 @@ 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] +\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] +\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). @@ -812,41 +929,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -872,9 +987,11 @@ An empty statement .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] +\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] +\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 @@ -885,10 +1002,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -905,7 +1022,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -913,12 +1047,11 @@ 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 +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 @@ -935,9 +1068,8 @@ 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]. +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 @@ -964,14 +1096,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -981,20 +1111,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1003,28 +1130,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1035,10 +1157,10 @@ 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 +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 +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] @@ -1052,18 +1174,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1077,17 +1196,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1095,16 +1211,13 @@ 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]. +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. +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1155,12 +1268,11 @@ 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -1183,8 +1295,7 @@ The transcendental functions in the standard math library are: .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 +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 @@ -1204,7 +1315,6 @@ 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. @@ -1227,7 +1337,6 @@ 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] @@ -1257,24 +1366,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1282,28 +1391,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -1324,14 +1433,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1343,7 +1452,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -1352,7 +1461,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -1362,13 +1471,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -1377,11 +1486,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -1390,18 +1499,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1417,7 +1554,7 @@ 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. +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 @@ -1438,7 +1575,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -1461,7 +1598,7 @@ 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. +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) @@ -1472,19 +1609,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -1493,7 +1629,6 @@ 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 @@ -1501,53 +1636,49 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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 +.SS Command\-Line History +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], +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. +\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. +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. +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] @@ -1556,7 +1687,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1582,12 +1713,11 @@ 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. +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 +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 @@ -1600,20 +1730,23 @@ 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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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]. @@ -1621,10 +1754,13 @@ the value of \f[B]LC_NUMERIC\f[R]. This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/E.1.md b/contrib/bc/manuals/bc/E.1.md index 63367e436cc..0082caea840 100644 --- a/contrib/bc/manuals/bc/E.1.md +++ b/contrib/bc/manuals/bc/E.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,20 +34,21 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-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 +POSIX. (See the **STANDARDS** section.) 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). +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 @@ -62,6 +63,77 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, and **scale** into stacks. @@ -117,7 +189,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -141,6 +222,15 @@ The following are the options that bc(1) accepts. To learn what is in the library, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -154,6 +244,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -203,29 +306,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* -: 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. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. + + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -241,50 +344,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -330,9 +401,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -433,40 +504,48 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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**. @@ -474,14 +553,40 @@ The following are valid operands in bc(1): 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. ## Operators @@ -583,6 +688,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\^** @@ -648,9 +756,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -714,6 +822,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -774,7 +895,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -883,7 +1004,8 @@ command-line flags are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -929,10 +1051,11 @@ The [standard][1] defines the following functions for the math library: ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -1054,7 +1177,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -1149,6 +1273,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -1222,10 +1372,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -1251,8 +1401,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -1338,9 +1488,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -1351,15 +1506,11 @@ This bc(1) supports error messages for different locales, and thus, it supports # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EH.1 b/contrib/bc/manuals/bc/EH.1 index 0bdfaa9fe14..c132a0b76a4 100644 --- a/contrib/bc/manuals/bc/EH.1 +++ b/contrib/bc/manuals/bc/EH.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,53 +25,139 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -84,19 +170,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -104,8 +187,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -119,12 +201,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -137,34 +217,45 @@ 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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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. @@ -173,11 +264,23 @@ any expressions or files specified on the command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -185,14 +288,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. +.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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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] +\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). +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 @@ -200,16 +320,16 @@ 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. +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]. +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] +\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 @@ -256,108 +376,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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 +\f[B]plznl(x)\f[R], \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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -371,8 +447,7 @@ 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]. +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]. @@ -380,7 +455,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -388,13 +463,12 @@ 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. +\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 @@ -402,12 +476,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -415,32 +487,32 @@ 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 +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]. +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]. +\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 +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. +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 +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. @@ -453,7 +525,7 @@ exceptions. \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. +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 @@ -478,20 +550,18 @@ 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]. +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]. +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] @@ -506,7 +576,7 @@ Array Elements: \f[B]I[E]\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]. +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. @@ -520,7 +590,6 @@ Named expressions are required as the operand of 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). @@ -530,108 +599,152 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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]. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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 +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. .PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. +.SS 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. .TP -\f[B]++\f[R] \f[B]--\f[R] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -640,7 +753,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -667,7 +780,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -676,7 +789,7 @@ Associativity: Left 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] +\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 @@ -714,18 +827,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -735,7 +848,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -746,7 +863,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -764,18 +881,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -783,12 +900,12 @@ 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] +\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] +\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). @@ -812,41 +929,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -872,9 +987,11 @@ An empty statement .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] +\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] +\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 @@ -885,10 +1002,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -905,7 +1022,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -913,12 +1047,11 @@ 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 +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 @@ -935,9 +1068,8 @@ 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]. +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 @@ -964,14 +1096,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -981,20 +1111,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1003,28 +1130,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1035,10 +1157,10 @@ 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 +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 +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] @@ -1052,18 +1174,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1077,17 +1196,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1095,16 +1211,13 @@ 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]. +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. +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1155,12 +1268,11 @@ 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -1183,8 +1295,7 @@ The transcendental functions in the standard math library are: .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 +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 @@ -1204,7 +1315,6 @@ 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. @@ -1227,7 +1337,6 @@ 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] @@ -1257,24 +1366,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1282,28 +1391,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -1324,14 +1433,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1343,7 +1452,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -1352,7 +1461,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -1362,13 +1471,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -1377,11 +1486,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -1390,18 +1499,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1417,7 +1554,7 @@ 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. +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 @@ -1438,7 +1575,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -1461,7 +1598,7 @@ 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. +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) @@ -1472,19 +1609,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -1493,7 +1629,6 @@ 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 @@ -1501,45 +1636,42 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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], +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. +\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. +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. +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] @@ -1548,7 +1680,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1571,20 +1703,23 @@ the user to continue. \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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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]. @@ -1592,10 +1727,13 @@ the value of \f[B]LC_NUMERIC\f[R]. This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/EH.1.md b/contrib/bc/manuals/bc/EH.1.md index 044330b7fe0..7e682058234 100644 --- a/contrib/bc/manuals/bc/EH.1.md +++ b/contrib/bc/manuals/bc/EH.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,20 +34,21 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-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 +POSIX. (See the **STANDARDS** section.) 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). +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 @@ -62,6 +63,77 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, and **scale** into stacks. @@ -117,7 +189,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -141,6 +222,15 @@ The following are the options that bc(1) accepts. To learn what is in the library, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -154,6 +244,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -203,29 +306,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* -: 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. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. + + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -241,50 +344,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -330,9 +401,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -433,40 +504,48 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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**. @@ -474,14 +553,40 @@ The following are valid operands in bc(1): 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. ## Operators @@ -583,6 +688,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\^** @@ -648,9 +756,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -714,6 +822,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -774,7 +895,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -883,7 +1004,8 @@ command-line flags are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -929,10 +1051,11 @@ The [standard][1] defines the following functions for the math library: ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -1054,7 +1177,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -1149,6 +1273,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -1222,10 +1372,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -1251,8 +1401,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -1312,9 +1462,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -1325,15 +1480,11 @@ This bc(1) supports error messages for different locales, and thus, it supports # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EHN.1 b/contrib/bc/manuals/bc/EHN.1 index f0519898ad7..e3395b1cc20 100644 --- a/contrib/bc/manuals/bc/EHN.1 +++ b/contrib/bc/manuals/bc/EHN.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,53 +25,139 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -84,19 +170,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -104,8 +187,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -119,12 +201,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -137,34 +217,45 @@ 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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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. @@ -173,11 +264,23 @@ any expressions or files specified on the command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -185,14 +288,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. +.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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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] +\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). +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 @@ -200,16 +320,16 @@ 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. +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]. +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] +\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 @@ -256,108 +376,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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. +\f[B]plznl(x)\f[R], \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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -371,8 +447,7 @@ 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]. +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]. @@ -380,7 +455,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -388,13 +463,12 @@ 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. +\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 @@ -402,12 +476,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -415,32 +487,32 @@ 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 +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]. +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]. +\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 +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. +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 +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. @@ -453,7 +525,7 @@ exceptions. \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. +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 @@ -478,20 +550,18 @@ 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]. +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]. +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] @@ -506,7 +576,7 @@ Array Elements: \f[B]I[E]\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]. +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. @@ -520,7 +590,6 @@ Named expressions are required as the operand of 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). @@ -530,108 +599,152 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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]. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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 +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. .PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. +.SS 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. .TP -\f[B]++\f[R] \f[B]--\f[R] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -640,7 +753,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -667,7 +780,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -676,7 +789,7 @@ Associativity: Left 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] +\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 @@ -714,18 +827,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -735,7 +848,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -746,7 +863,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -764,18 +881,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -783,12 +900,12 @@ 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] +\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] +\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). @@ -812,41 +929,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -872,9 +987,11 @@ An empty statement .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] +\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] +\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 @@ -885,10 +1002,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -905,7 +1022,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -913,12 +1047,11 @@ 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 +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 @@ -935,9 +1068,8 @@ 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]. +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 @@ -964,14 +1096,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -981,20 +1111,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1003,28 +1130,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1035,10 +1157,10 @@ 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 +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 +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] @@ -1052,18 +1174,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1077,17 +1196,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1095,16 +1211,13 @@ 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]. +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. +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1155,12 +1268,11 @@ 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -1183,8 +1295,7 @@ The transcendental functions in the standard math library are: .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 +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 @@ -1204,7 +1315,6 @@ 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. @@ -1227,7 +1337,6 @@ 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] @@ -1257,24 +1366,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1282,28 +1391,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -1324,14 +1433,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1343,7 +1452,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -1352,7 +1461,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -1362,13 +1471,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -1377,11 +1486,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -1390,18 +1499,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS .PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1417,7 +1554,7 @@ 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. +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 @@ -1438,7 +1575,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -1461,7 +1598,7 @@ 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. +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) @@ -1472,19 +1609,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -1493,7 +1629,6 @@ 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 @@ -1501,45 +1636,42 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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], +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. +\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. +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. +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] @@ -1548,7 +1680,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1571,24 +1703,31 @@ the user to continue. \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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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 +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/EHN.1.md b/contrib/bc/manuals/bc/EHN.1.md index 25543500eea..9578d2ab772 100644 --- a/contrib/bc/manuals/bc/EHN.1.md +++ b/contrib/bc/manuals/bc/EHN.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,20 +34,21 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-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 +POSIX. (See the **STANDARDS** section.) 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). +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 @@ -62,6 +63,77 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, and **scale** into stacks. @@ -117,7 +189,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -141,6 +222,15 @@ The following are the options that bc(1) accepts. To learn what is in the library, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -154,6 +244,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -203,29 +306,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* -: 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. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. + + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -241,50 +344,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -330,9 +401,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -433,40 +504,48 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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**. @@ -474,14 +553,40 @@ The following are valid operands in bc(1): 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. ## Operators @@ -583,6 +688,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\^** @@ -648,9 +756,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -714,6 +822,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -774,7 +895,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -883,7 +1004,8 @@ command-line flags are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -929,10 +1051,11 @@ The [standard][1] defines the following functions for the math library: ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -1054,7 +1177,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -1149,6 +1273,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -1222,10 +1372,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -1251,8 +1401,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -1307,9 +1457,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -1317,15 +1472,11 @@ use a period (**.**) as a radix point, regardless of the value of # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EN.1 b/contrib/bc/manuals/bc/EN.1 index 192dccfea2f..c1ccbec567e 100644 --- a/contrib/bc/manuals/bc/EN.1 +++ b/contrib/bc/manuals/bc/EN.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,53 +25,139 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -84,19 +170,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -104,8 +187,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -119,12 +201,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -137,34 +217,45 @@ 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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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. @@ -173,11 +264,23 @@ any expressions or files specified on the command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -185,14 +288,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. +.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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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] +\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). +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 @@ -200,16 +320,16 @@ 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. +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]. +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] +\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 @@ -256,108 +376,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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 +\f[B]plznl(x)\f[R], \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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -371,8 +447,7 @@ 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]. +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]. @@ -380,7 +455,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -388,13 +463,12 @@ 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. +\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 @@ -402,12 +476,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -415,32 +487,32 @@ 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 +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]. +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]. +\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 +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. +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 +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. @@ -453,7 +525,7 @@ exceptions. \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. +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 @@ -478,20 +550,18 @@ 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]. +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]. +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] @@ -506,7 +576,7 @@ Array Elements: \f[B]I[E]\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]. +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. @@ -520,7 +590,6 @@ Named expressions are required as the operand of 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). @@ -530,108 +599,152 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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]. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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 +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. .PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. +.SS 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. .TP -\f[B]++\f[R] \f[B]--\f[R] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -640,7 +753,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -667,7 +780,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -676,7 +789,7 @@ Associativity: Left 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] +\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 @@ -714,18 +827,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -735,7 +848,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -746,7 +863,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -764,18 +881,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -783,12 +900,12 @@ 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] +\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] +\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). @@ -812,41 +929,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -872,9 +987,11 @@ An empty statement .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] +\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] +\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 @@ -885,10 +1002,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -905,7 +1022,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -913,12 +1047,11 @@ 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 +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 @@ -935,9 +1068,8 @@ 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]. +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 @@ -964,14 +1096,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -981,20 +1111,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1003,28 +1130,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1035,10 +1157,10 @@ 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 +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 +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] @@ -1052,18 +1174,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1077,17 +1196,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1095,16 +1211,13 @@ 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]. +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. +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1155,12 +1268,11 @@ 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -1183,8 +1295,7 @@ The transcendental functions in the standard math library are: .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 +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 @@ -1204,7 +1315,6 @@ 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. @@ -1227,7 +1337,6 @@ 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] @@ -1257,24 +1366,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1282,28 +1391,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -1324,14 +1433,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1343,7 +1452,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -1352,7 +1461,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -1362,13 +1471,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -1377,11 +1486,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -1390,18 +1499,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1417,7 +1554,7 @@ 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. +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 @@ -1438,7 +1575,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -1461,7 +1598,7 @@ 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. +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) @@ -1472,19 +1609,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -1493,7 +1629,6 @@ 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 @@ -1501,53 +1636,49 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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 +.SS Command\-Line History +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], +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. +\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. +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. +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] @@ -1556,7 +1687,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1582,12 +1713,11 @@ 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. +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 +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 @@ -1600,24 +1730,31 @@ 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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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 +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/EN.1.md b/contrib/bc/manuals/bc/EN.1.md index e77d64cd7a5..f6ad0093090 100644 --- a/contrib/bc/manuals/bc/EN.1.md +++ b/contrib/bc/manuals/bc/EN.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,20 +34,21 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-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 +POSIX. (See the **STANDARDS** section.) 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). +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 @@ -62,6 +63,77 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, and **scale** into stacks. @@ -117,7 +189,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -141,6 +222,15 @@ The following are the options that bc(1) accepts. To learn what is in the library, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -154,6 +244,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -203,29 +306,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* -: 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. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. + + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -241,50 +344,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -330,9 +401,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -433,40 +504,48 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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**. @@ -474,14 +553,40 @@ The following are valid operands in bc(1): 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. ## Operators @@ -583,6 +688,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\^** @@ -648,9 +756,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -714,6 +822,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -774,7 +895,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -883,7 +1004,8 @@ command-line flags are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -929,10 +1051,11 @@ The [standard][1] defines the following functions for the math library: ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -1054,7 +1177,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -1149,6 +1273,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -1222,10 +1372,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -1251,8 +1401,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -1333,9 +1483,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -1343,15 +1498,11 @@ use a period (**.**) as a radix point, regardless of the value of # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/H.1 b/contrib/bc/manuals/bc/H.1 index 5f290f12ae3..9dc46ee50de 100644 --- a/contrib/bc/manuals/bc/H.1 +++ b/contrib/bc/manuals/bc/H.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,34 +25,38 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. @@ -61,19 +65,114 @@ implementations. 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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -86,19 +185,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -106,8 +202,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -125,12 +220,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -140,53 +233,63 @@ 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 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 +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] +.EX seed = seed -\f[R] -.fi +.EE .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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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 @@ -196,11 +299,23 @@ command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -208,14 +323,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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). +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 @@ -223,16 +355,16 @@ 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. +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]. +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] +\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 @@ -287,108 +419,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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. +\f[B]plznl(x)\f[R], \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]. +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]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -402,8 +490,7 @@ 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]. +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]. @@ -411,7 +498,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -419,13 +506,12 @@ 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. +\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 @@ -433,12 +519,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -446,32 +530,32 @@ 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 +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]. +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]. +\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 +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. +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 +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 @@ -479,8 +563,8 @@ 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]. +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] @@ -490,7 +574,7 @@ exceptions. \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. +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 @@ -515,20 +599,18 @@ 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]. +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]. +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] @@ -545,26 +627,26 @@ Array Elements: \f[B]I[E]\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]. +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 +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 +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. +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. +\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 @@ -585,7 +667,6 @@ Named expressions are required as the operand of 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). @@ -595,99 +676,113 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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] +This is a \f[B]non\-portable extension\f[R]. +.IP "23." 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 "21." 4 -\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] +This is a \f[B]non\-portable extension\f[R]. +.IP "24." 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 +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 +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 @@ -696,52 +791,83 @@ 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 "22." 4 +This is a \f[B]non\-portable extension\f[R]. +.IP "25." 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]. +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. +the pseudo\-random number generator. .PP -\f[B]Note\f[R]: The values returned by the pseudo-random number +\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. +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 +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. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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 +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 +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 @@ -751,17 +877,16 @@ 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]. +\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 +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] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -770,7 +895,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -815,7 +940,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -833,7 +958,7 @@ Associativity: Left 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] +\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 @@ -871,18 +996,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -892,7 +1017,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -900,7 +1029,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -914,9 +1043,9 @@ more). .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -927,7 +1056,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -945,18 +1074,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -964,7 +1093,7 @@ 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] +\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]. @@ -976,9 +1105,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]>>\f[R] @@ -988,12 +1117,12 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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). @@ -1006,7 +1135,7 @@ 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]. +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] @@ -1020,41 +1149,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -1080,9 +1207,11 @@ An empty statement .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] +\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] +\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 @@ -1093,10 +1222,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -1113,7 +1242,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -1121,7 +1267,7 @@ 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 +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. @@ -1134,13 +1280,12 @@ Scientific notation is activated by assigning \f[B]0\f[R] to 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 +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]. +\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 @@ -1157,9 +1302,8 @@ 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]. +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 @@ -1186,14 +1330,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -1203,20 +1345,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1225,28 +1364,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1257,10 +1391,10 @@ 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 +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 +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] @@ -1274,18 +1408,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1299,17 +1430,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1317,20 +1445,17 @@ 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]. +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 +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 +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1381,13 +1506,12 @@ 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] +\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). +standard (see the \f[B]STANDARDS\f[R] section). .PP -The extended library is a \f[B]non-portable extension\f[R]. +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] @@ -1404,17 +1528,25 @@ Functions\f[R] subsection below). .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). +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). +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]max(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is greater than \f[B]b\f[R]; +otherwise, returns \f[B]b\f[R]. +.TP +\f[B]min(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is less than \f[B]b\f[R]; otherwise, +returns \f[B]b\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]. @@ -1425,6 +1557,10 @@ 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]fib(n)\f[R] +Returns the Fibonacci number of the truncated absolute value of +\f[B]n\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 @@ -1496,11 +1632,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1534,7 +1670,7 @@ Functions\f[R] subsection below). 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 +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]. @@ -1562,11 +1698,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1595,7 +1731,7 @@ 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 +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 @@ -1604,14 +1740,22 @@ 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]. +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. +is returned, and \f[B]seed\f[R] is not changed. +.TP +\f[B]i2rand(a, b)\f[R] +Takes the truncated value of \f[B]a\f[R] and \f[B]b\f[R] and uses them +as inclusive bounds to enerate a pseudo\-random integer. +If the difference of the truncated values of \f[B]a\f[R] and \f[B]b\f[R] +is \f[B]0\f[R], then the truncated value is returned, and \f[B]seed\f[R] +is \f[I]not\f[R] changed. +Otherwise, this function will change the value of \f[B]seed\f[R]. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability @@ -1653,8 +1797,8 @@ If you want to use signed two\[cq]s complement arguments, use .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. +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 @@ -1664,7 +1808,7 @@ If you want to use signed two\[cq]s complement arguments, use \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. +bit\-shifted right by \f[B]b\f[R] places. .RS .PP If you want to use signed two\[cq]s complement arguments, use @@ -1683,7 +1827,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]8\f[R] binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1692,7 +1836,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]16\f[R] binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1701,7 +1845,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]32\f[R] binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1710,7 +1854,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]64\f[R] binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1728,7 +1872,7 @@ If you want to a use signed two\[cq]s complement argument, use .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 +though it has the same number of 8\-bit bytes as the truncated absolute value of \f[B]n\f[R]. .RS .PP @@ -1738,7 +1882,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 8 binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1747,7 +1891,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 16 binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1756,7 +1900,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 32 binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1765,7 +1909,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 64 binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1783,11 +1927,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1818,7 +1962,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]4\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 @@ -1829,7 +1973,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]8\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 @@ -1841,9 +1985,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1852,11 +1996,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1910,9 +2054,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1966,7 +2110,7 @@ If you want to a use signed two\[cq]s complement argument, use .RE .TP \f[B]bunrev(t)\f[R] -Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit +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. @@ -1977,29 +2121,29 @@ 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. +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. +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 +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 @@ -2007,9 +2151,9 @@ 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 +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 @@ -2021,22 +2165,22 @@ 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 +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. +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 +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. +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 +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] @@ -2080,7 +2224,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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 +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 @@ -2108,7 +2252,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2136,7 +2280,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2164,7 +2308,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2192,7 +2336,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2220,7 +2364,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2267,19 +2411,18 @@ subsection of the \f[B]FUNCTIONS\f[R] section). \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. +\- 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -2330,8 +2473,7 @@ The transcendental functions in the extended math library are: .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 +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 @@ -2351,7 +2493,6 @@ 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. @@ -2374,7 +2515,6 @@ 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] @@ -2404,29 +2544,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]BC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -2434,28 +2574,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -2476,14 +2616,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -2495,7 +2635,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -2504,7 +2644,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -2514,13 +2654,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -2529,11 +2669,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -2542,18 +2682,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS .PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -2567,10 +2735,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -2592,7 +2760,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -2615,7 +2783,7 @@ 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. +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) @@ -2626,19 +2794,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -2647,7 +2814,6 @@ 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 @@ -2655,45 +2821,42 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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], +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. +\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. +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. +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] @@ -2702,7 +2865,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -2725,20 +2888,23 @@ the user to continue. \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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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]. @@ -2746,10 +2912,13 @@ the value of \f[B]LC_NUMERIC\f[R]. This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/H.1.md b/contrib/bc/manuals/bc/H.1.md index 99c88db9323..fbc0658d817 100644 --- a/contrib/bc/manuals/bc/H.1.md +++ b/contrib/bc/manuals/bc/H.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,12 +34,12 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # 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 +POSIX. (See the **STANDARDS** section.) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. @@ -63,6 +63,86 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. @@ -133,7 +213,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -157,6 +246,15 @@ The following are the options that bc(1) accepts. To learn what is in the libraries, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -170,6 +268,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -223,29 +334,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* + +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. -: 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. + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -261,50 +372,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -350,9 +429,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -479,46 +558,54 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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 +22. **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**. -21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the +23. **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 @@ -529,7 +616,7 @@ The following are valid operands in bc(1): 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**. -22. **maxrand()**: The max integer returned by **rand()**. This is a +24. **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 @@ -548,14 +635,40 @@ use a non-seeded pseudo-random number generator. 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -698,6 +811,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\$** @@ -805,9 +921,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -871,6 +987,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -942,7 +1071,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -1054,7 +1183,8 @@ equivalents are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -1102,7 +1232,7 @@ The [standard][1] defines the following functions for the math 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]. +defined by the standard (see the **STANDARDS** section). The extended library is a **non-portable extension**. @@ -1119,17 +1249,27 @@ The extended library is a **non-portable extension**. **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round half away from **0**][3]. + round half away from **0** + (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round away from **0**][6]. + round away from **0** + (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). **f(x)** : Returns the factorial of the truncated absolute value of **x**. +**max(a, b)** + +: Returns **a** if **a** is greater than **b**; otherwise, returns **b**. + +**min(a, b)** + +: Returns **a** if **a** is less than **b**; otherwise, returns **b**. + **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the @@ -1140,6 +1280,10 @@ The extended library is a **non-portable extension**. : 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**. +**fib(n)** + +: Returns the Fibonacci number of the truncated absolute value of **n**. + **l2(x)** : Returns the logarithm base **2** of **x**. @@ -1302,7 +1446,15 @@ The extended library is a **non-portable extension**. 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. + **seed**; otherwise, **0** is returned, and **seed** is not changed. + +**i2rand(a, b)** + +: Takes the truncated value of **a** and **b** and uses them as inclusive + bounds to enerate a pseudo-random integer. If the difference of the + truncated values of **a** and **b** is **0**, then the truncated value is + returned, and **seed** is *not* changed. Otherwise, this function will + change the value of **seed**. **srand(x)** @@ -1364,7 +1516,7 @@ The extended library is a **non-portable extension**. **bnot8(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **8** binary digits (1 unsigned byte). + **8** binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1372,7 +1524,7 @@ The extended library is a **non-portable extension**. **bnot16(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **16** binary digits (2 unsigned bytes). + **16** binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1380,7 +1532,7 @@ The extended library is a **non-portable extension**. **bnot32(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **32** binary digits (4 unsigned bytes). + **32** binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1388,7 +1540,7 @@ The extended library is a **non-portable extension**. **bnot64(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **64** binary digits (8 unsigned bytes). + **64** binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1412,7 +1564,7 @@ The extended library is a **non-portable extension**. **brev8(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 8 binary digits (1 unsigned byte). + has 8 binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1420,7 +1572,7 @@ The extended library is a **non-portable extension**. **brev16(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 16 binary digits (2 unsigned bytes). + has 16 binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1428,7 +1580,7 @@ The extended library is a **non-portable extension**. **brev32(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 32 binary digits (4 unsigned bytes). + has 32 binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1436,7 +1588,7 @@ The extended library is a **non-portable extension**. **brev64(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 64 binary digits (8 unsigned bytes). + has 64 binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1483,7 +1635,7 @@ The extended library is a **non-portable extension**. **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 + though it has **32** binary digits (**4** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **32**. @@ -1493,7 +1645,7 @@ The extended library is a **non-portable extension**. **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 + though it has **64** binary digits (**8** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **64**. @@ -1888,10 +2040,11 @@ The extended library is a **non-portable extension**. ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -2034,7 +2187,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -2129,6 +2283,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -2204,10 +2384,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -2233,8 +2413,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -2294,9 +2474,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -2307,15 +2492,11 @@ This bc(1) supports error messages for different locales, and thus, it supports # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/HN.1 b/contrib/bc/manuals/bc/HN.1 index 4773ff77efe..7b4577f2dbd 100644 --- a/contrib/bc/manuals/bc/HN.1 +++ b/contrib/bc/manuals/bc/HN.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,34 +25,38 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. @@ -61,19 +65,114 @@ implementations. 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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -86,19 +185,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -106,8 +202,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -125,12 +220,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -140,53 +233,63 @@ 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 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 +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] +.EX seed = seed -\f[R] -.fi +.EE .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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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 @@ -196,11 +299,23 @@ command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -208,14 +323,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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). +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 @@ -223,16 +355,16 @@ 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. +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]. +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] +\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 @@ -287,108 +419,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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. +\f[B]plznl(x)\f[R], \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]. +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]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -402,8 +490,7 @@ 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]. +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]. @@ -411,7 +498,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -419,13 +506,12 @@ 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. +\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 @@ -433,12 +519,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -446,32 +530,32 @@ 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 +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]. +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]. +\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 +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. +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 +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 @@ -479,8 +563,8 @@ 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]. +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] @@ -490,7 +574,7 @@ exceptions. \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. +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 @@ -515,20 +599,18 @@ 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]. +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]. +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] @@ -545,26 +627,26 @@ Array Elements: \f[B]I[E]\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]. +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 +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 +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. +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. +\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 @@ -585,7 +667,6 @@ Named expressions are required as the operand of 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). @@ -595,99 +676,113 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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] +This is a \f[B]non\-portable extension\f[R]. +.IP "23." 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 "21." 4 -\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] +This is a \f[B]non\-portable extension\f[R]. +.IP "24." 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 +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 +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 @@ -696,52 +791,83 @@ 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 "22." 4 +This is a \f[B]non\-portable extension\f[R]. +.IP "25." 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]. +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. +the pseudo\-random number generator. .PP -\f[B]Note\f[R]: The values returned by the pseudo-random number +\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. +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 +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. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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 +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 +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 @@ -751,17 +877,16 @@ 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]. +\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 +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] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -770,7 +895,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -815,7 +940,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -833,7 +958,7 @@ Associativity: Left 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] +\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 @@ -871,18 +996,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -892,7 +1017,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -900,7 +1029,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -914,9 +1043,9 @@ more). .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -927,7 +1056,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -945,18 +1074,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -964,7 +1093,7 @@ 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] +\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]. @@ -976,9 +1105,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]>>\f[R] @@ -988,12 +1117,12 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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). @@ -1006,7 +1135,7 @@ 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]. +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] @@ -1020,41 +1149,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -1080,9 +1207,11 @@ An empty statement .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] +\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] +\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 @@ -1093,10 +1222,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -1113,7 +1242,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -1121,7 +1267,7 @@ 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 +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. @@ -1134,13 +1280,12 @@ Scientific notation is activated by assigning \f[B]0\f[R] to 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 +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]. +\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 @@ -1157,9 +1302,8 @@ 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]. +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 @@ -1186,14 +1330,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -1203,20 +1345,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1225,28 +1364,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1257,10 +1391,10 @@ 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 +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 +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] @@ -1274,18 +1408,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1299,17 +1430,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1317,20 +1445,17 @@ 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]. +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 +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 +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1381,13 +1506,12 @@ 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] +\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). +standard (see the \f[B]STANDARDS\f[R] section). .PP -The extended library is a \f[B]non-portable extension\f[R]. +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] @@ -1404,17 +1528,25 @@ Functions\f[R] subsection below). .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). +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). +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]max(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is greater than \f[B]b\f[R]; +otherwise, returns \f[B]b\f[R]. +.TP +\f[B]min(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is less than \f[B]b\f[R]; otherwise, +returns \f[B]b\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]. @@ -1425,6 +1557,10 @@ 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]fib(n)\f[R] +Returns the Fibonacci number of the truncated absolute value of +\f[B]n\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 @@ -1496,11 +1632,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1534,7 +1670,7 @@ Functions\f[R] subsection below). 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 +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]. @@ -1562,11 +1698,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1595,7 +1731,7 @@ 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 +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 @@ -1604,14 +1740,22 @@ 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]. +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. +is returned, and \f[B]seed\f[R] is not changed. +.TP +\f[B]i2rand(a, b)\f[R] +Takes the truncated value of \f[B]a\f[R] and \f[B]b\f[R] and uses them +as inclusive bounds to enerate a pseudo\-random integer. +If the difference of the truncated values of \f[B]a\f[R] and \f[B]b\f[R] +is \f[B]0\f[R], then the truncated value is returned, and \f[B]seed\f[R] +is \f[I]not\f[R] changed. +Otherwise, this function will change the value of \f[B]seed\f[R]. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability @@ -1653,8 +1797,8 @@ If you want to use signed two\[cq]s complement arguments, use .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. +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 @@ -1664,7 +1808,7 @@ If you want to use signed two\[cq]s complement arguments, use \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. +bit\-shifted right by \f[B]b\f[R] places. .RS .PP If you want to use signed two\[cq]s complement arguments, use @@ -1683,7 +1827,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]8\f[R] binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1692,7 +1836,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]16\f[R] binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1701,7 +1845,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]32\f[R] binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1710,7 +1854,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]64\f[R] binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1728,7 +1872,7 @@ If you want to a use signed two\[cq]s complement argument, use .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 +though it has the same number of 8\-bit bytes as the truncated absolute value of \f[B]n\f[R]. .RS .PP @@ -1738,7 +1882,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 8 binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1747,7 +1891,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 16 binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1756,7 +1900,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 32 binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1765,7 +1909,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 64 binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1783,11 +1927,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1818,7 +1962,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]4\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 @@ -1829,7 +1973,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]8\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 @@ -1841,9 +1985,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1852,11 +1996,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1910,9 +2054,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1966,7 +2110,7 @@ If you want to a use signed two\[cq]s complement argument, use .RE .TP \f[B]bunrev(t)\f[R] -Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit +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. @@ -1977,29 +2121,29 @@ 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. +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. +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 +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 @@ -2007,9 +2151,9 @@ 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 +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 @@ -2021,22 +2165,22 @@ 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 +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. +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 +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. +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 +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] @@ -2080,7 +2224,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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 +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 @@ -2108,7 +2252,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2136,7 +2280,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2164,7 +2308,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2192,7 +2336,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2220,7 +2364,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2267,19 +2411,18 @@ subsection of the \f[B]FUNCTIONS\f[R] section). \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. +\- 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -2330,8 +2473,7 @@ The transcendental functions in the extended math library are: .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 +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 @@ -2351,7 +2493,6 @@ 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. @@ -2374,7 +2515,6 @@ 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] @@ -2404,29 +2544,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]BC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -2434,28 +2574,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -2476,14 +2616,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -2495,7 +2635,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -2504,7 +2644,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -2514,13 +2654,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -2529,11 +2669,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -2542,18 +2682,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -2567,10 +2735,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -2592,7 +2760,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -2615,7 +2783,7 @@ 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. +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) @@ -2626,19 +2794,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -2647,7 +2814,6 @@ 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 @@ -2655,45 +2821,42 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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], +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. +\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. +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. +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] @@ -2702,7 +2865,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -2725,24 +2888,31 @@ the user to continue. \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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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 +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/HN.1.md b/contrib/bc/manuals/bc/HN.1.md index d5b3324514a..015035c14da 100644 --- a/contrib/bc/manuals/bc/HN.1.md +++ b/contrib/bc/manuals/bc/HN.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,12 +34,12 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # 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 +POSIX. (See the **STANDARDS** section.) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. @@ -63,6 +63,86 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. @@ -133,7 +213,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -157,6 +246,15 @@ The following are the options that bc(1) accepts. To learn what is in the libraries, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -170,6 +268,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -223,29 +334,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* + +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. -: 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. + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -261,50 +372,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -350,9 +429,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -479,46 +558,54 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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 +22. **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**. -21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the +23. **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 @@ -529,7 +616,7 @@ The following are valid operands in bc(1): 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**. -22. **maxrand()**: The max integer returned by **rand()**. This is a +24. **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 @@ -548,14 +635,40 @@ use a non-seeded pseudo-random number generator. 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -698,6 +811,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\$** @@ -805,9 +921,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -871,6 +987,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -942,7 +1071,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -1054,7 +1183,8 @@ equivalents are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -1102,7 +1232,7 @@ The [standard][1] defines the following functions for the math 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]. +defined by the standard (see the **STANDARDS** section). The extended library is a **non-portable extension**. @@ -1119,17 +1249,27 @@ The extended library is a **non-portable extension**. **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round half away from **0**][3]. + round half away from **0** + (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round away from **0**][6]. + round away from **0** + (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). **f(x)** : Returns the factorial of the truncated absolute value of **x**. +**max(a, b)** + +: Returns **a** if **a** is greater than **b**; otherwise, returns **b**. + +**min(a, b)** + +: Returns **a** if **a** is less than **b**; otherwise, returns **b**. + **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the @@ -1140,6 +1280,10 @@ The extended library is a **non-portable extension**. : 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**. +**fib(n)** + +: Returns the Fibonacci number of the truncated absolute value of **n**. + **l2(x)** : Returns the logarithm base **2** of **x**. @@ -1302,7 +1446,15 @@ The extended library is a **non-portable extension**. 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. + **seed**; otherwise, **0** is returned, and **seed** is not changed. + +**i2rand(a, b)** + +: Takes the truncated value of **a** and **b** and uses them as inclusive + bounds to enerate a pseudo-random integer. If the difference of the + truncated values of **a** and **b** is **0**, then the truncated value is + returned, and **seed** is *not* changed. Otherwise, this function will + change the value of **seed**. **srand(x)** @@ -1364,7 +1516,7 @@ The extended library is a **non-portable extension**. **bnot8(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **8** binary digits (1 unsigned byte). + **8** binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1372,7 +1524,7 @@ The extended library is a **non-portable extension**. **bnot16(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **16** binary digits (2 unsigned bytes). + **16** binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1380,7 +1532,7 @@ The extended library is a **non-portable extension**. **bnot32(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **32** binary digits (4 unsigned bytes). + **32** binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1388,7 +1540,7 @@ The extended library is a **non-portable extension**. **bnot64(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **64** binary digits (8 unsigned bytes). + **64** binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1412,7 +1564,7 @@ The extended library is a **non-portable extension**. **brev8(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 8 binary digits (1 unsigned byte). + has 8 binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1420,7 +1572,7 @@ The extended library is a **non-portable extension**. **brev16(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 16 binary digits (2 unsigned bytes). + has 16 binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1428,7 +1580,7 @@ The extended library is a **non-portable extension**. **brev32(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 32 binary digits (4 unsigned bytes). + has 32 binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1436,7 +1588,7 @@ The extended library is a **non-portable extension**. **brev64(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 64 binary digits (8 unsigned bytes). + has 64 binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1483,7 +1635,7 @@ The extended library is a **non-portable extension**. **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 + though it has **32** binary digits (**4** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **32**. @@ -1493,7 +1645,7 @@ The extended library is a **non-portable extension**. **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 + though it has **64** binary digits (**8** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **64**. @@ -1888,10 +2040,11 @@ The extended library is a **non-portable extension**. ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -2034,7 +2187,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -2129,6 +2283,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -2204,10 +2384,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -2233,8 +2413,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -2289,9 +2469,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -2299,15 +2484,11 @@ use a period (**.**) as a radix point, regardless of the value of # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/N.1 b/contrib/bc/manuals/bc/N.1 index 56fca3d02b4..193e0d15f6f 100644 --- a/contrib/bc/manuals/bc/N.1 +++ b/contrib/bc/manuals/bc/N.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,34 +25,38 @@ .\" 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" +.TH "BC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH NAME -.PP -bc - arbitrary-precision decimal arithmetic language and calculator +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[B]bc\f[R] [\f[B]\-cCghilPqRsvVw\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\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).) +(See the \f[B]STANDARDS\f[R] section.) The language provides unlimited precision decimal arithmetic and is -somewhat C-like, but there are differences. +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 +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. @@ -61,19 +65,114 @@ implementations. 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. +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] +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]BC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 the \f[B]\-f\f[R] and \f[B]\-\-file\f[R] +options), 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 the \f[B]\-e\f[R] and +\f[B]\-\-expression\f[R] options), 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 +.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 @@ -86,19 +185,16 @@ 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] +.EX define void output(x, b) { obase=b x } -\f[R] -.fi +.EE .PP instead of like this: .IP -.nf -\f[C] +.EX define void output(x, b) { auto c c=obase @@ -106,8 +202,7 @@ define void output(x, b) { x obase=c } -\f[R] -.fi +.EE .PP This makes writing functions much easier. .PP @@ -125,12 +220,10 @@ 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 +.EX +alias d2o=\[dq]bc \-e ibase=A \-e obase=8\[dq] +alias h2b=\[dq]bc \-e ibase=G \-e obase=2\[dq] +.EE .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 @@ -140,53 +233,63 @@ 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 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 +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] +.EX seed = seed -\f[R] -.fi +.EE .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. +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]. +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. +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]--mathlib\f[R] +\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 @@ -196,11 +299,23 @@ command line. 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] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 bc(1). +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 @@ -208,14 +323,31 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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 +unless the \f[B]BC_BANNER\f[R] environment variable is set and contains +a non\-zero integer or if this bc(1) was built with the header displayed +by default. +If \f[I]any\f[R] of that is the case, then this option \f[I]does\f[R] +prevent bc(1) from printing the header. +.RS +.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). +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 @@ -223,16 +355,16 @@ 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. +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]. +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] +\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 @@ -287,108 +419,64 @@ multiple times. 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 redefine keywords mandated by the POSIX standard +(see the \f[B]STANDARDS\f[R] section). 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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .RS .PP -This is a \f[B]non-portable extension\f[R]. +If multiple instances of this option are given, the last is used. +.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. +\f[B]\-s\f[R], \f[B]\-\-standard\f[R] +Process exactly the language defined by the standard (see the +\f[B]STANDARDS\f[R] section) and error if any extensions are used. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 +\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]. +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]\-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. +\f[B]plznl(x)\f[R], \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]. +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]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there are a few caveats to this. .PP @@ -402,8 +490,7 @@ 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]. +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]. @@ -411,7 +498,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -419,13 +506,12 @@ 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. +\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 @@ -433,12 +519,10 @@ 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. +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX standard (see the \f[B]STANDARDS\f[R] +section), 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 @@ -446,32 +530,32 @@ 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 +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]. +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]. +\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 +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. +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 +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 @@ -479,8 +563,8 @@ 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]. +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] @@ -490,7 +574,7 @@ exceptions. \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. +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 @@ -515,20 +599,18 @@ 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]. +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]. +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] @@ -545,26 +627,26 @@ Array Elements: \f[B]I[E]\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]. +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 +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 +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. +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. +\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 @@ -585,7 +667,6 @@ Named expressions are required as the operand of 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). @@ -595,99 +676,113 @@ Array indices (\f[B]I[E]\f[R]). \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. +\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 +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]. +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]. +This is a \f[B]non\-portable extension\f[R]. .IP " 9." 4 +\f[B]is_number(E)\f[R]: \f[B]1\f[R] if the given argument is a number, +\f[B]0\f[R] if it is a string. +This is a \f[B]non\-portable extension\f[R]. +.IP "10." 4 +\f[B]is_string(E)\f[R]: \f[B]1\f[R] if the given argument is a string, +\f[B]0\f[R] if it is a number. +This is a \f[B]non\-portable extension\f[R]. +.IP "11." 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 +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 "12." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "13." 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 +that number as a one\-character string. +This is a \f[B]non\-portable extension\f[R]. +.IP "14." 4 +\f[B]asciify(I[])\f[R]: A string that is made up of the characters that +would result from running \f[B]asciify(E)\f[R] on each element of the +array identified by the argument. +This allows creating multi\-character strings and storing them. +This is a \f[B]non\-portable extension\f[R]. +.IP "15." 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[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 +.IP "16." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "17." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "18." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "19." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "20." 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 +This is a \f[B]non\-portable extension\f[R]. +.IP "21." 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. +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 +This is a \f[B]non\-portable extension\f[R]. +.IP "22." 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. +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] +This is a \f[B]non\-portable extension\f[R]. +.IP "23." 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 "21." 4 -\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] +This is a \f[B]non\-portable extension\f[R]. +.IP "24." 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 +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 +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 @@ -696,52 +791,83 @@ 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 "22." 4 +This is a \f[B]non\-portable extension\f[R]. +.IP "25." 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]. +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. +the pseudo\-random number generator. .PP -\f[B]Note\f[R]: The values returned by the pseudo-random number +\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. +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 +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. +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]. +Uppercase letters are equal to \f[B]9\f[R] plus their position in the +alphabet, starting from \f[B]1\f[R] (i.e., \f[B]A\f[R] equals +\f[B]10\f[R], or \f[B]9+1\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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]BC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +This behavior is mandated by the standard (see the STANDARDS section) +and is meant to provide an easy way to set the current \f[B]ibase\f[R] +(with the \f[B]i\f[R] command) regardless of the current value of +\f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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 +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 +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 @@ -751,17 +877,16 @@ 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]. +\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 +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] +\f[B]++\f[R] \f[B]\-\-\f[R] Type: Prefix and Postfix .RS .PP @@ -770,7 +895,7 @@ Associativity: None Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP -\f[B]-\f[R] \f[B]!\f[R] +\f[B]\-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP @@ -815,7 +940,7 @@ Associativity: Left 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] +\f[B]+\f[R] \f[B]\-\f[R] Type: Binary .RS .PP @@ -833,7 +958,7 @@ Associativity: Left 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] +\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 @@ -871,18 +996,18 @@ Description: \f[B]boolean or\f[R] .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]--\f[R] +\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. +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] +\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. @@ -892,7 +1017,11 @@ 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]. +\f[B]Warning\f[R]: This operator has a \f[B]different precedence\f[R] +than the equivalent operator in GNU bc(1) and other bc(1) +implementations! +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -900,7 +1029,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -914,9 +1043,9 @@ more). .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -927,7 +1056,7 @@ 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. +is negative, the first value must be non\-zero. .RE .TP \f[B]*\f[R] @@ -945,18 +1074,18 @@ 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. +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]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. +The second expression must be non\-zero. .RE .TP \f[B]+\f[R] @@ -964,7 +1093,7 @@ 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] +\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]. @@ -976,9 +1105,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]>>\f[R] @@ -988,12 +1117,12 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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). @@ -1006,7 +1135,7 @@ 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]. +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] @@ -1020,41 +1149,39 @@ 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) +Also, unlike the standard (see the \f[B]STANDARDS\f[R] section) requires, these operators can appear anywhere any other expressions can be used. -This allowance is a \f[B]non-portable extension\f[R]. +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. +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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. +This is \f[I]not\f[R] a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] +\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 @@ -1080,9 +1207,11 @@ An empty statement .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] +\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] +\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 @@ -1093,10 +1222,10 @@ The \f[B]E\f[R] argument(s) may also be arrays of the form \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 +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 +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]. @@ -1113,7 +1242,24 @@ This is only allowed in loops. 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). +branch that will not be executed (it is a compile\-time command). +.PP +\f[B]Warning\f[R]: The behavior of this bc(1) on \f[B]quit\f[R] is +slightly different from other bc(1) implementations. +Other bc(1) implementations will exit as soon as they finish parsing the +line that a \f[B]quit\f[R] command is on. +This bc(1) will execute any completed and executable statements that +occur before the \f[B]quit\f[R] statement before exiting. +.PP +In other words, for the bc(1) code below: +.IP +.EX +for (i = 0; i < 3; ++i) i; quit +.EE +.PP +Other bc(1) implementations will print nothing, and this bc(1) will +print \f[B]0\f[R], \f[B]1\f[R], and \f[B]2\f[R] on successive lines +before exiting. .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 @@ -1121,7 +1267,7 @@ 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 +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. @@ -1134,13 +1280,12 @@ Scientific notation is activated by assigning \f[B]0\f[R] to 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 +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]. +\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 @@ -1157,9 +1302,8 @@ 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]. +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 @@ -1186,14 +1330,12 @@ below: \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. +character to be printed as\-is. .PP -Any non-string expression in a print statement shall be assigned to +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. +The 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. @@ -1203,20 +1345,17 @@ without a newline. 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 +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] +.EX a[i++] = i++ -\f[R] -.fi +.EE .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. @@ -1225,28 +1364,23 @@ 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] +.EX x(i++, i++) -\f[R] -.fi +.EE .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] +.EX define I(I,...,I){ auto I,...,I S;...;S return(E) } -\f[R] -.fi +.EE .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 @@ -1257,10 +1391,10 @@ 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 +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 +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] @@ -1274,18 +1408,15 @@ 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] +.EX define void I(I,...,I){ auto I,...,I S;...;S return } -\f[R] -.fi +.EE .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. @@ -1299,17 +1430,14 @@ 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]. +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] +.EX *I[] -\f[R] -.fi +.EE .PP it is a \f[B]reference\f[R]. Any changes to the array in the function are reflected, when the @@ -1317,20 +1445,17 @@ 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]. +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 +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 +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: +The standard (see the \f[B]STANDARDS\f[R] section) 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. @@ -1381,13 +1506,12 @@ 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] +\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). +standard (see the \f[B]STANDARDS\f[R] section). .PP -The extended library is a \f[B]non-portable extension\f[R]. +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] @@ -1404,17 +1528,25 @@ Functions\f[R] subsection below). .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). +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). +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]max(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is greater than \f[B]b\f[R]; +otherwise, returns \f[B]b\f[R]. +.TP +\f[B]min(a, b)\f[R] +Returns \f[B]a\f[R] if \f[B]a\f[R] is less than \f[B]b\f[R]; otherwise, +returns \f[B]b\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]. @@ -1425,6 +1557,10 @@ 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]fib(n)\f[R] +Returns the Fibonacci number of the truncated absolute value of +\f[B]n\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 @@ -1496,11 +1632,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1534,7 +1670,7 @@ Functions\f[R] subsection below). 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 +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]. @@ -1562,11 +1698,11 @@ Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns 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]. +\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]. +\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 @@ -1595,7 +1731,7 @@ 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 +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 @@ -1604,14 +1740,22 @@ 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]. +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. +is returned, and \f[B]seed\f[R] is not changed. +.TP +\f[B]i2rand(a, b)\f[R] +Takes the truncated value of \f[B]a\f[R] and \f[B]b\f[R] and uses them +as inclusive bounds to enerate a pseudo\-random integer. +If the difference of the truncated values of \f[B]a\f[R] and \f[B]b\f[R] +is \f[B]0\f[R], then the truncated value is returned, and \f[B]seed\f[R] +is \f[I]not\f[R] changed. +Otherwise, this function will change the value of \f[B]seed\f[R]. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability @@ -1653,8 +1797,8 @@ If you want to use signed two\[cq]s complement arguments, use .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. +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 @@ -1664,7 +1808,7 @@ If you want to use signed two\[cq]s complement arguments, use \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. +bit\-shifted right by \f[B]b\f[R] places. .RS .PP If you want to use signed two\[cq]s complement arguments, use @@ -1683,7 +1827,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]8\f[R] binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1692,7 +1836,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]16\f[R] binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1701,7 +1845,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]32\f[R] binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1710,7 +1854,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has \f[B]64\f[R] binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1728,7 +1872,7 @@ If you want to a use signed two\[cq]s complement argument, use .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 +though it has the same number of 8\-bit bytes as the truncated absolute value of \f[B]n\f[R]. .RS .PP @@ -1738,7 +1882,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 8 binary digits (\f[B]1\f[R] unsigned byte). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1747,7 +1891,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 16 binary digits (\f[B]2\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1756,7 +1900,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 32 binary digits (\f[B]4\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1765,7 +1909,7 @@ If you want to a use signed two\[cq]s complement argument, use .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). +though it has 64 binary digits (\f[B]8\f[R] unsigned bytes). .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1783,11 +1927,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1818,7 +1962,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]4\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 @@ -1829,7 +1973,7 @@ If you want to a use signed two\[cq]s complement argument, use .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] +\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]8\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 @@ -1841,9 +1985,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1852,11 +1996,11 @@ If you want to a use signed two\[cq]s complement argument, use .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 +\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. +8\-bit bytes. .RS .PP If you want to a use signed two\[cq]s complement argument, use @@ -1910,9 +2054,9 @@ If you want to a use signed two\[cq]s complement argument, use \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 +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. +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 @@ -1966,7 +2110,7 @@ If you want to a use signed two\[cq]s complement argument, use .RE .TP \f[B]bunrev(t)\f[R] -Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit +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. @@ -1977,29 +2121,29 @@ 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. +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. +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 +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 @@ -2007,9 +2151,9 @@ 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 +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 @@ -2021,22 +2165,22 @@ 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 +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. +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 +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. +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 +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] @@ -2080,7 +2224,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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 +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 @@ -2108,7 +2252,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2136,7 +2280,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2164,7 +2308,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2192,7 +2336,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2220,7 +2364,7 @@ subsection of the \f[B]FUNCTIONS\f[R] section). .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. +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 @@ -2267,19 +2411,18 @@ subsection of the \f[B]FUNCTIONS\f[R] section). \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. +\- 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 +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 the article at +https://people.eecs.berkeley.edu/\[ti]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 @@ -2330,8 +2473,7 @@ The transcendental functions in the extended math library are: .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 +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 @@ -2351,7 +2493,6 @@ 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. @@ -2374,7 +2515,6 @@ 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] @@ -2404,29 +2544,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]BC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -2434,28 +2574,28 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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. +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 @@ -2476,14 +2616,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -2495,7 +2635,7 @@ newlines. .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 +non\-zero value activates the copyright banner when bc(1) is in interactive mode, while zero deactivates it. .RS .PP @@ -2504,7 +2644,7 @@ 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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_SIGINT_RESET\f[R] @@ -2514,13 +2654,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_TTY_MODE\f[R] @@ -2529,11 +2669,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]BC_PROMPT\f[R] @@ -2542,18 +2682,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]BC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) exit after executing +the expressions and expression files, and a zero value makes bc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes bc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the standard (see +the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS bc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -2567,10 +2735,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -2592,7 +2760,7 @@ 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. +when the option \f[B]\-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] @@ -2615,7 +2783,7 @@ 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. +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) @@ -2626,19 +2794,18 @@ 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. +\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. +\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. +Per the standard (see the \f[B]STANDARDS\f[R] section), 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. +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 @@ -2647,7 +2814,6 @@ 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 @@ -2655,53 +2821,49 @@ 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 +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. +\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. +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), +required in the bc(1) standard (see the \f[B]STANDARDS\f[R] section), 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 +.SS Command\-Line History +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], +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. +\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. +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. +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] @@ -2710,7 +2872,7 @@ section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -2736,12 +2898,11 @@ 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. +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 +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 @@ -2754,24 +2915,31 @@ 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 +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . +The flags \f[B]\-efghiqsvVw\f[R], all long options, and the extensions noted above are extensions to that specification. .PP +In addition, the behavior of the \f[B]quit\f[R] implements an +interpretation of that specification that is different from all known +implementations. +For more information see the \f[B]Statements\f[R] subsection of the +\f[B]SYNTAX\f[R] section. +.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 +Before version \f[B]6.1.0\f[R], this bc(1) had incorrect behavior for +the \f[B]quit\f[R] statement. .PP -None are known. -Report bugs at https://git.yzena.com/gavin/bc. +No other bugs are known. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bc/N.1.md b/contrib/bc/manuals/bc/N.1.md index 51dad376b56..859c32e3e77 100644 --- a/contrib/bc/manuals/bc/N.1.md +++ b/contrib/bc/manuals/bc/N.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,12 +34,12 @@ 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*...] +**bc** [**-cCghilPqRsvVw**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # 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 +POSIX. (See the **STANDARDS** section.) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. @@ -63,6 +63,86 @@ that is a bug and should be reported. See the **BUGS** section. The following are the options that bc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **BC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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 the **-f** and **-\-file** options), + 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 the **-e** and + **-\-expression** options), 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**. + **-g**, **-\-global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. @@ -133,7 +213,16 @@ The following are the options that bc(1) accepts. **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. + +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -157,6 +246,15 @@ The following are the options that bc(1) accepts. To learn what is in the libraries, see the **LIBRARY** section. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -170,6 +268,19 @@ The following are the options that bc(1) accepts. This is a **non-portable extension**. +**-q**, **-\-quiet** + +: 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 **-v**, **-V**, or **-\-version** options are given + unless the **BC_BANNER** environment variable is set and contains a non-zero + integer or if this bc(1) was built with the header displayed by default. If + *any* of that is the case, then this option *does* prevent bc(1) from + printing the header. + + This is a **non-portable extension**. + **-R**, **-\-no-read-prompt** : Disables the read prompt in TTY mode. (The read prompt is only enabled in @@ -223,29 +334,29 @@ The following are the options that bc(1) accepts. 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. + It is a fatal error to redefine keywords mandated by the POSIX standard (see + the **STANDARDS** section). It is a fatal error to attempt to redefine words + that this bc(1) does not reserve as keywords. -**-q**, **-\-quiet** +**-S** *scale*, **-\-scale**=*scale* + +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. -: 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. + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. **-s**, **-\-standard** -: Process exactly the language defined by the [standard][1] and error if any - extensions are used. +: Process exactly the language defined by the standard (see the **STANDARDS** + section) and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **-\-version** -: Print the version information (copyright header) and exit. +: Print the version information (copyright header) and exits. This is a **non-portable extension**. @@ -261,50 +372,18 @@ The following are the options that bc(1) accepts. : 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)**, + 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**. +**-\-expression** options, then bc(1) reads from **stdin**. However, there are a few caveats to this. @@ -350,9 +429,9 @@ it is recommended that those scripts be changed to redirect **stderr** to # 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. +bc(1) follows the POSIX standard (see the **STANDARDS** section), 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. @@ -479,46 +558,54 @@ The following are valid operands in bc(1): 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 +9. **is_number(E)**: **1** if the given argument is a number, **0** if it is a + string. This is a **non-portable extension**. +10. **is_string(E)**: **1** if the given argument is a string, **0** if it is a + number. This is a **non-portable extension**. +11. **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 +11. **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 +12. **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 +13. **asciify(I[])**: A string that is made up of the characters that would + result from running **asciify(E)** on each element of the array identified + by the argument. This allows creating multi-character strings and storing + them. This is a **non-portable extension**. +14. **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 +15. **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 +16. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. -15. **maxobase()**: The max allowable **obase**. This is a **non-portable +17. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. -16. **maxscale()**: The max allowable **scale**. This is a **non-portable +18. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. -17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the +19. **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** +20. **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** +21. **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 +22. **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**. -21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the +23. **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 @@ -529,7 +616,7 @@ The following are valid operands in bc(1): 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**. -22. **maxrand()**: The max integer returned by **rand()**. This is a +24. **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 @@ -548,14 +635,40 @@ use a non-seeded pseudo-random number generator. 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**. +letters are equal to **9** plus their position in the alphabet, starting from +**1** (i.e., **A** equals **10**, or **9+1**). + +If a digit or letter makes no sense with the current value of **ibase** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **BC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard (see the STANDARDS section) and is meant to provide an +easy way to set the current **ibase** (with the **i** command) regardless of the +current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -698,6 +811,9 @@ The operators will be described in more detail below. : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. + **Warning**: This operator has a **different precedence** than the + equivalent operator in GNU bc(1) and other bc(1) implementations! + This is a **non-portable extension**. **\$** @@ -805,9 +921,9 @@ The operators will be described in more detail below. **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**. + Also, unlike the standard (see the **STANDARDS** section) requires, these + operators can appear anywhere any other expressions can be used. This + allowance is a **non-portable extension**. **&&** @@ -871,6 +987,19 @@ 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). +**Warning**: The behavior of this bc(1) on **quit** is slightly different from +other bc(1) implementations. Other bc(1) implementations will exit as soon as +they finish parsing the line that a **quit** command is on. This bc(1) will +execute any completed and executable statements that occur before the **quit** +statement before exiting. + +In other words, for the bc(1) code below: + + for (i = 0; i < 3; ++i) i; quit + +Other bc(1) implementations will print nothing, and this bc(1) will print **0**, +**1**, and **2** on successive lines before exiting. + 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.) @@ -942,7 +1071,7 @@ like any other expression that is printed. ## Stream Statement -The "expressions in a **stream** statement may also be strings. +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** @@ -1054,7 +1183,8 @@ equivalents are given. ## Standard Library -The [standard][1] defines the following functions for the math library: +The standard (see the **STANDARDS** section) defines the following functions for +the math library: **s(x)** @@ -1102,7 +1232,7 @@ The [standard][1] defines the following functions for the math 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]. +defined by the standard (see the **STANDARDS** section). The extended library is a **non-portable extension**. @@ -1119,17 +1249,27 @@ The extended library is a **non-portable extension**. **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round half away from **0**][3]. + round half away from **0** + (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode - [round away from **0**][6]. + round away from **0** + (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). **f(x)** : Returns the factorial of the truncated absolute value of **x**. +**max(a, b)** + +: Returns **a** if **a** is greater than **b**; otherwise, returns **b**. + +**min(a, b)** + +: Returns **a** if **a** is less than **b**; otherwise, returns **b**. + **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the @@ -1140,6 +1280,10 @@ The extended library is a **non-portable extension**. : 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**. +**fib(n)** + +: Returns the Fibonacci number of the truncated absolute value of **n**. + **l2(x)** : Returns the logarithm base **2** of **x**. @@ -1302,7 +1446,15 @@ The extended library is a **non-portable extension**. 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. + **seed**; otherwise, **0** is returned, and **seed** is not changed. + +**i2rand(a, b)** + +: Takes the truncated value of **a** and **b** and uses them as inclusive + bounds to enerate a pseudo-random integer. If the difference of the + truncated values of **a** and **b** is **0**, then the truncated value is + returned, and **seed** is *not* changed. Otherwise, this function will + change the value of **seed**. **srand(x)** @@ -1364,7 +1516,7 @@ The extended library is a **non-portable extension**. **bnot8(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **8** binary digits (1 unsigned byte). + **8** binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1372,7 +1524,7 @@ The extended library is a **non-portable extension**. **bnot16(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **16** binary digits (2 unsigned bytes). + **16** binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1380,7 +1532,7 @@ The extended library is a **non-portable extension**. **bnot32(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **32** binary digits (4 unsigned bytes). + **32** binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1388,7 +1540,7 @@ The extended library is a **non-portable extension**. **bnot64(x)** : Does a bitwise not of the truncated absolute value of **x** as though it has - **64** binary digits (8 unsigned bytes). + **64** binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1412,7 +1564,7 @@ The extended library is a **non-portable extension**. **brev8(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 8 binary digits (1 unsigned byte). + has 8 binary digits (**1** unsigned byte). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1420,7 +1572,7 @@ The extended library is a **non-portable extension**. **brev16(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 16 binary digits (2 unsigned bytes). + has 16 binary digits (**2** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1428,7 +1580,7 @@ The extended library is a **non-portable extension**. **brev32(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 32 binary digits (4 unsigned bytes). + has 32 binary digits (**4** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1436,7 +1588,7 @@ The extended library is a **non-portable extension**. **brev64(x)** : Runs a bit reversal on the truncated absolute value of **x** as though it - has 64 binary digits (8 unsigned bytes). + has 64 binary digits (**8** unsigned bytes). If you want to a use signed two's complement argument, use **s2u(x)** to convert. @@ -1483,7 +1635,7 @@ The extended library is a **non-portable extension**. **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 + though it has **32** binary digits (**4** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **32**. @@ -1493,7 +1645,7 @@ The extended library is a **non-portable extension**. **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 + though it has **64** binary digits (**8** unsigned bytes), by the number of places equal to the truncated absolute value of **p** modded by **2** to the power of **64**. @@ -1888,10 +2040,11 @@ The extended library is a **non-portable extension**. ## 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. +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 +the article at https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 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 @@ -2034,7 +2187,8 @@ be hit. # ENVIRONMENT VARIABLES -bc(1) recognizes the following environment variables: +As **non-portable extensions**, bc(1) recognizes the following environment +variables: **POSIXLY_CORRECT** @@ -2129,6 +2283,32 @@ bc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**BC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes bc(1) exit + after executing the expressions and expression files, and a zero value makes + bc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**BC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes bc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the standard (see the + **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS bc(1) returns the following exit statuses: @@ -2204,10 +2384,10 @@ checking, and its normal behavior can be forced by using the **-i** flag or # 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. +Per the standard (see the **STANDARDS** section), 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 @@ -2233,8 +2413,8 @@ 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. +in the bc(1) standard (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -2315,9 +2495,14 @@ 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. +bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) specification +at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . The +flags **-efghiqsvVw**, all long options, and the extensions noted above are +extensions to that specification. + +In addition, the behavior of the **quit** implements an interpretation of that +specification that is different from all known implementations. For more +information see the **Statements** subsection of the **SYNTAX** section. 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 @@ -2325,15 +2510,11 @@ use a period (**.**) as a radix point, regardless of the value of # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +Before version **6.1.0**, this bc(1) had incorrect behavior for the **quit** +statement. -# AUTHORS +No other bugs are known. Report bugs at https://git.gavinhoward.com/gavin/bc . -Gavin D. Howard and contributors. +# AUTHORS -[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 +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bcl.3 b/contrib/bc/manuals/bcl.3 index 9370417dcfe..f2791624b2c 100644 --- a/contrib/bc/manuals/bcl.3 +++ b/contrib/bc/manuals/bcl.3 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,28 +25,24 @@ .\" 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" +.TH "BCL" "3" "January 2024" "Gavin D. Howard" "Libraries Manual" +.nh +.ad l .SH NAME -.PP -bcl - library of arbitrary precision decimal arithmetic +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] +Link with \f[I]\-lbcl\f[R], and on POSIX systems, \f[I]\-lpthread\f[R] +is also required. .SS Setup -.PP These items allow clients to set up bcl(3). .PP +\f[B]BclError bcl_start(\f[R]\f[I]void\f[R]\f[B]);\f[R] +.PP +\f[B]void bcl_end(\f[R]\f[I]void\f[R]\f[B]);\f[R] +.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] @@ -61,8 +57,11 @@ These items allow clients to set up bcl(3). \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 +\f[B]bool bcl_digitClamp(\f[R]\f[I]void\f[R]\f[B]);\f[R] +.PP +\f[B]void bcl_setDigitClamp(bool\f[R] \f[I]digitClamp\f[R]\f[B]);\f[R] +.SS 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. @@ -98,16 +97,14 @@ size_t\f[R] \f[I]ibase\f[R]\f[B]);\f[R] \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). +arbitrary\-precision numbers managed by bcl(3). .PP \f[B]typedef struct { size_t i; } BclNumber;\f[R] .PP @@ -127,7 +124,6 @@ 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 @@ -136,48 +132,84 @@ integers. .PP \f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP +\f[B]char* bcl_string_keep(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]BclError bcl_bigdig_keep(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_add_keep(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_sub_keep(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_mul_keep(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_div_keep(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_mod_keep(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_pow_keep(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_lshift_keep(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_rshift_keep(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]BclNumber bcl_sqrt_keep(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]BclError bcl_divmod_keep(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 +\f[B]BclNumber bcl_modexp_keep(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 These items are miscellaneous. .PP \f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] @@ -191,9 +223,8 @@ These items are miscellaneous. \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 +.SS Pseudo\-Random Number Generator +These items allow clients to manipulate the seeded pseudo\-random number generator in bcl(3). .PP \f[B]#define BCL_SEED_ULONGS\f[R] @@ -206,14 +237,22 @@ generator in bcl(3). .PP \f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_irand_keep(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]BclNumber bcl_ifrand_keep(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_seedWithNum_keep(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 @@ -226,15 +265,10 @@ generator in bcl(3). \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.) +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) 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 @@ -243,53 +277,66 @@ without collision. 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. +.SS Setup +.TP +\f[B]BclError bcl_start(\f[R]\f[I]void\f[R]\f[B])\f[R] +Initializes this library. +This function can be called multiple times, but \f[B]bcl_end()\f[R] must +only be called \f[I]once\f[R]. +This is to make it possible for multiple libraries and applications to +initialize bcl(3) without problem. .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. +It is suggested that client libraries call this function, but do not +call \f[B]bcl_end()\f[R], and client applications should call both. .PP -See the \f[B]SIGNAL HANDLING\f[R] section. +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]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]. +\f[B]void bcl_end(\f[R]\f[I]void\f[R]\f[B])\f[R] +Deinitializes this library. +This function must only be called \f[I]once\f[R]. .RS .PP -See the \f[B]SIGNAL HANDLING\f[R] section. +All data must have been freed before calling this function. +.PP +This function must be the last one clients call. +Calling this function before calling any other function is undefined +behavior. .RE -.SS Setup .TP \f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B])\f[R] -Initializes this library. +Initializes the library for the current thread. 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. +initialize threads for bcl(3) without problem. .RS .PP +This function \f[I]must\f[R] be called from the thread that it is +supposed to initialize. +.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. +This function must be the second one clients call. +Calling any other function without calling \f[B]bcl_start()\f[R] and +then this one first is undefined behavior, except in the case of new +threads. +New threads can safely call this function without calling +\f[B]bcl_start()\f[R] if another thread has previously called +\f[B]bcl_start()\f[R]. +But this function must still be the first function in bcl(3) called by +that new thread. .RE .TP \f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R] @@ -297,9 +344,12 @@ 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. +This function \f[I]must\f[R] be called from the thread that it is +supposed to deinitialize. +.PP +This function must be the second to last one clients call. +Calling this function before calling any other function besides +\f[B]bcl_end()\f[R] is undefined behavior. .RE .TP \f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B])\f[R] @@ -311,6 +361,9 @@ a fatal error occurs. .PP If activated, clients do not need to check for fatal errors. .PP +This value is \f[I]thread\-local\f[R]; it applies to just the thread it +is read on. +.PP The default is \f[B]false\f[R]. .RE .TP @@ -322,32 +375,79 @@ 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 +This value is \f[I]thread\-local\f[R]; it applies to just the thread it +is set on. +.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]. +\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 +This value is \f[I]thread\-local\f[R]; it applies to just the thread it +is read on. +.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], +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]. +.RS +.PP +This value is \f[I]thread\-local\f[R]; it applies to just the thread it +is set on. +.RE +.TP +\f[B]bool bcl_digitClamp(\f[R]\f[I]void\f[R]\f[B])\f[R] +Queries and returns the state of whether digits in number strings that +are greater than or equal to the current \f[B]ibase\f[R] are clamped or +not. +.RS +.PP +If \f[B]true\f[R] is returned, then digits are treated as though they +are equal to the value of \f[B]ibase\f[R] minus \f[B]1\f[R]. +If this is \f[I]not\f[R] true, then digits are treated as though they +are equal to the value they would have if \f[B]ibase\f[R] was large +enough. +They are then multiplied by the appropriate power of \f[B]ibase\f[R]. +.PP +For example, with clamping off and an \f[B]ibase\f[R] of \f[B]3\f[R], +the string \[lq]AB\[rq] would equal \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which +is \f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R], +while with clamping on and an \f[B]ibase\f[R] of \f[B]3\f[R], the string +\[lq]AB\[rq] would be equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +This value is \f[I]thread\-local\f[R]; it applies to just the thread it +is read on. +.PP +The default is \f[B]true\f[R]. +.RE +.TP +\f[B]void bcl_setDigitClamp(bool\f[R] \f[I]digitClamp\f[R]\f[B])\f[R] +Sets the state of whether digits in number strings that are greater than +or equal to the current \f[B]ibase\f[R] are clamped or not. +For more information, see the +\f[B]bcl_digitClamp(\f[R]\f[I]void\f[R]\f[B])\f[R] function. +.RS +.PP +This value is \f[I]thread\-local\f[R]; it applies to just the thread it +is set on. +.RE .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. +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 @@ -390,6 +490,15 @@ 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. +.PP +Different threads also have different contexts, so any numbers created +in one thread are not valid in another thread. +To pass values between contexts and threads, use \f[B]bcl_string()\f[R] +to produce a string to pass around, and use \f[B]bcl_parse()\f[R] to +parse the string. +It is suggested that the \f[B]obase\f[R] used to create the string be +passed around with the string and used as the \f[B]ibase\f[R] for +\f[B]bcl_parse()\f[R] to ensure that the number will be the same. .RE .TP \f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R] @@ -466,13 +575,12 @@ If there was no error, it will return \f[B]BCL_ERROR_NONE\f[R]. 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. +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 +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] @@ -530,11 +638,11 @@ Otherwise, this function can return: 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. +All procedures in this section without the \f[B]_keep\f[R] suffix in +their name 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] @@ -542,7 +650,7 @@ 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. +\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 @@ -569,6 +677,11 @@ The string is dynamically allocated and must be freed by the caller. See the \f[B]Consumption and Propagation\f[R] subsection below. .RE .TP +\f[B]char* bcl_string_keep(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. +.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]. @@ -590,6 +703,24 @@ Otherwise, this function can return: See the \f[B]Consumption and Propagation\f[R] subsection below. .RE .TP +\f[B]BclError bcl_bigdig_keep(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] +.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 @@ -603,9 +734,13 @@ Possible errors include: \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 without the \f[B]_keep\f[R] suffix in +their name 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. +.PP All procedures in this section can return the following errors: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] @@ -637,6 +772,25 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_add_keep(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] 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 @@ -660,6 +814,25 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_sub_keep(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] 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 @@ -686,6 +859,28 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_mul_keep(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] 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 @@ -713,9 +908,32 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_div_keep(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] 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 +context, computes the modulus \f[B]a\-(a/b)*b\f[R], and returns the modulus. .RS .PP @@ -740,11 +958,34 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_mod_keep(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] 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. +If it is negative, \f[I]a\f[R] must be non\-zero. .RS .PP \f[I]b\f[R] must be an integer. @@ -776,6 +1017,38 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_pow_keep(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] 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. @@ -804,6 +1077,30 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_lshift_keep(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] 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. @@ -832,6 +1129,30 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_rshift_keep(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] 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 @@ -856,6 +1177,27 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_sqrt_keep(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 +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 @@ -884,6 +1226,30 @@ Otherwise, this function can return: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclError bcl_divmod_keep(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]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 @@ -916,6 +1282,35 @@ Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE +.TP +\f[B]BclNumber bcl_modexp_keep(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 +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] @@ -959,11 +1354,11 @@ Possible errors include: .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. +.SS Pseudo\-Random Number Generator +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. +pseudo\-random numbers twice. .PP By default, bcl(3) attempts to seed the PRNG with data from \f[B]/dev/urandom\f[R]. @@ -985,7 +1380,12 @@ 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 +All procedures in this section without the \f[B]_keep\f[R] suffix in +their name 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. +.PP +The following items allow clients to use the pseudo\-random number generator. All procedures require a valid current context. .TP @@ -1015,7 +1415,7 @@ 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. +\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. @@ -1037,6 +1437,36 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_irand_keep(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 +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 @@ -1061,7 +1491,7 @@ 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. +\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. @@ -1083,11 +1513,55 @@ Possible errors include: \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_ifrand_keep(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 +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. +\f[I]n\f[R] is 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_seedWithNum_keep(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] +Seeds the PRNG with \f[I]n\f[R]. +.RS .PP This procedure requires a valid current context. .PP @@ -1155,18 +1629,15 @@ Bias is removed before returning the integer. 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] +.EX BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); -\f[R] -.fi +.EE .PP If arguments to those functions were not consumed, memory would be leaked until reclaimed with \f[B]bcl_ctxt_freeNums(BclContext)\f[R]. @@ -1175,16 +1646,13 @@ 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] +.EX BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); -if (bc_num_err(n) != BCL_ERROR_NONE) { +if (bcl_err(n) != BCL_ERROR_NONE) { // Handle the error. } -\f[R] -.fi +.EE .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: @@ -1198,16 +1666,13 @@ An invalid \f[B]BclNumber\f[R] was given as a parameter. \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 +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] @@ -1222,7 +1687,7 @@ 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 +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. @@ -1242,7 +1707,7 @@ 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]. +\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] @@ -1275,14 +1740,17 @@ 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. +bcl(3) is \f[I]MT\-Safe\f[R]: it is safe to call any functions from more +than one thread. +However, is is \f[I]not\f[R] safe to pass any data between threads +except for strings returned by \f[B]bcl_string()\f[R]. +.PP +bcl(3) is not \f[I]async\-signal\-safe\f[R]. +It was not possible to make bcl(3) safe with signals and also make it +safe with multiple threads. +If it is necessary to be able to interrupt bcl(3), spawn a separate +thread to run the calculation. .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. @@ -1302,7 +1770,6 @@ 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] @@ -1332,63 +1799,43 @@ 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]. +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]. +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]. +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. +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). +1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html 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. +Report bugs at https://git.gavinhoward.com/gavin/bc. .SH AUTHORS -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/bcl.3.md b/contrib/bc/manuals/bcl.3.md index fa630fc79f1..41c1c120b62 100644 --- a/contrib/bc/manuals/bcl.3.md +++ b/contrib/bc/manuals/bcl.3.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -38,21 +38,16 @@ bcl - library of arbitrary precision decimal arithmetic *#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_**);** +Link with *-lbcl*, and on POSIX systems, *-lpthread* is also required. ## Setup These items allow clients to set up bcl(3). +**BclError bcl_start(**_void_**);** + +**void bcl_end(**_void_**);** + **BclError bcl_init(**_void_**);** **void bcl_free(**_void_**);** @@ -67,6 +62,10 @@ These items allow clients to set up bcl(3). **void bcl_gc(**_void_**);** +**bool bcl_digitClamp(**_void_**);** + +**void bcl_setDigitClamp(bool** _digitClamp_**);** + ## Contexts These items will allow clients to handle contexts, which are isolated from each @@ -137,8 +136,12 @@ These items allow clients to convert numbers into and from strings and integers. **char\* bcl_string(BclNumber** _n_**);** +**char\* bcl_string_keep(BclNumber** _n_**);** + **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);** +**BclError bcl_bigdig_keep(BclNumber** _n_**, BclBigDig \***_result_**);** + **BclNumber bcl_bigdig2num(BclBigDig** _val_**);** ## Math @@ -147,26 +150,48 @@ These items allow clients to run math on numbers. **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_add_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_sub_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_mul_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_div_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_mod_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_pow_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_lshift_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_rshift_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_sqrt(BclNumber** _a_**);** +**BclNumber bcl_sqrt_keep(BclNumber** _a_**);** + **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);** +**BclError bcl_divmod_keep(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);** + **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);** +**BclNumber bcl_modexp_keep(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);** + ## Miscellaneous These items are miscellaneous. @@ -196,12 +221,18 @@ generator in bcl(3). **BclNumber bcl_irand(BclNumber** _a_**);** +**BclNumber bcl_irand_keep(BclNumber** _a_**);** + **BclNumber bcl_frand(size_t** _places_**);** **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);** +**BclNumber bcl_ifrand_keep(BclNumber** _a_**, size_t** _places_**);** + **BclError bcl_rand_seedWithNum(BclNumber** _n_**);** +**BclError bcl_rand_seedWithNum_keep(BclNumber** _n_**);** + **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);** **void bcl_rand_reseed(**_void_**);** @@ -215,10 +246,8 @@ generator in bcl(3). # 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.) +standardized by POSIX +(https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1). bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and **Bc** prefixes for symbol names without collision. @@ -226,55 +255,67 @@ bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and All of the items in its interface are described below. See the documentation for each function for what each function can return. -## Signals +## Setup + +**BclError bcl_start(**_void_**)** -**void bcl_handleSignal(**_void_**)** +: Initializes this library. This function can be called multiple times, but + **bcl_end()** must only be called *once*. This is to make it possible for + multiple libraries and applications to initialize bcl(3) without problem. -: 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. + It is suggested that client libraries call this function, but do not call + **bcl_end()**, and client applications should call both. + + If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this + function can return: - If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not* - return to its caller. + * **BCL_ERROR_FATAL_ALLOC_ERR** - See the **SIGNAL HANDLING** section. + This function must be the first one clients call. Calling any other + function without calling this one first is undefined behavior. -**bool bcl_running(**_void_**)** +**void bcl_end(**_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**. +: Deinitializes this library. This function must only be called *once*. - See the **SIGNAL HANDLING** section. + All data must have been freed before calling this function. -## Setup + This function must be the last one clients call. Calling this function + before calling any other function is undefined behavior. **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. +: Initializes the library for the current thread. 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 threads for bcl(3) without problem. + + This function *must* be called from the thread that it is supposed to + initialize. 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. + This function must be the second one clients call. Calling any other + function without calling **bcl_start()** and then this one first is + undefined behavior, except in the case of new threads. New threads can + safely call this function without calling **bcl_start()** if another thread + has previously called **bcl_start()**. But this function must still be the + first function in bcl(3) called by that new thread. **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. + This function *must* be called from the thread that it is supposed to + deinitialize. + + This function must be the second to last one clients call. Calling this + function before calling any other function besides **bcl_end()** is + undefined behavior. **bool bcl_abortOnFatalError(**_void_**)** @@ -284,6 +325,8 @@ each function for what each function can return. If activated, clients do not need to check for fatal errors. + This value is *thread-local*; it applies to just the thread it is read on. + The default is **false**. **void bcl_setAbortOnFatalError(bool** _abrt_**)** @@ -293,6 +336,8 @@ each function for what each function can return. call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors after the call. + This value is *thread-local*; it applies to just the thread it is set on. + If activated, clients do not need to check for fatal errors. **bool bcl_leadingZeroes(**_void_**)** @@ -302,6 +347,8 @@ each function for what each function can return. **1**, and not equal to **0**. If **true** is returned, then leading zeroes will be added. + This value is *thread-local*; it applies to just the thread it is read on. + The default is **false**. **void bcl_setLeadingZeroes(bool** _leadingZeroes_**)** @@ -311,6 +358,37 @@ each function for what each function can return. not equal to **0**. If *leadingZeroes* is **true**, leading zeroes will be added to strings returned by **bcl_string()**. + This value is *thread-local*; it applies to just the thread it is set on. + +**bool bcl_digitClamp(**_void_**)** + +: Queries and returns the state of whether digits in number strings that are + greater than or equal to the current **ibase** are clamped or not. + + If **true** is returned, then digits are treated as though they are equal to + the value of **ibase** minus **1**. If this is *not* true, then digits are + treated as though they are equal to the value they would have if **ibase** + was large enough. They are then multiplied by the appropriate power of + **ibase**. + + For example, with clamping off and an **ibase** of **3**, the string "AB" + would equal **3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or + **41**, while with clamping on and an **ibase** of **3**, the string "AB" + would be equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus + **2**, or **8**. + + This value is *thread-local*; it applies to just the thread it is read on. + + The default is **true**. + +**void bcl_setDigitClamp(bool** _digitClamp_**)** + +: Sets the state of whether digits in number strings that are greater than or + equal to the current **ibase** are clamped or not. For more information, see + the **bcl_digitClamp(**_void_**)** function. + + This value is *thread-local*; it applies to just the thread it is set on. + **void bcl_gc(**_void_**)** : Garbage collects cached instances of arbitrary-precision numbers. This only @@ -356,6 +434,13 @@ an argument. are meant to isolate the numbers used by different clients in the same application. + Different threads also have different contexts, so any numbers created in + one thread are not valid in another thread. To pass values between contexts + and threads, use **bcl_string()** to produce a string to pass around, and + use **bcl_parse()** to parse the string. It is suggested that the **obase** + used to create the string be passed around with the string and used as the + **ibase** for **bcl_parse()** to ensure that the number will be the same. + **BclContext bcl_ctxt_create(**_void_**)** : Creates a context and returns it. Returns **NULL** if there was an error. @@ -495,9 +580,9 @@ All procedures in this section require a valid current context. 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. +All procedures in this section without the **_keep** suffix in their name +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_**)** @@ -525,6 +610,12 @@ subsection below. *n* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. +**char\* bcl_string_keep(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. + **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)** : Converts *n* into a **BclBigDig** and returns the result in the space @@ -542,6 +633,20 @@ subsection below. *n* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. +**BclError bcl_bigdig_keep(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** + **BclNumber bcl_bigdig2num(BclBigDig** _val_**)** : Creates a **BclNumber** from *val*. @@ -556,6 +661,10 @@ subsection below. All procedures in this section require a valid current context. +All procedures in this section without the **_keep** suffix in their name +consume the given **BclNumber** arguments that are not given to pointer +arguments. See the **Consumption and Propagation** subsection below. + All procedures in this section can return the following errors: * **BCL_ERROR_INVALID_NUM** @@ -579,6 +688,20 @@ All procedures in this section can return the following errors: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_add_keep(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* 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 @@ -596,6 +719,20 @@ All procedures in this section can return the following errors: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_sub_keep(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* 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 @@ -615,6 +752,22 @@ All procedures in this section can return the following errors: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_mul_keep(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* 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 @@ -635,6 +788,23 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_div_keep(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* 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 @@ -655,6 +825,23 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_mod_keep(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* 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. @@ -680,6 +867,28 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_pow_keep(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* 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 @@ -700,6 +909,23 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_lshift_keep(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* 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 @@ -720,6 +946,23 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_rshift_keep(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* 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 @@ -738,6 +981,21 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_NEGATIVE** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_sqrt_keep(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. + + 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 @@ -760,6 +1018,25 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclError bcl_divmod_keep(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**. + + *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 @@ -782,6 +1059,25 @@ All procedures in this section can return the following errors: * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_modexp_keep(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. + + 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_**)** @@ -838,6 +1134,10 @@ If necessary, the PRNG can be reseeded with one of the following functions: * **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])** * **bcl_rand_reseed(**_void_**)** +All procedures in this section without the **_keep** suffix in their name +consume the given **BclNumber** arguments that are not given to pointer +arguments. See the **Consumption and Propagation** subsection below. + The following items allow clients to use the pseudo-random number generator. All procedures require a valid current context. @@ -868,8 +1168,29 @@ procedures require a valid current context. *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. + *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_irand_keep(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. This procedure requires a valid current context. @@ -903,8 +1224,26 @@ procedures require a valid current context. *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. + *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_ifrand_keep(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. This procedure requires a valid current context. @@ -921,7 +1260,23 @@ procedures require a valid current context. : Seeds the PRNG with *n*. - *n* is *not* consumed. + *n* is 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_seedWithNum_keep(BclNumber** _n_**)** + +: Seeds the PRNG with *n*. This procedure requires a valid current context. @@ -993,7 +1348,7 @@ 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) { + if (bcl_err(n) != BCL_ERROR_NONE) { // Handle the error. } @@ -1014,10 +1369,6 @@ codes defined in **BclError**. The complete list of codes is the following: : 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 @@ -1087,11 +1438,13 @@ codes defined in **BclError**. The complete list of codes is the following: # ATTRIBUTES -When **bcl_handleSignal(**_void_**)** is used properly, bcl(3) is -async-signal-safe. +bcl(3) is *MT-Safe*: it is safe to call any functions from more than one thread. +However, is is *not* safe to pass any data between threads except for strings +returned by **bcl_string()**. -bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one -thread. +bcl(3) is not *async-signal-safe*. It was not possible to make bcl(3) safe with +signals and also make it safe with multiple threads. If it is necessary to be +able to interrupt bcl(3), spawn a separate thread to run the calculation. # PERFORMANCE @@ -1163,29 +1516,15 @@ These limits are meant to be effectively non-existent; the limits are so large 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). +bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017 +(“POSIX.1-2017â€) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html 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 @@ -1193,10 +1532,8 @@ use a period (**.**) as a radix point, regardless of the value of # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc. # AUTHORS -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/build.md b/contrib/bc/manuals/build.md index 1ed2b269f13..d9c46ae2260 100644 --- a/contrib/bc/manuals/build.md +++ b/contrib/bc/manuals/build.md @@ -40,13 +40,13 @@ accepted build options. ## Windows For releases, Windows builds of `bc`, `dc`, and `bcl` are available for download -from and GitHub. +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 enabled, history and NLS (locale support) disabled, with +supported: extra math and history enabled, 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`. @@ -83,6 +83,23 @@ where `` is either one of `Debug`, `ReleaseMD`, or `ReleaseMT`. Building `bc`, `dc`, and `bcl` (the library) is more complex than on Windows because many build options are supported. +### Out-of-Source Builds + +Out-of-source builds are done by calling `configure.sh` from the directory where +the build will happen. The `Makefile` is generated into that directory, and the +build can happen normally from there. + +For example, if the source is in `bc`, the build should happen in `build`, then +call `configure.sh` and `make` like so: + +``` +../bc/configure.sh +make +``` + +***WARNING***: The path to `configure.sh` from the build directory must not have +spaces because `make` does not support target names with spaces. + ### Cross Compiling To cross-compile this `bc`, an appropriate compiler must be present and assigned @@ -115,7 +132,7 @@ the environment variable `GEN_EMU`. This `bc` supports `CC`, `HOSTCC`, `HOST_CC`, `CFLAGS`, `HOSTCFLAGS`, `HOST_CFLAGS`, `CPPFLAGS`, `LDFLAGS`, `LDLIBS`, `PREFIX`, `DESTDIR`, `BINDIR`, -`DATAROOTDIR`, `DATADIR`, `MANDIR`, `MAN1DIR`, `LOCALEDIR` `EXECSUFFIX`, +`DATAROOTDIR`, `DATADIR`, `MANDIR`, `MAN1DIR`, `MAN3DIR`, `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. @@ -188,6 +205,10 @@ Can be overridden by passing the `--prefix` option to `configure.sh`. Defaults to `/usr/local`. +***WARNING***: Locales ignore the prefix because they *must* be installed at a +fixed location to work at all. If you do not want that to happen, you must +disable locales (NLS) completely. + #### `DESTDIR` Path to prepend onto `PREFIX`. This is mostly for distro and package @@ -255,13 +276,13 @@ Can be overridden by passing the `--man1dir` option to `configure.sh`. Defaults to `$MANDIR/man1`. -#### `LOCALEDIR` +#### `MAN3DIR` -The directory to install locales in. +The directory to install Section 3 manpages in. -Can be overridden by passing the `--localedir` option to `configure.sh`. +Can be overridden by passing the `--man3dir` option to `configure.sh`. -Defaults to `$DATAROOTDIR/locale`. +Defaults to `$MANDIR/man3`. #### `EXECSUFFIX` @@ -338,6 +359,30 @@ following forms: --option=arg ``` +#### Predefined Builds + +To quickly get a release build of a `bc` and `dc` that is (by default) +compatible with the BSD `bc` and `dc`, use the `-p` or `--predefined-build-type` +options: + +``` +./configure.sh -pBSD +./configure.sh --predefined-build-type=BSD +``` + +Both commands are equivalent. + +To quickly get a release build of a `bc` and `dc` that is (by default) +compatible with the GNU `bc` and `dc`, use the `-p` or `--predefined-build-type` +options: + +``` +./configure.sh -pGNU +./configure.sh --predefined-build-type=GNU +``` + +Both commands are equivalent. + #### Library To build the math library, use the following commands for the configure step: @@ -407,15 +452,74 @@ to `configure.sh`, as follows: 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]. +##### Editline + +History support can be provided by editline, in order to implement `vi`-like +keybindings and other features. + +To enable editline support, pass either the `-e` flag or the `--enable-editline` +option to `configure.sh`, as follows: + +``` +./configure.sh -e +./configure.sh --enable-editline +``` + +Both commands are equivalent. + +This is ignored if history is disabled. + +This option is only used if it is after any other `-e`/`--enable-editline` +options, any `-r`/`--enable-readline` options, and any +`-i`/`--enable-internal-history` options. + +##### Readline + +History support can be provided by readline, in order to implement `vi`-like +keybindings and other features. + +To enable readline support, pass either the `-r` flag or the `--enable-readline` +option to `configure.sh`, as follows: + +``` +./configure.sh -r +./configure.sh --enable-readline +``` + +Both commands are equivalent. + +This is ignored if history is disabled. + +This option is only used if it is after any other `-r`/`--enable-readline` +options, any `-e`/`--enable-editline` options, and any +`-i`/`--enable-internal-history` options. + +##### Internal History + +History support is also available as an internal implementation with no +dependencies. This is the default if editline and readline are not selected. + +However, if `-p` option is used, then this option can be useful for selecting +the internal history regardless of what the predefined build has. + +To enable the internal history, pass either the `-i` flag or the +`--enable-internal-history` option to `configure.sh` as follows: + +``` +./configure.sh -i +./configure.sh --enable-internal-history +``` + +This option is only used if it is after any other +`-i`/`--enable-internal-history` options, any `-e`/`--enable-editline` options, +and any `-r`/`--enable-readline` options. + #### NLS (Locale Support) To disable locale support (use only English), pass either the `-N` flag or the @@ -433,6 +537,10 @@ another platform that does not support the POSIX locale API or utilities. This option affects the [build type][7]. +***WARNING***: Locales ignore the prefix because they *must* be installed at a +fixed location to work at all. If you do not want that to happen, you must +disable locales (NLS) completely. + #### Extra Math This `bc` has 7 extra operators: @@ -559,6 +667,32 @@ environment variables to override them, is below: | | for dc should be on | | | | | in tty mode. | | | | --------------- | -------------------- | ------------ | -------------------- | +| bc.expr_exit | Whether to exit bc | 1 | BC_EXPR_EXIT | +| | if an expression or | | | +| | expression file is | | | +| | given with the -e or | | | +| | -f options. | | | +| --------------- | -------------------- | ------------ | -------------------- | +| dc.expr_exit | Whether to exit dc | 1 | DC_EXPR_EXIT | +| | if an expression or | | | +| | expression file is | | | +| | given with the -e or | | | +| | -f options. | | | +| --------------- | -------------------- | ------------ | -------------------- | +| bc.digit_clamp | Whether to have bc | 0 | BC_DIGIT_CLAMP | +| | clamp digits that | | | +| | are greater than or | | | +| | equal to the current | | | +| | ibase when parsing | | | +| | numbers. | | | +| --------------- | -------------------- | ------------ | -------------------- | +| dc.digit_clamp | Whether to have dc | 0 | DC_DIGIT_CLAMP | +| | clamp digits that | | | +| | are greater than or | | | +| | equal to the current | | | +| | ibase when parsing | | | +| | numbers. | | | +| --------------- | -------------------- | ------------ | -------------------- | ``` These settings are not meant to be changed on a whim. They are meant to ensure @@ -575,19 +709,22 @@ The relevant `autotools`-style install options are supported in `configure.sh`: * `--datadir` * `--mandir` * `--man1dir` -* `--localedir` +* `--man3dir` An example is: ``` -./configure.sh --prefix=/usr --localedir /usr/share/nls +./configure.sh --prefix=/usr make make install ``` They correspond to the environment variables `$PREFIX`, `$BINDIR`, -`$DATAROOTDIR`, `$DATADIR`, `$MANDIR`, `$MAN1DIR`, and `$LOCALEDIR`, -respectively. +`$DATAROOTDIR`, `$DATADIR`, `$MANDIR`, `$MAN1DIR`, `$MAN3DIR`, and respectively. + +***WARNING***: Locales ignore the prefix because they *must* be installed at a +fixed location to work at all. If you do not want that to happen, you must +disable locales (NLS) completely. ***WARNING***: If the option is given, the value of the corresponding environment variable is overridden. @@ -624,6 +761,10 @@ have, regardless. To enable that behavior, you can pass the `-l` flag or the Both commands are equivalent. +***WARNING***: Locales ignore the prefix because they *must* be installed at a +fixed location to work at all. If you do not want that to happen, you must +disable locales (NLS) completely. + ### Optimization The `configure.sh` script will accept an optimization level to pass to the @@ -825,6 +966,22 @@ Both commands are equivalent. ***WARNING***: Both `bc` and `dc` must be built for test coverage. Otherwise, `configure.sh` will give an error. +#### Problematic Tests + +Some tests are problematic, in that they can cause `SIGKILL` on FreeBSD or +`SIGSEGV` on Linux from being killed by the "OOM Killer" part of the kernel. On +Linux, these tests are usually fine, but on FreeBSD, they are usually a problem. + +To disable problematic tests, pass the `-P` flag or the +`--disable-problematic-tests` option to `configure.sh` as follows: + +``` +./configure.sh -P +./configure.sh --disable-problematic-tests +``` + +Both commands are equivalent. + [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://www.musl-libc.org/ diff --git a/contrib/bc/manuals/dc/A.1 b/contrib/bc/manuals/dc/A.1 index a7ff2e3a696..d59e0fa68a5 100644 --- a/contrib/bc/manuals/dc/A.1 +++ b/contrib/bc/manuals/dc/A.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,188 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\f[R]] .SH DESCRIPTION -.PP -dc(1) is an arbitrary-precision calculator. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] -Print the version information (copyright header) and exit. +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\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). +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 @@ -95,14 +214,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +236,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +284,7 @@ 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]. +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]. @@ -207,7 +292,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +300,12 @@ 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. +\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 @@ -229,7 +313,6 @@ 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. @@ -258,8 +341,8 @@ 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]. +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] @@ -271,14 +354,14 @@ 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. +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. +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. +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. @@ -288,39 +371,68 @@ 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 +\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. +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 +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. +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]. +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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. @@ -339,13 +451,11 @@ 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 +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 @@ -357,7 +467,7 @@ activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using 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]. +\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 @@ -377,12 +487,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -393,7 +503,6 @@ without altering anything. 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] @@ -402,7 +511,7 @@ 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] +\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 @@ -423,7 +532,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -433,10 +542,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -447,9 +556,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -460,7 +569,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -469,7 +578,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -479,7 +588,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -488,7 +597,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -497,12 +606,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -510,7 +619,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -520,9 +629,9 @@ extension. .RS .PP The first value popped off of the stack must be an integer and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]H\f[R] @@ -531,9 +640,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]h\f[R] @@ -542,9 +651,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -552,7 +661,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -560,7 +669,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -569,7 +678,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -578,7 +687,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -587,7 +696,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -596,42 +705,41 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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. +.SS 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 \f[B]seed\f[R] value that -controls the pseudo-random number generator.) +controls the pseudo\-random number generator.) .PP -The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] @@ -640,19 +748,19 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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 +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 @@ -664,12 +772,11 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -685,7 +792,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -707,7 +813,6 @@ 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. @@ -735,7 +840,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -745,7 +850,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the \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 +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 @@ -753,22 +858,22 @@ versions. 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] +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. +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]I\f[R] @@ -784,7 +889,7 @@ Pushes the current value of \f[B]scale\f[R] onto the main stack. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]T\f[R] @@ -792,7 +897,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -800,7 +905,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -808,18 +913,17 @@ 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]. +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. +\f[B]\[cq]\f[R] pseudo\-random number generator command. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 @@ -857,16 +961,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -902,7 +1006,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -923,7 +1027,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -944,7 +1048,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -965,7 +1069,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -986,7 +1090,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -1007,7 +1111,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -1020,7 +1124,7 @@ 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 +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. @@ -1031,8 +1135,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -1057,6 +1164,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -1072,10 +1197,9 @@ 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]. +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] @@ -1092,10 +1216,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -1107,12 +1230,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -1122,45 +1250,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -1180,7 +1308,6 @@ 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] @@ -1210,29 +1337,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]DC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1240,27 +1367,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1278,14 +1405,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1302,13 +1429,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1317,11 +1444,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1330,18 +1457,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1355,10 +1510,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -1393,7 +1548,7 @@ 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. +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) @@ -1404,17 +1559,17 @@ 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. +\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. +\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. +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. +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 @@ -1423,7 +1578,6 @@ 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 @@ -1431,53 +1585,49 @@ 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 +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. +\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. +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 +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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 +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], +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. +\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. +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. +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] @@ -1486,7 +1636,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1512,12 +1662,11 @@ 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. +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 +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 @@ -1527,23 +1676,20 @@ 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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/A.1.md b/contrib/bc/manuals/dc/A.1.md index 0007cc76760..ad0c59934fd 100644 --- a/contrib/bc/manuals/dc/A.1.md +++ b/contrib/bc/manuals/dc/A.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # DESCRIPTION @@ -55,13 +55,96 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* -: Print the version information (copyright header) and exit. +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +160,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +199,30 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. -**-x** **-\-extended-register** +**-S** *scale*, **-\-scale**=*scale* -: Enables extended register mode. See the *Extended Register Mode* subsection - of the **REGISTERS** section for more information. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +232,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -266,15 +335,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -902,6 +996,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -924,6 +1020,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -973,6 +1083,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -1014,11 +1130,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -1112,7 +1231,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1190,6 +1310,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1286,8 +1432,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -1370,15 +1516,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/E.1 b/contrib/bc/manuals/dc/E.1 index 8760477a03f..a5febe44705 100644 --- a/contrib/bc/manuals/dc/E.1 +++ b/contrib/bc/manuals/dc/E.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,173 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] -Print the version information (copyright header) and exit. +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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). +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 @@ -95,14 +199,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +221,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +269,7 @@ 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]. +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]. @@ -207,7 +277,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +285,12 @@ 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. +\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 @@ -229,7 +298,6 @@ 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. @@ -264,30 +332,57 @@ precision of any operations (with exceptions). 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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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] @@ -308,12 +403,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -324,7 +419,6 @@ without altering anything. 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] @@ -333,7 +427,7 @@ 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] +\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 @@ -354,7 +448,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -364,10 +458,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -378,9 +472,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -391,7 +485,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -400,7 +494,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -410,7 +504,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -419,7 +513,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -428,12 +522,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -441,7 +535,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -449,7 +543,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -458,7 +552,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -467,7 +561,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -476,7 +570,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -485,36 +579,35 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -530,7 +623,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -552,7 +644,6 @@ 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. @@ -579,7 +670,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -600,7 +691,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -608,7 +699,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -616,10 +707,9 @@ 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]. +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 @@ -657,16 +747,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -702,7 +792,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -723,7 +813,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -744,7 +834,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -765,7 +855,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -786,7 +876,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -807,7 +897,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -820,7 +910,7 @@ 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 +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. @@ -831,8 +921,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -857,6 +950,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -872,10 +983,9 @@ 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]. +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] @@ -892,10 +1002,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -907,12 +1016,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -922,45 +1036,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -980,7 +1094,6 @@ 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] @@ -1010,24 +1123,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1035,27 +1148,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1073,14 +1186,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1097,13 +1210,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1112,11 +1225,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1125,18 +1238,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1152,7 +1293,7 @@ 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. +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. @@ -1186,7 +1327,7 @@ 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. +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) @@ -1197,17 +1338,17 @@ 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. +\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. +\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. +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. +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 @@ -1216,7 +1357,6 @@ 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 @@ -1224,53 +1364,49 @@ 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 +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. +\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. +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 +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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 +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], +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. +\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. +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. +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] @@ -1279,7 +1415,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1305,12 +1441,11 @@ 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. +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 +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 @@ -1320,23 +1455,20 @@ 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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/E.1.md b/contrib/bc/manuals/dc/E.1.md index 6a2c465e564..54b877999d0 100644 --- a/contrib/bc/manuals/dc/E.1.md +++ b/contrib/bc/manuals/dc/E.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] # DESCRIPTION @@ -55,13 +55,87 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. -: Print the version information (copyright header) and exit. + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +151,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +190,30 @@ The following are the options that dc(1) accepts. 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** +**-S** *scale*, **-\-scale**=*scale* -: Makes bc(1) print all numbers greater than **-1** and less than **1**, and - not equal to **0**, with a leading zero. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +223,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -236,15 +296,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. # COMMANDS @@ -742,6 +827,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -764,6 +851,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -813,6 +914,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -854,11 +961,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -947,7 +1057,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1025,6 +1136,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1119,8 +1256,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -1203,15 +1340,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/EH.1 b/contrib/bc/manuals/dc/EH.1 index 4506001dfe5..61fbaa4efe9 100644 --- a/contrib/bc/manuals/dc/EH.1 +++ b/contrib/bc/manuals/dc/EH.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,173 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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. +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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). +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 @@ -95,14 +199,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +221,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +269,7 @@ 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]. +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]. @@ -207,7 +277,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +285,12 @@ 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. +\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 @@ -229,7 +298,6 @@ 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. @@ -264,30 +332,57 @@ precision of any operations (with exceptions). 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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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] @@ -308,12 +403,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -324,7 +419,6 @@ without altering anything. 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] @@ -333,7 +427,7 @@ 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] +\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 @@ -354,7 +448,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -364,10 +458,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -378,9 +472,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -391,7 +485,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -400,7 +494,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -410,7 +504,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -419,7 +513,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -428,12 +522,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -441,7 +535,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -449,7 +543,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -458,7 +552,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -467,7 +561,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -476,7 +570,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -485,36 +579,35 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -530,7 +623,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -552,7 +644,6 @@ 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. @@ -579,7 +670,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -600,7 +691,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -608,7 +699,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -616,10 +707,9 @@ 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]. +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 @@ -657,16 +747,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -702,7 +792,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -723,7 +813,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -744,7 +834,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -765,7 +855,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -786,7 +876,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -807,7 +897,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -820,7 +910,7 @@ 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 +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. @@ -831,8 +921,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -857,6 +950,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -872,10 +983,9 @@ 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]. +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] @@ -892,10 +1002,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -907,12 +1016,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -922,45 +1036,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -980,7 +1094,6 @@ 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] @@ -1010,24 +1123,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1035,27 +1148,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1073,14 +1186,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1097,13 +1210,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1112,11 +1225,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1125,18 +1238,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1152,7 +1293,7 @@ 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. +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. @@ -1186,7 +1327,7 @@ 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. +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) @@ -1197,17 +1338,17 @@ 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. +\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. +\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. +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. +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 @@ -1216,7 +1357,6 @@ 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 @@ -1224,45 +1364,42 @@ 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 +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. +\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. +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. +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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], +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. +\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. +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. +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] @@ -1271,7 +1408,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1294,23 +1431,20 @@ the user to continue. \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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/EH.1.md b/contrib/bc/manuals/dc/EH.1.md index 06ec59d4b3f..6398477a84d 100644 --- a/contrib/bc/manuals/dc/EH.1.md +++ b/contrib/bc/manuals/dc/EH.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] # DESCRIPTION @@ -55,13 +55,87 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. -: Print the version information (copyright header) and exit. + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +151,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +190,30 @@ The following are the options that dc(1) accepts. 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** +**-S** *scale*, **-\-scale**=*scale* -: Makes bc(1) print all numbers greater than **-1** and less than **1**, and - not equal to **0**, with a leading zero. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +223,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -236,15 +296,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. # COMMANDS @@ -742,6 +827,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -764,6 +851,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -813,6 +914,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -854,11 +961,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -947,7 +1057,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1025,6 +1136,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1119,8 +1256,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -1180,15 +1317,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/EHN.1 b/contrib/bc/manuals/dc/EHN.1 index 1124d907bdd..974cb3c8679 100644 --- a/contrib/bc/manuals/dc/EHN.1 +++ b/contrib/bc/manuals/dc/EHN.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,173 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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. +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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). +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 @@ -95,14 +199,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +221,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +269,7 @@ 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]. +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]. @@ -207,7 +277,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +285,12 @@ 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. +\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 @@ -229,7 +298,6 @@ 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. @@ -264,30 +332,57 @@ precision of any operations (with exceptions). 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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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] @@ -308,12 +403,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -324,7 +419,6 @@ without altering anything. 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] @@ -333,7 +427,7 @@ 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] +\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 @@ -354,7 +448,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -364,10 +458,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -378,9 +472,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -391,7 +485,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -400,7 +494,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -410,7 +504,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -419,7 +513,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -428,12 +522,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -441,7 +535,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -449,7 +543,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -458,7 +552,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -467,7 +561,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -476,7 +570,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -485,36 +579,35 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -530,7 +623,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -552,7 +644,6 @@ 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. @@ -579,7 +670,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -600,7 +691,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -608,7 +699,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -616,10 +707,9 @@ 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]. +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 @@ -657,16 +747,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -702,7 +792,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -723,7 +813,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -744,7 +834,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -765,7 +855,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -786,7 +876,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -807,7 +897,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -820,7 +910,7 @@ 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 +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. @@ -831,8 +921,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -857,6 +950,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -872,10 +983,9 @@ 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]. +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] @@ -892,10 +1002,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -907,12 +1016,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -922,45 +1036,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -980,7 +1094,6 @@ 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] @@ -1010,24 +1123,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1035,27 +1148,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1073,14 +1186,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1097,13 +1210,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1112,11 +1225,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1125,18 +1238,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1152,7 +1293,7 @@ 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. +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. @@ -1186,7 +1327,7 @@ 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. +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) @@ -1197,17 +1338,17 @@ 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. +\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. +\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. +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. +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 @@ -1216,7 +1357,6 @@ 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 @@ -1224,45 +1364,42 @@ 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 +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. +\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. +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. +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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], +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. +\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. +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. +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] @@ -1271,7 +1408,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1294,19 +1431,17 @@ the user to continue. \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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/EHN.1.md b/contrib/bc/manuals/dc/EHN.1.md index 50cb37ef258..51e30849996 100644 --- a/contrib/bc/manuals/dc/EHN.1.md +++ b/contrib/bc/manuals/dc/EHN.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] # DESCRIPTION @@ -55,13 +55,87 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. -: Print the version information (copyright header) and exit. + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +151,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +190,30 @@ The following are the options that dc(1) accepts. 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** +**-S** *scale*, **-\-scale**=*scale* -: Makes bc(1) print all numbers greater than **-1** and less than **1**, and - not equal to **0**, with a leading zero. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +223,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -236,15 +296,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. # COMMANDS @@ -742,6 +827,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -764,6 +851,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -813,6 +914,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -854,11 +961,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -947,7 +1057,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1025,6 +1136,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1119,8 +1256,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -1175,15 +1312,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/EN.1 b/contrib/bc/manuals/dc/EN.1 index beae0e46a9b..5ce8defc91c 100644 --- a/contrib/bc/manuals/dc/EN.1 +++ b/contrib/bc/manuals/dc/EN.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,173 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] -Print the version information (copyright header) and exit. +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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). +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 @@ -95,14 +199,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +221,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +269,7 @@ 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]. +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]. @@ -207,7 +277,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +285,12 @@ 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. +\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 @@ -229,7 +298,6 @@ 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. @@ -264,30 +332,57 @@ precision of any operations (with exceptions). 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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\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] @@ -308,12 +403,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -324,7 +419,6 @@ without altering anything. 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] @@ -333,7 +427,7 @@ 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] +\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 @@ -354,7 +448,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -364,10 +458,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -378,9 +472,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -391,7 +485,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -400,7 +494,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -410,7 +504,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -419,7 +513,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -428,12 +522,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -441,7 +535,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -449,7 +543,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -458,7 +552,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -467,7 +561,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -476,7 +570,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -485,36 +579,35 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -530,7 +623,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -552,7 +644,6 @@ 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. @@ -579,7 +670,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -600,7 +691,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -608,7 +699,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -616,10 +707,9 @@ 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]. +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 @@ -657,16 +747,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -702,7 +792,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -723,7 +813,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -744,7 +834,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -765,7 +855,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -786,7 +876,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -807,7 +897,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -820,7 +910,7 @@ 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 +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. @@ -831,8 +921,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -857,6 +950,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -872,10 +983,9 @@ 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]. +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] @@ -892,10 +1002,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -907,12 +1016,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -922,45 +1036,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -980,7 +1094,6 @@ 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] @@ -1010,24 +1123,24 @@ 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]. +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]. +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]. +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]. +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]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1035,27 +1148,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1073,14 +1186,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1097,13 +1210,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1112,11 +1225,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1125,18 +1238,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1152,7 +1293,7 @@ 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. +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. @@ -1186,7 +1327,7 @@ 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. +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) @@ -1197,17 +1338,17 @@ 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. +\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. +\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. +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. +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 @@ -1216,7 +1357,6 @@ 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 @@ -1224,53 +1364,49 @@ 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 +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. +\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. +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 +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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 +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], +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. +\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. +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. +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] @@ -1279,7 +1415,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1305,12 +1441,11 @@ 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. +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 +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 @@ -1320,19 +1455,17 @@ 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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/EN.1.md b/contrib/bc/manuals/dc/EN.1.md index db6f27f3457..ab9647a196b 100644 --- a/contrib/bc/manuals/dc/EN.1.md +++ b/contrib/bc/manuals/dc/EN.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] # DESCRIPTION @@ -55,13 +55,87 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* + +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. -: Print the version information (copyright header) and exit. + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +151,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +190,30 @@ The following are the options that dc(1) accepts. 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** +**-S** *scale*, **-\-scale**=*scale* -: Makes bc(1) print all numbers greater than **-1** and less than **1**, and - not equal to **0**, with a leading zero. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +223,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -236,15 +296,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. # COMMANDS @@ -742,6 +827,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -764,6 +851,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -813,6 +914,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -854,11 +961,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -947,7 +1057,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1025,6 +1136,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1119,8 +1256,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -1198,15 +1335,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/H.1 b/contrib/bc/manuals/dc/H.1 index b4ab9f51108..82c1bbd5c2b 100644 --- a/contrib/bc/manuals/dc/H.1 +++ b/contrib/bc/manuals/dc/H.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,188 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\f[R]] .SH DESCRIPTION -.PP -dc(1) is an arbitrary-precision calculator. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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. +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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). +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 @@ -95,14 +214,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +236,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +284,7 @@ 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]. +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]. @@ -207,7 +292,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +300,12 @@ 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. +\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 @@ -229,7 +313,6 @@ 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. @@ -258,8 +341,8 @@ 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]. +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] @@ -271,14 +354,14 @@ 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. +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. +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. +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. @@ -288,39 +371,68 @@ 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 +\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. +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 +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. +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]. +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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. @@ -339,13 +451,11 @@ 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 +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 @@ -357,7 +467,7 @@ activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using 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]. +\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 @@ -377,12 +487,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -393,7 +503,6 @@ without altering anything. 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] @@ -402,7 +511,7 @@ 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] +\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 @@ -423,7 +532,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -433,10 +542,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -447,9 +556,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -460,7 +569,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -469,7 +578,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -479,7 +588,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -488,7 +597,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -497,12 +606,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -510,7 +619,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -520,9 +629,9 @@ extension. .RS .PP The first value popped off of the stack must be an integer and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]H\f[R] @@ -531,9 +640,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]h\f[R] @@ -542,9 +651,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -552,7 +661,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -560,7 +669,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -569,7 +678,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -578,7 +687,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -587,7 +696,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -596,42 +705,41 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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. +.SS 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 \f[B]seed\f[R] value that -controls the pseudo-random number generator.) +controls the pseudo\-random number generator.) .PP -The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] @@ -640,19 +748,19 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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 +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 @@ -664,12 +772,11 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -685,7 +792,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -707,7 +813,6 @@ 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. @@ -735,7 +840,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -745,7 +850,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the \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 +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 @@ -753,22 +858,22 @@ versions. 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] +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. +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]I\f[R] @@ -784,7 +889,7 @@ Pushes the current value of \f[B]scale\f[R] onto the main stack. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]T\f[R] @@ -792,7 +897,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -800,7 +905,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -808,18 +913,17 @@ 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]. +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. +\f[B]\[cq]\f[R] pseudo\-random number generator command. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 @@ -857,16 +961,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -902,7 +1006,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -923,7 +1027,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -944,7 +1048,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -965,7 +1069,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -986,7 +1090,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -1007,7 +1111,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -1020,7 +1124,7 @@ 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 +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. @@ -1031,8 +1135,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -1057,6 +1164,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -1072,10 +1197,9 @@ 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]. +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] @@ -1092,10 +1216,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -1107,12 +1230,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -1122,45 +1250,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -1180,7 +1308,6 @@ 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] @@ -1210,29 +1337,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]DC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1240,27 +1367,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1278,14 +1405,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1302,13 +1429,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1317,11 +1444,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1330,18 +1457,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1355,10 +1510,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -1393,7 +1548,7 @@ 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. +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) @@ -1404,17 +1559,17 @@ 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. +\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. +\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. +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. +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 @@ -1423,7 +1578,6 @@ 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 @@ -1431,45 +1585,42 @@ 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 +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. +\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. +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. +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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], +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. +\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. +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. +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] @@ -1478,7 +1629,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1501,23 +1652,20 @@ the user to continue. \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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/H.1.md b/contrib/bc/manuals/dc/H.1.md index 647d486adc3..64c7142bc4a 100644 --- a/contrib/bc/manuals/dc/H.1.md +++ b/contrib/bc/manuals/dc/H.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # DESCRIPTION @@ -55,13 +55,96 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* -: Print the version information (copyright header) and exit. +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +160,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +199,30 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. -**-x** **-\-extended-register** +**-S** *scale*, **-\-scale**=*scale* -: Enables extended register mode. See the *Extended Register Mode* subsection - of the **REGISTERS** section for more information. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +232,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -266,15 +335,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -902,6 +996,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -924,6 +1020,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -973,6 +1083,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -1014,11 +1130,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -1112,7 +1231,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1190,6 +1310,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1286,8 +1432,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -1347,15 +1493,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/HN.1 b/contrib/bc/manuals/dc/HN.1 index eb35cb23ff7..c3f8c8ab1ff 100644 --- a/contrib/bc/manuals/dc/HN.1 +++ b/contrib/bc/manuals/dc/HN.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,188 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\f[R]] .SH DESCRIPTION -.PP -dc(1) is an arbitrary-precision calculator. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.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. +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. +.TP +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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). +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 @@ -95,14 +214,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +236,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +284,7 @@ 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]. +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]. @@ -207,7 +292,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +300,12 @@ 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. +\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 @@ -229,7 +313,6 @@ 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. @@ -258,8 +341,8 @@ 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]. +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] @@ -271,14 +354,14 @@ 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. +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. +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. +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. @@ -288,39 +371,68 @@ 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 +\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. +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 +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. +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]. +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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. @@ -339,13 +451,11 @@ 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 +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 @@ -357,7 +467,7 @@ activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using 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]. +\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 @@ -377,12 +487,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -393,7 +503,6 @@ without altering anything. 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] @@ -402,7 +511,7 @@ 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] +\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 @@ -423,7 +532,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -433,10 +542,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -447,9 +556,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -460,7 +569,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -469,7 +578,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -479,7 +588,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -488,7 +597,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -497,12 +606,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -510,7 +619,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -520,9 +629,9 @@ extension. .RS .PP The first value popped off of the stack must be an integer and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]H\f[R] @@ -531,9 +640,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]h\f[R] @@ -542,9 +651,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -552,7 +661,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -560,7 +669,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -569,7 +678,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -578,7 +687,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -587,7 +696,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -596,42 +705,41 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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. +.SS 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 \f[B]seed\f[R] value that -controls the pseudo-random number generator.) +controls the pseudo\-random number generator.) .PP -The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] @@ -640,19 +748,19 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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 +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 @@ -664,12 +772,11 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -685,7 +792,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -707,7 +813,6 @@ 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. @@ -735,7 +840,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -745,7 +850,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the \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 +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 @@ -753,22 +858,22 @@ versions. 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] +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. +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]I\f[R] @@ -784,7 +889,7 @@ Pushes the current value of \f[B]scale\f[R] onto the main stack. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]T\f[R] @@ -792,7 +897,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -800,7 +905,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -808,18 +913,17 @@ 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]. +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. +\f[B]\[cq]\f[R] pseudo\-random number generator command. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 @@ -857,16 +961,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -902,7 +1006,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -923,7 +1027,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -944,7 +1048,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -965,7 +1069,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -986,7 +1090,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -1007,7 +1111,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -1020,7 +1124,7 @@ 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 +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. @@ -1031,8 +1135,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -1057,6 +1164,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -1072,10 +1197,9 @@ 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]. +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] @@ -1092,10 +1216,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -1107,12 +1230,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -1122,45 +1250,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -1180,7 +1308,6 @@ 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] @@ -1210,29 +1337,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]DC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1240,27 +1367,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1278,14 +1405,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1302,13 +1429,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1317,11 +1444,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1330,18 +1457,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS +.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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). .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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1355,10 +1510,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -1393,7 +1548,7 @@ 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. +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) @@ -1404,17 +1559,17 @@ 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. +\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. +\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. +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. +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 @@ -1423,7 +1578,6 @@ 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 @@ -1431,45 +1585,42 @@ 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 +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. +\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. +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. +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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], +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. +\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. +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. +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] @@ -1478,7 +1629,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1501,19 +1652,17 @@ the user to continue. \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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/HN.1.md b/contrib/bc/manuals/dc/HN.1.md index 70c96262483..28b9dadd4b4 100644 --- a/contrib/bc/manuals/dc/HN.1.md +++ b/contrib/bc/manuals/dc/HN.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # DESCRIPTION @@ -55,13 +55,96 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* -: Print the version information (copyright header) and exit. +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +160,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +199,30 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. -**-x** **-\-extended-register** +**-S** *scale*, **-\-scale**=*scale* -: Enables extended register mode. See the *Extended Register Mode* subsection - of the **REGISTERS** section for more information. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +232,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -266,15 +335,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -902,6 +996,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -924,6 +1020,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -973,6 +1083,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -1014,11 +1130,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -1112,7 +1231,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1190,6 +1310,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1286,8 +1432,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Prompt @@ -1342,15 +1488,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/dc/N.1 b/contrib/bc/manuals/dc/N.1 index c5cc36ac9b1..6e2baa587b1 100644 --- a/contrib/bc/manuals/dc/N.1 +++ b/contrib/bc/manuals/dc/N.1 @@ -1,7 +1,7 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" -.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors. +.\" Copyright (c) 2018-2024 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: @@ -25,69 +25,188 @@ .\" 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" +.TH "DC" "1" "August 2024" "Gavin D. Howard" "General Commands Manual" +.nh +.ad l .SH Name -.PP -dc - arbitrary-precision decimal reverse-Polish notation calculator +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[B]dc\f[R] [\f[B]\-cChiPRvVx\f[R]] [\f[B]\-\-version\f[R]] +[\f[B]\-\-help\f[R]] [\f[B]\-\-digit\-clamp\f[R]] +[\f[B]\-\-no\-digit\-clamp\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]\&...] +[\f[B]\-I\f[R] \f[I]ibase\f[R]] [\f[B]\-\-ibase\f[R]=\f[I]ibase\f[R]] +[\f[B]\-O\f[R] \f[I]obase\f[R]] [\f[B]\-\-obase\f[R]=\f[I]obase\f[R]] +[\f[B]\-S\f[R] \f[I]scale\f[R]] [\f[B]\-\-scale\f[R]=\f[I]scale\f[R]] +[\f[B]\-E\f[R] \f[I]seed\f[R]] [\f[B]\-\-seed\f[R]=\f[I]seed\f[R]] .SH DESCRIPTION -.PP -dc(1) is an arbitrary-precision calculator. +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 +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], +\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. +\f[B]\-C\f[R], \f[B]\-\-no\-digit\-clamp\f[R] +Disables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that the value added to a number from a digit is always that +digit\[cq]s value multiplied by the value of ibase raised to the power +of the digit\[cq]s position, which starts from 0 at the least +significant digit. +.PP +If this and/or the \f[B]\-c\f[R] or \f[B]\-\-digit\-clamp\f[R] options +are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-c\f[R], \f[B]\-\-digit\-clamp\f[R] +Enables clamping of digits greater than or equal to the current +\f[B]ibase\f[R] when parsing numbers. +.RS +.PP +This means that digits that the value added to a number from a digit +that is greater than or equal to the ibase is the value of ibase minus 1 +all multiplied by the value of ibase raised to the power of the +digit\[cq]s position, which starts from 0 at the least significant +digit. +.PP +If this and/or the \f[B]\-C\f[R] or \f[B]\-\-no\-digit\-clamp\f[R] +options are given multiple times, the last one given is used. +.PP +This option overrides the \f[B]DC_DIGIT_CLAMP\f[R] environment variable +(see the \f[B]ENVIRONMENT VARIABLES\f[R] section) and the default, which +can be queried with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-E\f[R] \f[I]seed\f[R], \f[B]\-\-seed\f[R]=\f[I]seed\f[R] +Sets the builtin variable \f[B]seed\f[R] to the value \f[I]seed\f[R] +assuming that \f[I]seed\f[R] is in base 10. +It is a fatal error if \f[I]seed\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.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 +.TP +\f[B]\-h\f[R], \f[B]\-\-help\f[R] +Prints a usage message and exits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] -Print the version information (copyright header) and exit. +\f[B]\-I\f[R] \f[I]ibase\f[R], \f[B]\-\-ibase\f[R]=\f[I]ibase\f[R] +Sets the builtin variable \f[B]ibase\f[R] to the value \f[I]ibase\f[R] +assuming that \f[I]ibase\f[R] is in base 10. +It is a fatal error if \f[I]ibase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE .TP -\f[B]-i\f[R], \f[B]--interactive\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-L\f[R], \f[B]--no-line-length\f[R] +\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]. +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]\-O\f[R] \f[I]obase\f[R], \f[B]\-\-obase\f[R]=\f[I]obase\f[R] +Sets the builtin variable \f[B]obase\f[R] to the value \f[I]obase\f[R] +assuming that \f[I]obase\f[R] is in base 10. +It is a fatal error if \f[I]obase\f[R] is not a valid number. +.RS +.PP +If multiple instances of this option are given, the last is used. +.PP +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]--no-prompt\f[R] +\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). +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 @@ -95,14 +214,15 @@ Most of those users would want to put this option in 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP -\f[B]-R\f[R], \f[B]--no-read-prompt\f[R] +\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). +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 @@ -116,79 +236,45 @@ 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]. +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. +\f[B]\-S\f[R] \f[I]scale\f[R], \f[B]\-\-scale\f[R]=\f[I]scale\f[R] +Sets the builtin variable \f[B]scale\f[R] to the value \f[I]scale\f[R] +assuming that \f[I]scale\f[R] is in base 10. +It is a fatal error if \f[I]scale\f[R] is not a valid number. .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). +If multiple instances of this option are given, the last is used. .PP -This is a \f[B]non-portable extension\f[R]. +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. +\f[B]\-v\f[R], \f[B]\-V\f[R], \f[B]\-\-version\f[R] +Print the version information (copyright header) and exits. +.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 -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]. +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. +\f[B]\-z\f[R], \f[B]\-\-leading\-zeroes\f[R] +Makes dc(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 -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]. +This is a \f[B]non\-portable extension\f[R]. .RE .PP -All long options are \f[B]non-portable extensions\f[R]. +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]. +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) reads from \f[B]stdin\f[R]. .PP However, there is a caveat to this. .PP @@ -198,8 +284,7 @@ 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]. +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]. @@ -207,7 +292,7 @@ to \f[B]stdout\f[R]. \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. +\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 @@ -215,13 +300,12 @@ 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. +\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 @@ -229,7 +313,6 @@ 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. @@ -258,8 +341,8 @@ 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]. +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] @@ -271,14 +354,14 @@ 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. +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. +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. +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. @@ -288,39 +371,68 @@ 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 +\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. +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 +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. +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]. +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]. +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 +Uppercase letters are equal to \f[B]9\f[R] plus 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]. +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[R] (i.e., they are greater than or equal to the current +value of \f[B]ibase\f[R]), then the behavior depends on the existence of +the \f[B]\-c\f[R]/\f[B]\-\-digit\-clamp\f[R] or +\f[B]\-C\f[R]/\f[B]\-\-no\-digit\-clamp\f[R] options (see the +\f[B]OPTIONS\f[R] section), the existence and setting of the +\f[B]DC_DIGIT_CLAMP\f[R] environment variable (see the \f[B]ENVIRONMENT +VARIABLES\f[R] section), or the default, which can be queried with the +\f[B]\-h\f[R]/\f[B]\-\-help\f[R] option. +.PP +If clamping is off, then digits or letters that are greater than or +equal to the current value of \f[B]ibase\f[R] are not changed. +Instead, their given value is multiplied by the appropriate power of +\f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is +\f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R]. +.PP +If clamping is on, then digits or letters that are greater than or equal +to the current value of \f[B]ibase\f[R] are set to the value of the +highest valid digit in \f[B]ibase\f[R] before being multiplied by the +appropriate power of \f[B]ibase\f[R] and added into the number. +This means that, with an \f[B]ibase\f[R] of \f[B]3\f[R], the number +\f[B]AB\f[R] is equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is +\f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. +.PP +There is one exception to clamping: single\-character numbers (i.e., +\f[B]A\f[R] alone). +Such numbers are never clamped and always take the value they would have +in the highest possible \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]. +\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. +This behavior is mandated by the standard for bc(1) (see the STANDARDS +section) and is meant to provide an easy way to set the current +\f[B]ibase\f[R] (with the \f[B]i\f[R] command) regardless of the current +value of \f[B]ibase\f[R]. +.PP +If clamping is on, and the clamped value of a character is needed, use a +leading zero, i.e., for \f[B]A\f[R], use \f[B]0A\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. @@ -339,13 +451,11 @@ 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 +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 @@ -357,7 +467,7 @@ activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using 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]. +\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 @@ -377,12 +487,12 @@ Pops a value off the stack. .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 +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]f\f[R] @@ -393,7 +503,6 @@ without altering anything. 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] @@ -402,7 +511,7 @@ 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] +\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 @@ -423,7 +532,7 @@ 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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]%\f[R] @@ -433,10 +542,10 @@ is pushed onto the stack. .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]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. +The first value popped off of the stack must be non\-zero. .RE .TP \f[B]\[ti]\f[R] @@ -447,9 +556,9 @@ 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. +The first value popped off of the stack must be non\-zero. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] @@ -460,7 +569,7 @@ The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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. +non\-zero. .RE .TP \f[B]v\f[R] @@ -469,7 +578,7 @@ 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. +The value popped off of the stack must be non\-negative. .RE .TP \f[B]_\f[R] @@ -479,7 +588,7 @@ or other commands), then that number is input as a negative number. .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]. +This behavior without a number is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]b\f[R] @@ -488,7 +597,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]|\f[R] @@ -497,12 +606,12 @@ 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. +integer and non\-zero. The second value popped is used as the exponent and must be an integer -and non-negative. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]$\f[R] @@ -510,7 +619,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] @@ -520,9 +629,9 @@ extension. .RS .PP The first value popped off of the stack must be an integer and -non-negative. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]H\f[R] @@ -531,9 +640,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]h\f[R] @@ -542,9 +651,9 @@ 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. +non\-negative. .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]G\f[R] @@ -552,7 +661,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]N\f[R] @@ -560,7 +669,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B](\f[R] @@ -569,7 +678,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]{\f[R] @@ -578,7 +687,7 @@ The top two values are popped off of the stack, they are compared, and a or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B])\f[R] @@ -587,7 +696,7 @@ The top two values are popped off of the stack, they are compared, and a \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]}\f[R] @@ -596,42 +705,41 @@ The top two values are popped off of the stack, they are compared, and a second, or \f[B]0\f[R] otherwise. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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. +a short\-circuit operator. .PP -This is a \f[B]non-portable extension\f[R]. +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. +.SS 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 \f[B]seed\f[R] value that -controls the pseudo-random number generator.) +controls the pseudo\-random number generator.) .PP -The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] @@ -640,19 +748,19 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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 +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 +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 @@ -664,12 +772,11 @@ 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. +limitations of the pseudo\-random number generator. .PP -This is a \f[B]non-portable extension\f[R]. +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] @@ -685,7 +792,6 @@ Swaps (\[lq]reverses\[rq]) the two top items on the stack. \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] @@ -707,7 +813,6 @@ 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. @@ -735,7 +840,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the .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. +\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 @@ -745,7 +850,7 @@ If the value on top of the stack has any \f[I]scale\f[R], the \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 +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 @@ -753,22 +858,22 @@ versions. 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] +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. +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]I\f[R] @@ -784,7 +889,7 @@ Pushes the current value of \f[B]scale\f[R] onto the main stack. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]T\f[R] @@ -792,7 +897,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]U\f[R] @@ -800,7 +905,7 @@ 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]V\f[R] @@ -808,18 +913,17 @@ 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]. +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. +\f[B]\[cq]\f[R] pseudo\-random number generator command. .RS .PP -This is a \f[B]non-portable extension\f[R]. +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 @@ -857,16 +961,16 @@ 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 \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 +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. +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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]x\f[R] @@ -902,7 +1006,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[R] @@ -923,7 +1027,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[R] @@ -944,7 +1048,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[R] @@ -965,7 +1069,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[R] @@ -986,7 +1090,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[R] @@ -1007,7 +1111,7 @@ fails. 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]. +This is a \f[B]non\-portable extension\f[R]. .RE .TP \f[B]?\f[R] @@ -1020,7 +1124,7 @@ 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 +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. @@ -1031,8 +1135,11 @@ 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 +.RS .PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.SS Status These commands query status of the stack or its top value. .TP \f[B]Z\f[R] @@ -1057,6 +1164,24 @@ stack. If it is a string, pushes \f[B]0\f[R]. .RE .TP +\f[B]u\f[R] +Pops one value off of the stack. +If the value is a number, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a string), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP +\f[B]t\f[R] +Pops one value off of the stack. +If the value is a string, this pushes \f[B]1\f[R] onto the stack. +Otherwise (if it is a number), it pushes \f[B]0\f[R]. +.RS +.PP +This is a \f[B]non\-portable extension\f[R]. +.RE +.TP \f[B]z\f[R] Pushes the current depth of the stack (before execution of this command) onto the stack. @@ -1072,10 +1197,9 @@ 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]. +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] @@ -1092,10 +1216,9 @@ The selected value is then pushed onto the stack. 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]. +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]. @@ -1107,12 +1230,17 @@ section). 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]gx\f[R] +Pushes \f[B]1\f[R] onto the stack if extended register mode is on, +\f[B]0\f[R] otherwise. +See the \f[I]Extended Register Mode\f[R] subsection of the +\f[B]REGISTERS\f[R] section for more information. +.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. +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 @@ -1122,45 +1250,45 @@ 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 +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 +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. +\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 +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. +execution 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 +However, the stack of values is \f[I]not\f[R] cleared; in interactive +mode, users can inspect the stack and manipulate it. +.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. @@ -1180,7 +1308,6 @@ 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] @@ -1210,29 +1337,29 @@ 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]. +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]. +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]. +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]. +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]. +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]. +Set at \f[B]2\[ha]DC_LONG_BIT\-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). @@ -1240,27 +1367,27 @@ 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]. +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. +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: +As \f[B]non\-portable extensions\f[R], 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. +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. +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 +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 @@ -1278,14 +1405,14 @@ you can use double quotes as the outside quotes, as in \f[B]\[lq]some 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. +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, +(\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 @@ -1302,13 +1429,13 @@ 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) +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_TTY_MODE\f[R] @@ -1317,11 +1444,11 @@ 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 +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. +with the \f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE .TP \f[B]DC_PROMPT\f[R] @@ -1330,18 +1457,46 @@ 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. +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. +\f[B]\-h\f[R] or \f[B]\-\-help\f[R] options. .RE -.SH EXIT STATUS +.TP +\f[B]DC_EXPR_EXIT\f[R] +If any expressions or expression files are given on the command\-line +with \f[B]\-e\f[R], \f[B]\-\-expression\f[R], \f[B]\-f\f[R], or +\f[B]\-\-file\f[R], then if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) exit after executing +the expressions and expression files, and a zero value makes dc(1) not +exit. +.RS .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_DIGIT_CLAMP\f[R] +When parsing numbers and if this environment variable exists and +contains an integer, a non\-zero value makes dc(1) clamp digits that are +greater than or equal to the current \f[B]ibase\f[R] so that all such +digits are considered equal to the \f[B]ibase\f[R] minus 1, and a zero +value disables such clamping so that those digits are always equal to +their value, which is multiplied by the power of the \f[B]ibase\f[R]. +.RS +.PP +This never applies to single\-digit numbers, as per the bc(1) standard +(see the \f[B]STANDARDS\f[R] section). +.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 +.SH EXIT STATUS dc(1) returns the following exit statuses: .TP \f[B]0\f[R] @@ -1355,10 +1510,10 @@ since math errors will happen in the process of normal execution. .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 +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. +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 @@ -1393,7 +1548,7 @@ 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. +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) @@ -1404,17 +1559,17 @@ 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. +\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. +\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. +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. +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 @@ -1423,7 +1578,6 @@ 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 @@ -1431,53 +1585,49 @@ 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 +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. +\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. +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 +required in the bc(1) specification (see the \f[B]STANDARDS\f[R] +section), 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 +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], +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. +\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. +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. +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] @@ -1486,7 +1636,7 @@ section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the 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, +\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 @@ -1512,12 +1662,11 @@ 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. +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 +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 @@ -1527,19 +1676,17 @@ 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. +The dc(1) utility operators and some behavior are compliant with the +operators in the IEEE Std 1003.1\-2017 (\[lq]POSIX.1\-2017\[rq]) bc(1) +specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . .SH BUGS -.PP None are known. -Report bugs at https://git.yzena.com/gavin/bc. +Report bugs at https://git.gavinhoward.com/gavin/bc . .SH AUTHOR -.PP -Gavin D. -Howard and contributors. +Gavin D. Howard \c +.MT gavin@gavinhoward.com +.ME \c +\ and contributors. diff --git a/contrib/bc/manuals/dc/N.1.md b/contrib/bc/manuals/dc/N.1.md index fea23028e48..22ea9c96bc8 100644 --- a/contrib/bc/manuals/dc/N.1.md +++ b/contrib/bc/manuals/dc/N.1.md @@ -2,7 +2,7 @@ SPDX-License-Identifier: BSD-2-Clause -Copyright (c) 2018-2021 Gavin D. Howard and contributors. +Copyright (c) 2018-2024 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: @@ -34,7 +34,7 @@ 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*...] +**dc** [**-cChiPRvVx**] [**-\-version**] [**-\-help**] [**-\-digit-clamp**] [**-\-no-digit-clamp**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...] [**-I** *ibase*] [**-\-ibase**=*ibase*] [**-O** *obase*] [**-\-obase**=*obase*] [**-S** *scale*] [**-\-scale**=*scale*] [**-E** *seed*] [**-\-seed**=*seed*] # DESCRIPTION @@ -55,13 +55,96 @@ this dc(1) will always start with a **scale** of **10**. The following are the options that dc(1) accepts. +**-C**, **-\-no-digit-clamp** + +: Disables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that the value added to a number from a digit is always that + digit's value multiplied by the value of ibase raised to the power of the + digit's position, which starts from 0 at the least significant digit. + + If this and/or the **-c** or **-\-digit-clamp** options are given multiple + times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-c**, **-\-digit-clamp** + +: Enables clamping of digits greater than or equal to the current **ibase** + when parsing numbers. + + This means that digits that the value added to a number from a digit that is + greater than or equal to the ibase is the value of ibase minus 1 all + multiplied by the value of ibase raised to the power of the digit's + position, which starts from 0 at the least significant digit. + + If this and/or the **-C** or **-\-no-digit-clamp** options are given + multiple times, the last one given is used. + + This option overrides the **DC_DIGIT_CLAMP** environment variable (see the + **ENVIRONMENT VARIABLES** section) and the default, which can be queried + with the **-h** or **-\-help** options. + + This is a **non-portable extension**. + +**-E** *seed*, **-\-seed**=*seed* + +: Sets the builtin variable **seed** to the value *seed* assuming that *seed* + is in base 10. It is a fatal error if *seed* is not a valid number. + + If multiple instances of this option are given, the last is used. + + 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**. + **-h**, **-\-help** -: Prints a usage message and quits. +: Prints a usage message and exits. -**-v**, **-V**, **-\-version** +**-I** *ibase*, **-\-ibase**=*ibase* -: Print the version information (copyright header) and exit. +: Sets the builtin variable **ibase** to the value *ibase* assuming that + *ibase* is in base 10. It is a fatal error if *ibase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. **-i**, **-\-interactive** @@ -77,6 +160,15 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. +**-O** *obase*, **-\-obase**=*obase* + +: Sets the builtin variable **obase** to the value *obase* assuming that + *obase* is in base 10. It is a fatal error if *obase* is not a valid number. + + If multiple instances of this option are given, the last is used. + + This is a **non-portable extension**. + **-P**, **-\-no-prompt** : Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. @@ -107,53 +199,30 @@ The following are the options that dc(1) accepts. This is a **non-portable extension**. -**-x** **-\-extended-register** +**-S** *scale*, **-\-scale**=*scale* -: Enables extended register mode. See the *Extended Register Mode* subsection - of the **REGISTERS** section for more information. +: Sets the builtin variable **scale** to the value *scale* assuming that + *scale* is in base 10. It is a fatal error if *scale* is not a valid number. - 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). + If multiple instances of this option are given, the last is used. This is a **non-portable extension**. -**-e** *expr*, **-\-expression**=*expr* +**-v**, **-V**, **-\-version** -: 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. +: Print the version information (copyright header) and exits. - 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. +**-x** **-\-extended-register** - This is a **non-portable extension**. +: Enables extended register mode. See the *Extended Register Mode* subsection + of the **REGISTERS** section for more information. -**-f** *file*, **-\-file**=*file* + This is a **non-portable extension**. -: 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. +**-z**, **-\-leading-zeroes** - 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. +: Makes dc(1) print all numbers greater than **-1** and less than **1**, and + not equal to **0**, with a leading zero. This is a **non-portable extension**. @@ -163,7 +232,7 @@ All long options are **non-portable extensions**. 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**. +reads from **stdin**. However, there is a caveat to this. @@ -266,15 +335,40 @@ Comments go from **#** until, and not including, the next newline. This is a 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**. +Uppercase letters are equal to **9** plus 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** (i.e., +they are greater than or equal to the current value of **ibase**), then the +behavior depends on the existence of the **-c**/**-\-digit-clamp** or +**-C**/**-\-no-digit-clamp** options (see the **OPTIONS** section), the +existence and setting of the **DC_DIGIT_CLAMP** environment variable (see the +**ENVIRONMENT VARIABLES** section), or the default, which can be queried with +the **-h**/**-\-help** option. + +If clamping is off, then digits or letters that are greater than or equal to the +current value of **ibase** are not changed. Instead, their given value is +multiplied by the appropriate power of **ibase** and added into the number. This +means that, with an **ibase** of **3**, the number **AB** is equal to +**3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**. + +If clamping is on, then digits or letters that are greater than or equal to the +current value of **ibase** are set to the value of the highest valid digit in +**ibase** before being multiplied by the appropriate power of **ibase** and +added into the number. This means that, with an **ibase** of **3**, the number +**AB** is equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, +or **8**. + +There is one exception to clamping: single-character numbers (i.e., **A** +alone). Such numbers are never clamped and always take the value they would have +in the highest possible **ibase**. This means that **A** alone always equals +decimal **10** and **Z** alone always equals decimal **35**. This behavior is +mandated by the standard for bc(1) (see the STANDARDS section) and is meant to +provide an easy way to set the current **ibase** (with the **i** command) +regardless of the current value of **ibase**. + +If clamping is on, and the clamped value of a character is needed, use a leading +zero, i.e., for **A**, use **0A**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The exponent (the portion after the **e**) must be @@ -902,6 +996,8 @@ will be printed with a newline after and then popped from 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. + This is a **non-portable extension**. + ## Status These commands query status of the stack or its top value. @@ -924,6 +1020,20 @@ These commands query status of the stack or its top value. If it is a string, pushes **0**. +**u** + +: Pops one value off of the stack. If the value is a number, this pushes **1** + onto the stack. Otherwise (if it is a string), it pushes **0**. + + This is a **non-portable extension**. + +**t** + +: Pops one value off of the stack. If the value is a string, this pushes **1** + onto the stack. Otherwise (if it is a number), it pushes **0**. + + This is a **non-portable extension**. + **z** : Pushes the current depth of the stack (before execution of this command) @@ -973,6 +1083,12 @@ other character produces a parse error (see the **ERRORS** section). : Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT VARIABLES** section) onto the stack. +**gx** + +: Pushes **1** onto the stack if extended register mode is on, **0** + otherwise. See the *Extended Register Mode* subsection of the **REGISTERS** + section for more information. + **gz** : Pushes **0** onto the stack if the leading zero setting has not been enabled @@ -1014,11 +1130,14 @@ the next non-space characters do not match that regex. 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 +First, any macros that are executing are stopped and popped off the execution +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. +However, the stack of values is *not* cleared; in interactive mode, users can +inspect the stack and manipulate it. + 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 @@ -1112,7 +1231,8 @@ be hit. # ENVIRONMENT VARIABLES -dc(1) recognizes the following environment variables: +As **non-portable extensions**, dc(1) recognizes the following environment +variables: **DC_ENV_ARGS** @@ -1190,6 +1310,32 @@ dc(1) recognizes the following environment variables: override the default, which can be queried with the **-h** or **-\-help** options. +**DC_EXPR_EXIT** + +: If any expressions or expression files are given on the command-line with + **-e**, **-\-expression**, **-f**, or **-\-file**, then if this environment + variable exists and contains an integer, a non-zero value makes dc(1) exit + after executing the expressions and expression files, and a zero value makes + dc(1) not exit. + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + +**DC_DIGIT_CLAMP** + +: When parsing numbers and if this environment variable exists and contains an + integer, a non-zero value makes dc(1) clamp digits that are greater than or + equal to the current **ibase** so that all such digits are considered equal + to the **ibase** minus 1, and a zero value disables such clamping so that + those digits are always equal to their value, which is multiplied by the + power of the **ibase**. + + This never applies to single-digit numbers, as per the bc(1) standard (see + the **STANDARDS** section). + + This environment variable overrides the default, which can be queried with + the **-h** or **-\-help** options. + # EXIT STATUS dc(1) returns the following exit statuses: @@ -1286,8 +1432,8 @@ 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. +in the bc(1) specification (see the **STANDARDS** section), and interactive mode +requires only **stdin** and **stdout** to be connected to a terminal. ## Command-Line History @@ -1365,15 +1511,14 @@ 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. +The dc(1) utility operators and some behavior are compliant with the operators +in the IEEE Std 1003.1-2017 (“POSIX.1-2017â€) bc(1) specification at +https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html . # BUGS -None are known. Report bugs at https://git.yzena.com/gavin/bc. +None are known. Report bugs at https://git.gavinhoward.com/gavin/bc . # AUTHOR -Gavin D. Howard and contributors. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +Gavin D. Howard and contributors. diff --git a/contrib/bc/scripts/exec-install.sh b/contrib/bc/scripts/exec-install.sh index 25d56c6fc68..581b6bd1ed2 100755 --- a/contrib/bc/scripts/exec-install.sh +++ b/contrib/bc/scripts/exec-install.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -29,7 +29,7 @@ # Print usage and exit with an error. usage() { - printf "usage: %s install_dir exec_suffix\n" "$0" 1>&2 + printf "usage: %s install_dir exec_suffix [bindir]\n" "$0" 1>&2 exit 1 } @@ -49,12 +49,23 @@ shift exec_suffix="$1" shift -bindir="$scriptdir/../bin" +if [ "$#" -gt 0 ]; then + bindir="$1" + shift +else + bindir="$scriptdir/../bin" +fi # Install or symlink, depending on the type of file. If it's a file, install it. # If it's a symlink, create an equivalent in the install directory. for exe in $bindir/*; do + # Skip any directories in case the bin/ directory is also used as the + # prefix. + if [ -d "$exe" ]; then + continue + fi + base=$(basename "$exe") if [ -L "$exe" ]; then diff --git a/contrib/bc/scripts/format.sh b/contrib/bc/scripts/format.sh new file mode 100755 index 00000000000..f76aed37818 --- /dev/null +++ b/contrib/bc/scripts/format.sh @@ -0,0 +1,53 @@ +#! /bin/sh +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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. +# + +scriptdir=$(dirname "$0") + +. "$scriptdir/functions.sh" + +cd "$scriptdir/.." + +if [ "$#" -gt 0 ]; then + files="$@" +else + files=$(find "." -name "*.c" -or -name "*.h") +fi + +for f in $files; do + + case "$f" in + *scripts/ministat.c) continue ;; + esac + + clang-format -i --style=file "$f" + sed -i 's|^#else //|#else //|g' "$f" + +done + +sed -i 's|^ // clang-format on| // clang-format on|g' src/program.c diff --git a/contrib/bc/scripts/functions.sh b/contrib/bc/scripts/functions.sh index 65ec0a1167f..1599fea4847 100755 --- a/contrib/bc/scripts/functions.sh +++ b/contrib/bc/scripts/functions.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -71,6 +71,88 @@ err_exit() { exit "$2" } +# Function for checking the "d"/"dir" argument of scripts. This function expects +# a usage() function to exist in the caller. +# @param 1 The argument to check. +check_d_arg() { + + if [ "$#" -ne 1 ]; then + printf 'Invalid number of args to check_d_arg\n' + exit 1 + fi + + _check_d_arg_arg="$1" + shift + + if [ "$_check_d_arg_arg" != "bc" ] && [ "$_check_d_arg_arg" != "dc" ]; then + _check_d_arg_msg=$(printf 'Invalid d arg: %s\nMust be either "bc" or "dc".\n\n' \ + "$_check_d_arg_arg") + usage "$_check_d_arg_msg" + fi +} + +# Function for checking the boolean arguments of scripts. This function expects +# a usage() function to exist in the caller. +# @param 1 The argument to check. +check_bool_arg() { + + if [ "$#" -ne 1 ]; then + printf 'Invalid number of args to check_bool_arg\n' + exit 1 + fi + + _check_bool_arg_arg="$1" + shift + + if [ "$_check_bool_arg_arg" != "0" ] && [ "$_check_bool_arg_arg" != "1" ]; then + _check_bool_arg_msg=$(printf 'Invalid bool arg: %s\nMust be either "0" or "1".\n\n' \ + "$_check_bool_arg_arg") + usage "$_check_bool_arg_msg" + fi +} + +# Function for checking the executable arguments of scripts. This function +# expects a usage() function to exist in the caller. +# @param 1 The argument to check. +check_exec_arg() { + + if [ "$#" -ne 1 ]; then + printf 'Invalid number of args to check_exec_arg\n' + exit 1 + fi + + _check_exec_arg_arg="$1" + shift + + if [ ! -x "$_check_exec_arg_arg" ]; then + if ! command -v "$_check_exec_arg_arg" >/dev/null 2>&1; then + _check_exec_arg_msg=$(printf 'Invalid exec arg: %s\nMust be an executable file.\n\n' \ + "$_check_exec_arg_arg") + usage "$_check_exec_arg_msg" + fi + fi +} + +# Function for checking the file arguments of scripts. This function expects a +# usage() function to exist in the caller. +# @param 1 The argument to check. +check_file_arg() { + + if [ "$#" -ne 1 ]; then + printf 'Invalid number of args to check_file_arg\n' + exit 1 + fi + + _check_file_arg_arg="$1" + shift + + if [ ! -f "$_check_file_arg_arg" ]; then + _check_file_arg_msg=$(printf 'Invalid file arg: %s\nMust be a file.\n\n' \ + "$_check_file_arg_arg") + usage "$_check_file_arg_msg" + fi +} + # 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. @@ -326,3 +408,94 @@ gen_nlspath() { # Return the result. printf '%s' "$_gen_nlspath_nlspath" } + +ALL=0 +NOSKIP=1 +SKIP=2 + +# Filters text out of a file according to the build type. +# @param in File to filter. +# @param out File to write the filtered output to. +# @param type Build type. +filter_text() { + + _filter_text_in="$1" + shift + + _filter_text_out="$1" + shift + + _filter_text_buildtype="$1" + shift + + # Set up some local variables. + _filter_text_status="$ALL" + _filter_text_last_line="" + + # We need to set IFS, so we store it here for restoration later. + _filter_text_ifs="$IFS" + + # Remove the file- that will be generated. + rm -rf "$_filter_text_out" + + # Here is the magic. This loop reads the template line-by-line, and based on + # _filter_text_status, either prints it to the markdown manual or not. + # + # Here is how the template is set up: it is a normal markdown file except + # that there are sections surrounded tags that look like this: + # + # {{ }} + # ... + # {{ end }} + # + # Those tags mean that whatever build types are found in the + # get to keep that section. Otherwise, skip. + # + # Obviously, the tag itself and its end are not printed to the markdown + # manual. + while IFS= read -r _filter_text_line; do + + # If we have found an end, reset the status. + if [ "$_filter_text_line" = "{{ end }}" ]; then + + # Some error checking. This helps when editing the templates. + if [ "$_filter_text_status" -eq "$ALL" ]; then + err_exit "{{ end }} tag without corresponding start tag" 2 + fi + + _filter_text_status="$ALL" + + # We have found a tag that allows our build type to use it. + elif [ "${_filter_text_line#\{\{* $_filter_text_buildtype *\}\}}" != "$_filter_text_line" ]; then + + # More error checking. We don't want tags nested. + if [ "$_filter_text_status" -ne "$ALL" ]; then + err_exit "start tag nested in start tag" 3 + fi + + _filter_text_status="$NOSKIP" + + # We have found a tag that is *not* allowed for our build type. + elif [ "${_filter_text_line#\{\{*\}\}}" != "$_filter_text_line" ]; then + + if [ "$_filter_text_status" -ne "$ALL" ]; then + err_exit "start tag nested in start tag" 3 + fi + + _filter_text_status="$SKIP" + + # This is for normal lines. If we are not skipping, print. + else + if [ "$_filter_text_status" -ne "$SKIP" ]; then + if [ "$_filter_text_line" != "$_filter_text_last_line" ]; then + printf '%s\n' "$_filter_text_line" >> "$_filter_text_out" + fi + _filter_text_last_line="$_filter_text_line" + fi + fi + + done < "$_filter_text_in" + + # Reset IFS. + IFS="$_filter_text_ifs" +} diff --git a/contrib/bc/scripts/karatsuba.py b/contrib/bc/scripts/karatsuba.py index b8505186b52..637887986ee 100755 --- a/contrib/bc/scripts/karatsuba.py +++ b/contrib/bc/scripts/karatsuba.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -49,9 +49,6 @@ def run(cmd, env=None): if testdir == "": testdir = os.getcwd() -# We want to be in the root directory. -os.chdir(testdir + "/..") - print("\nWARNING: This script is for distro and package maintainers.") print("It is for finding the optimal Karatsuba number.") print("Though it only needs to be run once per release/platform,") @@ -116,7 +113,7 @@ def run(cmd, env=None): except KeyError: flags["CFLAGS"] = "-flto" -p = run([ "./configure.sh", "-O3" ], flags) +p = run([ "{}/../configure.sh".format(testdir), "-O3" ], flags) if p.returncode != 0: print("configure.sh returned an error ({}); exiting...".format(p.returncode)) sys.exit(p.returncode) @@ -161,7 +158,7 @@ def run(cmd, env=None): # Configure and compile. print("\nCompiling...\n") - p = run([ "./configure.sh", "-O3", "-k{}".format(i) ], config_env) + p = run([ "{}/../configure.sh".format(testdir), "-O3", "-k{}".format(i) ], config_env) if p.returncode != 0: print("configure.sh returned an error ({}); exiting...".format(p.returncode)) diff --git a/contrib/bc/scripts/link.sh b/contrib/bc/scripts/link.sh index f1c403d50dd..772de27a08c 100755 --- a/contrib/bc/scripts/link.sh +++ b/contrib/bc/scripts/link.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -32,6 +32,11 @@ usage() { exit 1 } +script="$0" +scriptdir=$(dirname "$script") + +. "$scriptdir/functions.sh" + # Command-line processing. test "$#" -gt 1 || usage diff --git a/contrib/bc/scripts/lint.sh b/contrib/bc/scripts/lint.sh new file mode 100755 index 00000000000..14cdc5c3afc --- /dev/null +++ b/contrib/bc/scripts/lint.sh @@ -0,0 +1,66 @@ +#! /bin/sh +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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") + +. "$scriptdir/functions.sh" + +cd "$scriptdir/.." + +if [ "$#" -gt 0 ]; then + files="$@" +else + files=$(find "." -name "*.c" -or -name "*.h") +fi + +for f in $files; do + + case "$f" in + *scripts/ministat.c) continue ;; + esac + + contents=$(clang-tidy --use-color -p ../build "$f" -- -I./include \ + -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 -D_BSD_SOURCE \ + -D_GNU_SOURCE -D_DEFAULT_SOURCE 2>&1) + + err="$?" + + if [ ! -z "$contents" ] || [ "$err" -ne 0 ]; then + + printf '%s\n' "$f" + printf '%s\n' "$contents" + printf '\n' + + if [ "$err" -ne 0 ]; then + exit "$err" + fi + fi + +done diff --git a/contrib/bc/scripts/locale_install.sh b/contrib/bc/scripts/locale_install.sh index a67e6aa5297..e891bf57db8 100755 --- a/contrib/bc/scripts/locale_install.sh +++ b/contrib/bc/scripts/locale_install.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -28,6 +28,7 @@ # # Just print the usage and exit with an error. +# @param 1 A message to print. usage() { if [ $# -eq 1 ]; then printf '%s\n' "$1" @@ -183,13 +184,14 @@ all_locales=0 while getopts "l" opt; do case "$opt" in - l) all_locales=1 ; shift ;; + l) all_locales=1 ;; ?) usage "Invalid option: $opt" ;; esac done +shift $(($OPTIND - 1)) -test "$#" -ge 2 || usage +test "$#" -ge 2 || usage "Must have at least two arguments" nlspath="$1" shift @@ -240,11 +242,15 @@ for file in $locales_dir/*.msg; do continue fi + printf 'Installing %s...' "$locale" + # Generate the proper location for the cat file. loc=$(gen_nlspath "$destdir/$nlspath" "$locale" "$main_exec") gencatfile "$loc" "$file" + printf 'done\n' + done # Now that we have done the non-symlinks, it's time to do the symlinks. Think @@ -275,6 +281,8 @@ for file in $locales_dir/*.msg; do # Make sure to skip non-symlinks; they are already done. if [ -L "$file" ]; then + printf 'Linking %s...' "$locale" + # This song and dance is because we want to generate relative symlinks. # They take less space, but also, they are more resilient to being # moved. @@ -294,6 +302,8 @@ for file in $locales_dir/*.msg; do # Finally, symlink to the install of the generated cat file that # corresponds to the correct msg file. ln -fs "$rel" "$loc" + + printf 'done\n' fi done diff --git a/contrib/bc/scripts/locale_uninstall.sh b/contrib/bc/scripts/locale_uninstall.sh index 3e79e083b80..1bf292b801e 100755 --- a/contrib/bc/scripts/locale_uninstall.sh +++ b/contrib/bc/scripts/locale_uninstall.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: diff --git a/contrib/bc/scripts/os.c b/contrib/bc/scripts/os.c new file mode 100644 index 00000000000..212a61772cc --- /dev/null +++ b/contrib/bc/scripts/os.c @@ -0,0 +1,59 @@ +/* + * ***************************************************************************** + * + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2018-2024 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. + * + * ***************************************************************************** + * + * File for testing compilation on different platforms. + * + */ + +// This is used by configure.sh to test for OpenBSD. +#ifdef BC_TEST_OPENBSD +#ifdef __OpenBSD__ +#error On OpenBSD without _BSD_SOURCE +#endif // __OpenBSD__ +#endif // BC_TEST_OPENBSD + +// This is used by configure.sh to test for FreeBSD. +#ifdef BC_TEST_FREEBSD +#ifdef __FreeBSD__ +#error On FreeBSD with _POSIX_C_SOURCE +#endif // __FreeBSD__ +#endif // BC_TEST_FREEBSD + +// This is used by configure.sh to test for macOS. +#ifdef BC_TEST_APPLE +#ifdef __APPLE__ +#error On macOS without _DARWIN_C_SOURCE +#endif // __APPLE__ +#endif // BC_TEST_APPLE + +extern int test; + +int test; diff --git a/contrib/bc/scripts/safe-install.sh b/contrib/bc/scripts/safe-install.sh index 04108838668..5774a17e20d 100755 --- a/contrib/bc/scripts/safe-install.sh +++ b/contrib/bc/scripts/safe-install.sh @@ -41,7 +41,7 @@ set -e if test "$mkdirp" ; then umask 022 -case "$2" in +case "$dst" in */*) mkdir -p "${dst%/*}" ;; esac fi @@ -51,15 +51,15 @@ trap 'rm -f "$tmp"' EXIT INT QUIT TERM HUP umask 077 if test "$symlink" ; then -ln -s "$1" "$tmp" +ln -s "$src" "$tmp" else -cat < "$1" > "$tmp" +cat < "$src" > "$tmp" chmod "$mode" "$tmp" fi -mv -f "$tmp" "$2" -test -d "$2" && { -rm -f "$2/$tmp" +mv -f "$tmp" "$dst" +test -d "$dst" && { +rm -f "$dst/$tmp" printf "%s: %s is a directory\n" "$0" "$dst" 1>&2 exit 1 } diff --git a/contrib/bc/scripts/sqrt_frac_guess.bc b/contrib/bc/scripts/sqrt_frac_guess.bc new file mode 100644 index 00000000000..acbcb368d2d --- /dev/null +++ b/contrib/bc/scripts/sqrt_frac_guess.bc @@ -0,0 +1,126 @@ +#! /usr/bin/bc +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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. +# + +scale = 20 + +# Adjust this number to try ranges below different powers of 10. +shift = 4 + +# Adjust this to try extra digits. For example, a value of one means that one +# digit is checked (such as 0.09 through 0.01), a value of two means that two +# digits are checked (0.090 through 0.010), etc. +max = shift + 2 + +n = (9 >> shift) +inc = (1 >> max) +stop = (1 >> shift) + +# Uncomment this to test the high part of the ranges. +#n += (1 - (1 >> max + 5)) >> shift + +for (i = n; i >= stop; i -= inc) +{ + # This is the lower limit. + t1 = sqrt(1/(3*i)) + + # Start with the inverse. + t2 = (1/i) + + # And take half its length of course. + l = length(t2$)/2 + + temp = i + odd = 0 + + # We go by powers of 10 below, but there is a degenerate case: an exact + # power of 10, for which length() will return one digit more. So we check + # for that and fix it. + while (temp < 1) + { + temp <<= 1 + odd = !odd + } + + if (temp == 1) + { + odd = !odd + } + + print "i: ", i, "\n" + print "t2: ", t2, "\n" + #print "l: ", l, "\n" + print "odd: ", odd, "\n" + + if (odd) + { + # Limit between 6 and 7.5. + limit1 = 6.7 >> (l$ * 2 + 1) + + # Limit between 1.5 and 1.83-ish. + limit2 = 1.7 >> (l$ * 2 + 1) + print "limit1: ", limit1, "\n" + print "limit2: ", limit2, "\n" + + if (i >= limit1) + { + t2 = (t2 >> l$) + } + else if (i >= limit2) + { + t2 = (t2 >> l$) / 2 + } + else + { + t2 = (t2 >> l$) / 4 + } + } + else + { + # Limit between 2.4 and 3. + limit = 2.7 >> (l$ * 2) + print "limit: ", limit, "\n" + + if (i >= limit) + { + t2 = (t2 >> l$) * 2 + } + else + { + t2 = (t2 >> l$) + } + } + #t2 = 1 + t3 = sqrt(5/(3*i)) + good = (t1 < t2 && t2 < t3) + + print t1, " < ", t2, " < ", t3, ": ", good, "\n\n" + if (!good) sqrt(-1) +} + +halt diff --git a/contrib/bc/scripts/sqrt_int_guess.bc b/contrib/bc/scripts/sqrt_int_guess.bc new file mode 100644 index 00000000000..925b7af7e10 --- /dev/null +++ b/contrib/bc/scripts/sqrt_int_guess.bc @@ -0,0 +1,94 @@ +#! /usr/bin/bc -l +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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. +# + +# Adjust this number to try ranges above different powers of 10. +max = 0 + +n = (1 << max) + +# Uncomment this to test the high part of the ranges. +#n += (1 - (1 >> 10)) + +n + +# Loop from the start number to the next power of 10. +for (i = n; i < (n$ << 1); i += 1) +{ + # This is the lower limit. + t1 = sqrt(1/(3*i)) + + l = length(i$)/2 + + print "i: ", i, "\n" + #print "l: ", l, "\n" + + if (l$ != l) + { + # Limit between 2.4 and 3. + limit = 2.7 << (l$ * 2) + #print "limit: ", limit, "\n" + + if (i >= limit) + { + t2 = 1/(i >> (l$)) * 2 + } + else + { + t2 = 1/(i >> (l$)) + } + } + else + { + # Limit between 3.8-ish and 4.8 + limit = 4.3 << (l$ * 2 - 1) + #print "limit: ", limit, "\n" + + if (i >= limit) + { + t2 = 1/(i >> (l$ - 1)) * 8 + } + else + { + t2 = 1/(i >> (l$ - 1)) * 4 + } + } + + # This is the upper limit. + t3 = sqrt(5/(3*i)) + + # This is true when the guess is in between the limits. + good = (t1 < t2 && t2 < t3) + + print t1, " < ", t2, " < ", t3, ": ", good, "\n" + + # Error if we have a problem. + if (!good) sqrt(-1) +} + +halt diff --git a/contrib/bc/scripts/sqrt_random.bc b/contrib/bc/scripts/sqrt_random.bc new file mode 100644 index 00000000000..1f58c2e30c5 --- /dev/null +++ b/contrib/bc/scripts/sqrt_random.bc @@ -0,0 +1,129 @@ +#! /usr/bin/bc +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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. +# + +scale = 0 + +bits = rand() + +# This extracts a bit and takes it out of the original value. +# +# Here, I am getting a bit to say whether we should have a value that is less +# than 1. +bits = divmod(bits, 2, negpow[]) + +# Get a bit that will say whether the value should be an exact square. +bits = divmod(bits, 2, square[]) + +# See below. This is to help bias toward small numbers. +pow = 4 + +# I want to bias toward small numbers, so let's give a 50 percent chance to +# values below 16 or so. +bits = divmod(bits, 2, small[]) + +# Let's keep raising the power limit by 2^4 when the bit is zero. +while (!small[0]) +{ + pow += 4 + bits = divmod(bits, 2, small[]) +} + +limit = 2^pow + +# Okay, this is the starting number. +num = irand(limit) + 1 + +# Figure out if we should have (more) fractional digits. +bits = divmod(bits, 2, extra_digits[]) + +if (square[0]) +{ + # Okay, I lied. If we need a perfect square, square now. + num *= num + + # If we need extra digits, we need to multiply by an even power of 10. + if (extra_digits[0]) + { + extra = (irand(8) + 1) * 2 + } + else + { + extra = 0 + } + + # If we need a number less than 1, just take the inverse, which will still + # be a perfect square. + if (negpow[0]) + { + scale = length(num) + 5 + num = 1/num + scale = 0 + + num >>= extra + } + else + { + num <<= extra + } +} +else +{ + # Get this for later. + l = length(num) + + # If we need extra digits. + if (extra_digits[0]) + { + # Add up to 32 decimal places. + num += frand(irand(32) + 1) + } + + # If we need a value less than 1... + if (negpow[0]) + { + # Move right until the number is + num >>= l + } +} + +bits = divmod(bits, 2, zero_scale[]) + +# Do we want a zero scale? +if (zero_scale[0]) +{ + print "scale = 0\n" +} +else +{ + print "scale = 20\n" +} + +print "sqrt(", num, ")\n" + +halt diff --git a/contrib/bc/scripts/sqrt_random.sh b/contrib/bc/scripts/sqrt_random.sh new file mode 100755 index 00000000000..e107ef532f6 --- /dev/null +++ b/contrib/bc/scripts/sqrt_random.sh @@ -0,0 +1,77 @@ +#! /bin/sh +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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. +# + +scriptdir=$(dirname "$0") + +gnu=/usr/bin/bc +gdh=/usr/local/bin/bc + +if [ "$#" -lt 1 ]; then + printf 'err: must provide path to new bc\n' + exit 1 +fi + +new="$1" +shift + +unset BC_LINE_LENGTH && unset BC_ENV_ARGS + +gdh_fail_file="sqrt_fails.bc" +new_fail_file="new_sqrt_fails.bc" + +rm -rf "$gdh_fail_file" +rm -rf "$new_fail_file" + +while [ true ]; do + + tst=$("$gdh" -l "$scriptdir/sqrt_random.bc") + err=$? + + if [ "$err" -ne 0 ]; then + printf 'err: failed to create test\n' + exit 2 + fi + + good=$(printf '%s\n' "$tst" | "$gnu" -l) + + gdh_out=$(printf '%s\n' "$tst" | "$gdh" -l) + new_out=$(printf '%s\n' "$tst" | "$new" -l) + + gdh_good=$(printf '%s == %s\n' "$good" "$gdh_out" | "$gnu") + new_good=$(printf '%s == %s\n' "$good" "$new_out" | "$gnu") + + if [ "$gdh_good" -eq 0 ]; then + printf '%s\n' "$tst" >> "$gdh_fail_file" + fi + + if [ "$new_good" -eq 0 ]; then + printf '%s\n' "$tst" >> "$new_fail_file" + fi + +done diff --git a/contrib/bc/src/args.c b/contrib/bc/src/args.c index 6601cfb2eeb..6eba802d34a 100644 --- a/contrib/bc/src/args.c +++ b/contrib/bc/src/args.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -47,16 +47,25 @@ #include #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) { +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"); + + 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"); } /** @@ -64,13 +73,14 @@ static void bc_args_exprs(const char *str) { * @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; +static void +bc_args_file(const char* file) +{ + char* buf; BC_SIG_ASSERT_LOCKED; - vm.file = file; + vm->file = file; buf = bc_read_file(file); @@ -80,6 +90,31 @@ static void bc_args_file(const char *file) { free(buf); } +static BcBigDig +bc_args_builtin(const char* arg) +{ + bool strvalid; + BcNum n; + BcBigDig res; + + strvalid = bc_num_strValid(arg); + + if (BC_ERR(!strvalid)) + { + bc_verr(BC_ERR_FATAL_ARG, arg); + } + + bc_num_init(&n, 0); + + bc_num_parse(&n, arg, 10); + + res = bc_num_bigdig(&n); + + bc_num_free(&n); + + return res; +} + #if BC_ENABLED /** @@ -87,19 +122,22 @@ static void bc_args_file(const char *file) { * throws a fatal error. * @param keyword The keyword to redefine. */ -static void bc_args_redefine(const char *keyword) { - +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; + BC_SIG_ASSERT_LOCKED; - if (!strcmp(keyword, kw->name)) { + 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; + vm->redefined_kws[i] = true; return; } @@ -110,12 +148,17 @@ static void bc_args_redefine(const char *keyword) { #endif // BC_ENABLED -void bc_args(int argc, char *argv[], bool exit_exprs) { - +void +bc_args(int argc, const char* argv[], bool exit_exprs, BcBigDig* scale, + BcBigDig* ibase, BcBigDig* obase) +{ int c; size_t i; bool do_exit = false, version = false; BcOpt opts; +#if BC_ENABLE_EXTRA_MATH + const char* seed = NULL; +#endif // BC_ENABLE_EXTRA_MATH BC_SIG_ASSERT_LOCKED; @@ -123,19 +166,33 @@ void bc_args(int argc, char *argv[], bool exit_exprs) { // 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) { + while ((c = bc_opt_parse(&opts, bc_args_lopt)) != -1) + { + switch (c) + { + case 'c': + { + vm->flags |= BC_FLAG_DIGIT_CLAMP; + break; + } - switch (c) { + case 'C': + { + vm->flags &= ~BC_FLAG_DIGIT_CLAMP; + break; + } case 'e': { // Barf if not allowed. - if (vm.no_exprs) + 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); + vm->exit_exprs = (exit_exprs || vm->exit_exprs); break; } @@ -143,16 +200,18 @@ void bc_args(int argc, char *argv[], bool exit_exprs) { case 'f': { // Figure out if exiting on expressions is disabled. - if (!strcmp(opts.optarg, "-")) vm.no_exprs = true; - else { - + if (!strcmp(opts.optarg, "-")) vm->no_exprs = true; + else + { // Barf if not allowed. - if (vm.no_exprs) + if (vm->no_exprs) + { bc_verr(BC_ERR_FATAL_OPTION, "-f (--file)"); + } - // Add the expressions and set exit. + // Add the expressions and set exit. bc_args_file(opts.optarg); - vm.exit_exprs = (exit_exprs || vm.exit_exprs); + vm->exit_exprs = (exit_exprs || vm->exit_exprs); } break; @@ -160,60 +219,92 @@ void bc_args(int argc, char *argv[], bool exit_exprs) { case 'h': { - bc_vm_info(vm.help); + bc_vm_info(vm->help); do_exit = true; break; } case 'i': { - vm.flags |= BC_FLAG_I; + vm->flags |= BC_FLAG_I; + break; + } + + case 'I': + { + *ibase = bc_args_builtin(opts.optarg); break; } case 'z': { - vm.flags |= BC_FLAG_Z; + vm->flags |= BC_FLAG_Z; break; } case 'L': { - vm.line_len = 0; + vm->line_len = 0; + break; + } + + case 'O': + { + *obase = bc_args_builtin(opts.optarg); break; } case 'P': { - vm.flags &= ~(BC_FLAG_P); + vm->flags &= ~(BC_FLAG_P); break; } case 'R': { - vm.flags &= ~(BC_FLAG_R); + vm->flags &= ~(BC_FLAG_R); + break; + } + + case 'S': + { + *scale = bc_args_builtin(opts.optarg); + break; + } + +#if BC_ENABLE_EXTRA_MATH + case 'E': + { + if (BC_ERR(!bc_num_strValid(opts.optarg))) + { + bc_verr(BC_ERR_FATAL_ARG, opts.optarg); + } + + seed = opts.optarg; + break; } +#endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLED case 'g': { assert(BC_IS_BC); - vm.flags |= BC_FLAG_G; + vm->flags |= BC_FLAG_G; break; } case 'l': { assert(BC_IS_BC); - vm.flags |= BC_FLAG_L; + vm->flags |= BC_FLAG_L; break; } case 'q': { assert(BC_IS_BC); - vm.flags &= ~(BC_FLAG_Q); + vm->flags &= ~(BC_FLAG_Q); break; } @@ -226,14 +317,14 @@ void bc_args(int argc, char *argv[], bool exit_exprs) { case 's': { assert(BC_IS_BC); - vm.flags |= BC_FLAG_S; + vm->flags |= BC_FLAG_S; break; } case 'w': { assert(BC_IS_BC); - vm.flags |= BC_FLAG_W; + vm->flags |= BC_FLAG_W; break; } #endif // BC_ENABLED @@ -249,12 +340,12 @@ void bc_args(int argc, char *argv[], bool exit_exprs) { case 'x': { assert(BC_IS_DC); - vm.flags |= DC_FLAG_X; + vm->flags |= DC_FLAG_X; break; } #endif // DC_ENABLED -#ifndef NDEBUG +#if BC_DEBUG // We shouldn't get here because bc_opt_error()/bc_error() should // longjmp() out. case '?': @@ -262,27 +353,53 @@ void bc_args(int argc, char *argv[], bool exit_exprs) { default: { BC_UNREACHABLE +#if !BC_CLANG abort(); +#endif // !BC_CLANG } -#endif // NDEBUG +#endif // BC_DEBUG } } if (version) bc_vm_info(NULL); - if (do_exit) { - vm.status = (sig_atomic_t) BC_STATUS_QUIT; + 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); + if (BC_ARGS_SHOULD_BE_QUIET) 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); + 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); + { + bc_vec_push(&vm->files, argv + i); + } + +#if BC_ENABLE_EXTRA_MATH + if (seed != NULL) + { + BcNum n; + + bc_num_init(&n, strlen(seed)); + + BC_SIG_UNLOCK; + + bc_num_parse(&n, seed, BC_BASE); + + bc_program_assignSeed(&vm->prog, &n); + + BC_SIG_LOCK; + + bc_num_free(&n); + } +#endif // BC_ENABLE_EXTRA_MATH } diff --git a/contrib/bc/src/bc.c b/contrib/bc/src/bc.c index 4f35cc42b91..572e42b1a16 100644 --- a/contrib/bc/src/bc.c +++ b/contrib/bc/src/bc.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -45,19 +45,21 @@ * @param argc The number of arguments. * @param argv The arguments. */ -void bc_main(int argc, char *argv[]) { - +BcStatus +bc_main(int argc, const char* argv[]) +{ // All of these just set bc-specific items in BcVm. - vm.read_ret = BC_INST_RET; - vm.help = bc_help; - vm.sigmsg = bc_sig_msg; - vm.siglen = bc_sig_msg_len; + vm->read_ret = BC_INST_RET; + vm->help = bc_help; + vm->sigmsg = bc_sig_msg; + vm->siglen = bc_sig_msg_len; - vm.next = bc_lex_token; - vm.parse = bc_parse_parse; - vm.expr = bc_parse_expr; + vm->next = bc_lex_token; + vm->parse = bc_parse_parse; + vm->expr = bc_parse_expr; - bc_vm_boot(argc, argv); + return bc_vm_boot(argc, argv); } + #endif // BC_ENABLED diff --git a/contrib/bc/src/bc_fuzzer.c b/contrib/bc/src/bc_fuzzer.c new file mode 100644 index 00000000000..7d7b3292b72 --- /dev/null +++ b/contrib/bc/src/bc_fuzzer.c @@ -0,0 +1,112 @@ +/* + * ***************************************************************************** + * + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2018-2024 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 entry point for libFuzzer when fuzzing bc. + * + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +uint8_t* bc_fuzzer_data; + +/// A boolean about whether we should use -c (false) or -C (true). +static bool bc_C; + +int +LLVMFuzzerInitialize(int* argc, char*** argv) +{ + BC_UNUSED(argc); + + if (argv == NULL || *argv == NULL) + { + bc_C = false; + } + else + { + char* name; + + // Get the basename + name = strrchr((*argv)[0], BC_FILE_SEP); + name = name == NULL ? (*argv)[0] : name + 1; + + // Figure out which to use. + bc_C = (strcmp(name, "bc_fuzzer_C") == 0); + } + + return 0; +} + +int +LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) +{ + BcStatus s; + + // I've already tested empty input, so just ignore. + if (Size == 0 || Data[0] == '\0') return 0; + + // Clear the global. This is to ensure a clean start. + memset(vm, 0, sizeof(BcVm)); + + // Make sure to set the name. + vm->name = "bc"; + + BC_SIG_LOCK; + + // We *must* do this here. Otherwise, other code could not jump out all of + // the way. + bc_vec_init(&vm->jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); + + BC_SETJMP_LOCKED(vm, exit); + + // Create a string with the data. + bc_fuzzer_data = bc_vm_malloc(Size + 1); + memcpy(bc_fuzzer_data, Data, Size); + bc_fuzzer_data[Size] = '\0'; + + s = bc_main((int) (bc_fuzzer_args_len - 1), + bc_C ? bc_fuzzer_args_C : bc_fuzzer_args_c); + +exit: + + BC_SIG_MAYLOCK; + + free(bc_fuzzer_data); + + return s == BC_STATUS_SUCCESS || s == BC_STATUS_QUIT ? 0 : -1; +} diff --git a/contrib/bc/src/bc_lex.c b/contrib/bc/src/bc_lex.c index cdbdf24b17a..f83eaf73162 100644 --- a/contrib/bc/src/bc_lex.c +++ b/contrib/bc/src/bc_lex.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -46,26 +46,27 @@ * Lexes an identifier, which may be a keyword. * @param l The lexer. */ -static void bc_lex_identifier(BcLex *l) { - +static void +bc_lex_identifier(BcLex* l) +{ // We already passed the first character, so we need to be sure to include // it. - const char *buf = l->buf + l->i - 1; + const char* buf = l->buf + l->i - 1; size_t i; // This loop is simply checking for keywords. - for (i = 0; i < bc_lex_kws_len; ++i) { - - const BcLexKeyword *kw = bc_lex_kws + i; + for (i = 0; i < bc_lex_kws_len; ++i) + { + const BcLexKeyword* kw = bc_lex_kws + i; size_t n = BC_LEX_KW_LEN(kw); - if (!strncmp(buf, kw->name, n) && !isalnum(buf[n]) && buf[n] != '_') { - + if (!strncmp(buf, kw->name, n) && !isalnum(buf[n]) && buf[n] != '_') + { // If the keyword has been redefined, and redefinition is allowed // (it is not allowed for builtin libraries), break out of the loop // and use it as a name. This depends on the argument parser to // ensure that only non-POSIX keywords get redefined. - if (!vm.no_redefine && vm.redefined_kws[i]) break; + if (!vm->no_redefine && vm->redefined_kws[i]) break; l->t = BC_LEX_KW_AUTO + (BcLexType) i; @@ -87,7 +88,9 @@ static void bc_lex_identifier(BcLex *l) { // POSIX doesn't allow identifiers that are more than one character, so we // might have to warn or error here too. if (BC_ERR(l->str.len - 1 > 1)) + { bc_lex_verr(l, BC_ERR_POSIX_NAME_LEN, l->str.v); + } } /** @@ -95,35 +98,44 @@ static void bc_lex_identifier(BcLex *l) { * to be balanced. * @param l The lexer. */ -static void bc_lex_string(BcLex *l) { - +static void +bc_lex_string(BcLex* l) +{ // We need to keep track of newlines to increment them properly. size_t len, nlines, i; - const char *buf; + const char* buf; char c; bool got_more; l->t = BC_LEX_STR; - do { - + do + { nlines = 0; buf = l->buf; got_more = false; - assert(!vm.is_stdin || buf == vm.buffer.v); +#if !BC_ENABLE_OSSFUZZ + assert(vm->mode != BC_MODE_STDIN || buf == vm->buffer.v); +#endif // !BC_ENABLE_OSSFUZZ // Fortunately for us, bc doesn't escape quotes. Instead, the equivalent // is '\q', which makes this loop simpler. - for (i = l->i; (c = buf[i]) && c != '"'; ++i) nlines += (c == '\n'); + for (i = l->i; (c = buf[i]) && c != '"'; ++i) + { + nlines += (c == '\n'); + } - if (BC_ERR(c == '\0') && !vm.eof && l->is_stdin) + if (BC_ERR(c == '\0') && !vm->eof && l->mode != BC_MODE_FILE) + { got_more = bc_lex_readLine(l); - - } while (got_more && c != '"'); + } + } + while (got_more && c != '"'); // If the string did not end properly, barf. - if (c != '"') { + if (c != '"') + { l->i = i; bc_lex_err(l, BC_ERR_PARSE_STRING); } @@ -143,24 +155,30 @@ static void bc_lex_string(BcLex *l) { * @param with The token to assign if it is an assignment operator. * @param without The token to assign if it is not an assignment operator. */ -static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without) { - if (l->buf[l->i] == '=') { +static void +bc_lex_assign(BcLex* l, BcLexType with, BcLexType without) +{ + if (l->buf[l->i] == '=') + { l->i += 1; l->t = with; } else l->t = without; } -void bc_lex_token(BcLex *l) { - +void +bc_lex_token(BcLex* l) +{ // We increment here. This means that all lexing needs to take that into // account, such as when parsing an identifier. If we don't, the first // character of every identifier would be missing. char c = l->buf[l->i++], c2; - // This is the workhorse of the lexer. - switch (c) { + BC_SIG_ASSERT_LOCKED; + // This is the workhorse of the lexer. + switch (c) + { case '\0': case '\n': case '\t': @@ -180,7 +198,9 @@ void bc_lex_token(BcLex *l) { // POSIX doesn't allow boolean not. if (l->t == BC_LEX_OP_BOOL_NOT) + { bc_lex_verr(l, BC_ERR_POSIX_BOOL, "!"); + } break; } @@ -211,8 +231,8 @@ void bc_lex_token(BcLex *l) { // Either we have boolean and or an error. And boolean and is not // allowed by POSIX. - if (BC_NO_ERR(c2 == '&')) { - + if (BC_NO_ERR(c2 == '&')) + { bc_lex_verr(l, BC_ERR_POSIX_BOOL, "&&"); l->i += 1; @@ -253,7 +273,8 @@ void bc_lex_token(BcLex *l) { c2 = l->buf[l->i]; // Have to check for increment first. - if (c2 == '+') { + if (c2 == '+') + { l->i += 1; l->t = BC_LEX_OP_INC; } @@ -272,7 +293,8 @@ void bc_lex_token(BcLex *l) { c2 = l->buf[l->i]; // Have to check for decrement first. - if (c2 == '-') { + if (c2 == '-') + { l->i += 1; l->t = BC_LEX_OP_DEC; } @@ -286,7 +308,8 @@ void bc_lex_token(BcLex *l) { // If it's alone, it's an alias for last. if (BC_LEX_NUM_CHAR(c2, true, false)) bc_lex_number(l, c); - else { + else + { l->t = BC_LEX_KW_LAST; bc_lex_err(l, BC_ERR_POSIX_DOT); } @@ -297,7 +320,7 @@ void bc_lex_token(BcLex *l) { case '/': { c2 = l->buf[l->i]; - if (c2 =='*') bc_lex_comment(l); + if (c2 == '*') bc_lex_comment(l); else bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE); break; } @@ -359,7 +382,8 @@ void bc_lex_token(BcLex *l) { c2 = l->buf[l->i]; // Check for shift. - if (c2 == '<') { + if (c2 == '<') + { l->i += 1; bc_lex_assign(l, BC_LEX_OP_ASSIGN_LSHIFT, BC_LEX_OP_LSHIFT); break; @@ -381,7 +405,8 @@ void bc_lex_token(BcLex *l) { c2 = l->buf[l->i]; // Check for shift. - if (c2 == '>') { + if (c2 == '>') + { l->i += 1; bc_lex_assign(l, BC_LEX_OP_ASSIGN_RSHIFT, BC_LEX_OP_RSHIFT); break; @@ -401,7 +426,8 @@ void bc_lex_token(BcLex *l) { case '\\': { // In bc, a backslash+newline is whitespace. - if (BC_NO_ERR(l->buf[l->i] == '\n')) { + if (BC_NO_ERR(l->buf[l->i] == '\n')) + { l->i += 1; l->t = BC_LEX_WHITESPACE; } @@ -458,8 +484,8 @@ void bc_lex_token(BcLex *l) { c2 = l->buf[l->i]; // Once again, boolean or is not allowed by POSIX. - if (BC_NO_ERR(c2 == '|')) { - + if (BC_NO_ERR(c2 == '|')) + { bc_lex_verr(l, BC_ERR_POSIX_BOOL, "||"); l->i += 1; diff --git a/contrib/bc/src/bc_parse.c b/contrib/bc/src/bc_parse.c index c2fc2186a06..cf4398709e5 100644 --- a/contrib/bc/src/bc_parse.c +++ b/contrib/bc/src/bc_parse.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -55,23 +55,32 @@ // 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); +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. + * @return True if the instruction is a from a leaf expression. */ -static bool bc_parse_inst_isLeaf(BcInst t) { - return (t >= BC_INST_NUM && t <= BC_INST_MAXSCALE) || +static bool +bc_parse_inst_isLeaf(BcInst t) +{ + return (t >= BC_INST_NUM && t <= BC_INST_LEADING_ZERO) || #if BC_ENABLE_EXTRA_MATH - t == BC_INST_TRUNC || + t == BC_INST_TRUNC || #endif // BC_ENABLE_EXTRA_MATH - t <= BC_INST_DEC; + t <= BC_INST_DEC; } /** @@ -79,9 +88,11 @@ static bool bc_parse_inst_isLeaf(BcInst t) { * 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. + * @return True if the token is a legal delimiter. */ -static bool bc_parse_isDelimiter(const BcParse *p) { - +static bool +bc_parse_isDelimiter(const BcParse* p) +{ BcLexType t = p->l.t; bool good; @@ -93,33 +104,36 @@ static bool bc_parse_isDelimiter(const BcParse *p) { // 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) { - + 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) { - + 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) { - + 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); + 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); } } @@ -127,16 +141,35 @@ static bool bc_parse_isDelimiter(const BcParse *p) { return good; } +/** + * Returns true if we are in top level of a function body. The POSIX grammar + * is defined such that anything is allowed after a function body, so we must + * use this function to detect that case when ending a function body. + * @param p The parser. + * @return True if we are in the top level of parsing a function body. + */ +static bool +bc_parse_TopFunc(const BcParse* p) +{ + bool good = p->flags.len == 2; + + uint16_t val = BC_PARSE_FLAG_BRACE | BC_PARSE_FLAG_FUNC_INNER; + val |= BC_PARSE_FLAG_FUNC; + + return good && BC_PARSE_TOP_FLAG(p) == val; +} + /** * 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; +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)); @@ -155,7 +188,9 @@ static void bc_parse_setLabel(BcParse *p) { * @param p The parser. * @param idx The index of the label. */ -static void bc_parse_createLabel(BcParse *p, size_t idx) { +static void +bc_parse_createLabel(BcParse* p, size_t idx) +{ bc_vec_push(&p->func->labels, &idx); } @@ -165,12 +200,14 @@ static void bc_parse_createLabel(BcParse *p, size_t idx) { * @param p The parser. * @param idx The index of the label. */ -static void bc_parse_createCondLabel(BcParse *p, size_t idx) { +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 @@ -184,8 +221,9 @@ static void bc_parse_createCondLabel(BcParse *p, size_t idx) { * @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) { - +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)); @@ -210,32 +248,37 @@ static void bc_parse_createExitLabel(BcParse *p, size_t idx, bool loop) { * @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) +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) { - + // 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 it's a left paren, we have reached the end of whatever expression + // this is no matter what. We also don't pop the left paren because it + // will need to stay for the rest of the subexpression. 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. + // + // Also, a lower precedence value means a higher precedence. 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.) + // expression was consumed (well, two were, but another was added) if + // the operator was not a prefix operator. (Postfix operators are not + // handled by this function at all.) bc_parse_push(p, BC_PARSE_TOKEN_INST(t)); bc_vec_pop(&p->ops); *nexprs -= !BC_PARSE_OP_PREFIX(t); @@ -252,12 +295,14 @@ static void bc_parse_operator(BcParse *p, BcLexType type, * @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) { - +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) { + 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); @@ -276,8 +321,9 @@ static void bc_parse_rightParen(BcParse *p, size_t *nexprs) { * @param flags Flags restricting what kind of expressions the arguments can * be. */ -static void bc_parse_args(BcParse *p, uint8_t flags) { - +static void +bc_parse_args(BcParse* p, uint8_t flags) +{ bool comma = false; size_t nargs; @@ -289,8 +335,8 @@ static void bc_parse_args(BcParse *p, uint8_t flags) { flags |= (BC_PARSE_ARRAY | BC_PARSE_NEEDVAL); // Count the arguments and parse them. - for (nargs = 0; p->l.t != BC_LEX_RPAREN; ++nargs) { - + 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); @@ -311,8 +357,9 @@ static void bc_parse_args(BcParse *p, uint8_t flags) { * @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) { - +static void +bc_parse_call(BcParse* p, const char* name, uint8_t flags) +{ size_t idx; bc_parse_args(p, flags); @@ -327,14 +374,10 @@ static void bc_parse_call(BcParse *p, const char *name, uint8_t flags) { // 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; - + if (idx == BC_VEC_INVALID_IDX) + { idx = bc_program_insertFunc(p->prog, name); - BC_SIG_UNLOCK; - assert(idx != BC_VEC_INVALID_IDX); // Make sure that this pointer was not invalidated. @@ -352,42 +395,46 @@ static void bc_parse_call(BcParse *p, const char *name, uint8_t flags) { /** * Parses a name/identifier-based expression. It could be a variable, an array * element, an array itself (for function arguments), a function call, etc. - * + * @param p The parser. + * @param type A pointer to return the resulting instruction. + * @param can_assign A pointer to return true if the name can be assigned to, + * false otherwise. + * @param flags Flags restricting what kind of expression the name can be. */ -static void bc_parse_name(BcParse *p, BcInst *type, - bool *can_assign, uint8_t flags) +static void +bc_parse_name(BcParse* p, BcInst* type, bool* can_assign, uint8_t flags) { - char *name; + char* name; - BC_SIG_LOCK; + BC_SIG_ASSERT_LOCKED; // 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; + BC_SETJMP_LOCKED(vm, err); // 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) { - + 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) { - + 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 { - + 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)) | @@ -397,7 +444,9 @@ static void bc_parse_name(BcParse *p, BcInst *type, // 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; @@ -410,18 +459,21 @@ static void bc_parse_name(BcParse *p, BcInst *type, bc_parse_push(p, *type); bc_parse_pushName(p, name, false); } - else if (p->l.t == BC_LEX_LPAREN) { - + 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 { + else + { // Just a variable. *type = BC_INST_VAR; *can_assign = true; @@ -431,9 +483,9 @@ static void bc_parse_name(BcParse *p, BcInst *type, err: // Need to make sure to unallocate the name. - BC_SIG_MAYLOCK; free(name); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); + BC_SIG_MAYLOCK; } /** @@ -442,8 +494,9 @@ static void bc_parse_name(BcParse *p, BcInst *type, * @param p The parser. * @param inst The instruction corresponding to the builtin. */ -static void bc_parse_noArgBuiltin(BcParse *p, BcInst inst) { - +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); @@ -465,13 +518,12 @@ static void bc_parse_noArgBuiltin(BcParse *p, BcInst inst) { * @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) +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); + if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); @@ -480,13 +532,18 @@ static void bc_parse_builtin(BcParse *p, BcLexType type, 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; + if (type == BC_LEX_KW_LENGTH || type == BC_LEX_KW_ASCIIFY) + { + flags |= BC_PARSE_ARRAY; + } + + // Otherwise, we need to clear it because it could be set. + else 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); + 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; @@ -498,16 +555,19 @@ static void bc_parse_builtin(BcParse *p, BcLexType type, /** * Parses a builtin function that takes 3 arguments. This includes modexp() and * divmod(). + * @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_builtin3(BcParse *p, BcLexType type, - uint8_t flags, BcInst *prev) +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); + if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); @@ -518,23 +578,21 @@ static void bc_parse_builtin3(BcParse *p, BcLexType type, 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); + 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); + 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) { - + 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); @@ -543,14 +601,18 @@ static void bc_parse_builtin3(BcParse *p, BcLexType type, // 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); @@ -558,8 +620,7 @@ static void bc_parse_builtin3(BcParse *p, BcLexType type, 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); + 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; @@ -567,8 +628,8 @@ static void bc_parse_builtin3(BcParse *p, BcLexType type, // 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) { - + if (type == BC_LEX_KW_DIVMOD) + { // The zeroth element. bc_parse_push(p, BC_INST_ZERO); bc_parse_push(p, BC_INST_ARRAY_ELEM); @@ -594,14 +655,14 @@ static void bc_parse_builtin3(BcParse *p, BcLexType type, * 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) +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) { - + if (p->l.t != BC_LEX_LPAREN) + { // Set, push, and return. *type = BC_INST_SCALE; *can_assign = true; @@ -622,8 +683,7 @@ static void bc_parse_scale(BcParse *p, BcInst *type, 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); + 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); @@ -640,8 +700,9 @@ static void bc_parse_scale(BcParse *p, BcInst *type, * 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) +static void +bc_parse_incdec(BcParse* p, BcInst* prev, bool* can_assign, size_t* nexs, + uint8_t flags) { BcLexType type; uchar inst; @@ -658,8 +719,8 @@ static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, } // Is the previous instruction for a variable? - if (BC_PARSE_INST_VAR(etype)) { - + if (BC_PARSE_INST_VAR(etype)) + { // If so, this is a postfix operator. if (!*can_assign) bc_parse_err(p, BC_ERR_PARSE_ASSIGN); @@ -669,8 +730,8 @@ static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, bc_lex_next(&p->l); *can_assign = false; } - else { - + 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); @@ -683,25 +744,28 @@ static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, *nexs = *nexs + 1; // Is the next token a normal identifier? - if (type == BC_LEX_NAME) { - + if (type == BC_LEX_NAME) + { // Parse the name. - uint8_t flags2 = flags & ~BC_PARSE_ARRAY; + 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) { + 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)) { - + 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. @@ -724,8 +788,9 @@ static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, * @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) +static void +bc_parse_minus(BcParse* p, BcInst* prev, size_t ops_bgn, bool rparen, + bool binlast, size_t* nexprs) { BcLexType type; @@ -747,7 +812,9 @@ static void bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn, * @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) { +static void +bc_parse_str(BcParse* p, BcInst inst) +{ bc_parse_addString(p); bc_parse_push(p, inst); bc_lex_next(&p->l); @@ -757,12 +824,13 @@ static void bc_parse_str(BcParse *p, BcInst inst) { * Parses a print statement. * @param p The parser. */ -static void bc_parse_print(BcParse *p, BcLexType type) { - +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; + BcInst inst = type == BC_LEX_KW_STREAM ? BC_INST_PRINT_STREAM : + BC_INST_PRINT_POP; bc_lex_next(&p->l); @@ -771,12 +839,13 @@ static void bc_parse_print(BcParse *p, BcLexType type) { // A print or stream statement has to have *something*. if (bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERR_PARSE_PRINT); - do { - + 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 { + 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); @@ -787,17 +856,16 @@ static void bc_parse_print(BcParse *p, BcLexType type) { // Get the next token if we have a comma. if (comma) bc_lex_next(&p->l); - else { - + 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); + if (!bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); else break; } t = p->l.t; - - } while (true); + } + 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); @@ -807,8 +875,9 @@ static void bc_parse_print(BcParse *p, BcLexType type) { * Parses a return statement. * @param p The parser. */ -static void bc_parse_return(BcParse *p) { - +static void +bc_parse_return(BcParse* p) +{ BcLexType t; bool paren; uchar inst = BC_INST_RET0; @@ -826,28 +895,33 @@ static void bc_parse_return(BcParse *p) { // An empty return statement just needs to push the selected instruction. if (bc_parse_isDelimiter(p)) bc_parse_push(p, inst); - else { - + 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) { + 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) { + 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 (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. @@ -860,8 +934,10 @@ static void bc_parse_return(BcParse *p) { * the jump location. * @param p The parser. */ -static void bc_parse_noElse(BcParse *p) { - uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p); +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); } @@ -871,15 +947,16 @@ static void bc_parse_noElse(BcParse *p) { * @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) { - +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) { - + 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); @@ -887,14 +964,17 @@ static void bc_parse_endBody(BcParse *p, bool brace) { bc_lex_next(&p->l); // If the next token is not a delimiter, that is a problem. - if (BC_ERR(!bc_parse_isDelimiter(p))) + if (BC_ERR(!bc_parse_isDelimiter(p) && !bc_parse_TopFunc(p))) + { bc_parse_err(p, BC_ERR_PARSE_TOKEN); + } } // Do we have a brace flag? has_brace = (BC_PARSE_BRACE(p) != 0); - do { + do + { size_t len = p->flags.len; bool loop; @@ -905,12 +985,12 @@ static void bc_parse_endBody(BcParse *p, bool brace) { loop = (BC_PARSE_LOOP_INNER(p) != 0); // If we are ending a loop or an else... - if (loop || BC_PARSE_ELSE(p)) { - + 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); + if (loop) + { + size_t* label = bc_vec_top(&p->conds); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, *label); @@ -922,7 +1002,8 @@ static void bc_parse_endBody(BcParse *p, bool brace) { bc_vec_pop(&p->flags); } // If we are ending a function... - else if (BC_PARSE_FUNC_INNER(p)) { + 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); @@ -933,17 +1014,20 @@ static void bc_parse_endBody(BcParse *p, bool brace) { 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))) { - + 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); + 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) { - + 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); @@ -951,7 +1035,9 @@ static void bc_parse_endBody(BcParse *p, bool brace) { // 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); @@ -959,20 +1045,19 @@ static void bc_parse_endBody(BcParse *p, bool brace) { // 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))); + } + // 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 (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); @@ -992,15 +1077,18 @@ static void bc_parse_endBody(BcParse *p, bool brace) { * @param p The parser. * @param flags The current flags (will be edited). */ -static void bc_parse_startBody(BcParse *p, uint16_t flags) { +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); } -void bc_parse_endif(BcParse *p) { - +void +bc_parse_endif(BcParse* p) +{ size_t i; bool good; @@ -1011,54 +1099,55 @@ void bc_parse_endif(BcParse *p) { // Find an instance of a body that needs closing, i.e., a statement that did // not have a right brace when it should have. - for (i = 0; good && i < p->flags.len; ++i) { + for (i = 0; good && i < p->flags.len; ++i) + { uint16_t flag = *((uint16_t*) bc_vec_item(&p->flags, i)); good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE); } // If we did not find such an instance... - if (good) { - + if (good) + { // We set this to restore it later. We don't want the parser thinking // that we are on stdin for this one because it will want more. - bool is_stdin = vm.is_stdin; + BcMode mode = vm->mode; - vm.is_stdin = false; + vm->mode = BC_MODE_FILE; // End all of the if statements and loops. - while (p->flags.len > 1 || BC_PARSE_IF_END(p)) { + while (p->flags.len > 1 || BC_PARSE_IF_END(p)) + { if (BC_PARSE_IF_END(p)) bc_parse_noElse(p); if (p->flags.len > 1) bc_parse_endBody(p, false); } - vm.is_stdin = is_stdin; + vm->mode = (uchar) mode; } // If we reach here, a block was not properly closed, and we should error. - else bc_parse_err(&vm.prs, BC_ERR_PARSE_BLOCK); + else bc_parse_err(&vm->prs, BC_ERR_PARSE_BLOCK); } /** * Parses an if statement. * @param p The parser. */ -static void bc_parse_if(BcParse *p) { - +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); + 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); + if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); @@ -1079,13 +1168,13 @@ static void bc_parse_if(BcParse *p) { * Parses an else statement. * @param p The parser. */ -static void bc_parse_else(BcParse *p) { - +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); + 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. @@ -1107,16 +1196,16 @@ static void bc_parse_else(BcParse *p) { * Parse a while loop. * @param p The parser. */ -static void bc_parse_while(BcParse *p) { - +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); + 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. @@ -1126,8 +1215,7 @@ static void bc_parse_while(BcParse *p) { // 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); + 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. @@ -1140,20 +1228,19 @@ static void bc_parse_while(BcParse *p) { * Parse a for loop. * @param p The parser. */ -static void bc_parse_for(BcParse *p) { - +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); + 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); + 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. @@ -1173,12 +1260,13 @@ static void bc_parse_for(BcParse *p) { bc_parse_createLabel(p, p->func->code.len); // Parse an expression if it exists. - if (p->l.t != BC_LEX_SCOLON) { + 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 { - + 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 @@ -1191,8 +1279,7 @@ static void bc_parse_for(BcParse *p) { } // Must have a semicolon. - if (BC_ERR(p->l.t != BC_LEX_SCOLON)) - bc_parse_err(p, BC_ERR_PARSE_TOKEN); + 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 @@ -1208,13 +1295,11 @@ static void bc_parse_for(BcParse *p) { 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); + 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); + 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); @@ -1233,17 +1318,18 @@ static void bc_parse_for(BcParse *p) { * @param p The parser. * @param type The type of exit. */ -static void bc_parse_loopExit(BcParse *p, BcLexType type) { - +static void +bc_parse_loopExit(BcParse* p, BcLexType type) +{ size_t i; - BcInstPtr *ip; + 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 (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); @@ -1253,7 +1339,11 @@ static void bc_parse_loopExit(BcParse *p, BcLexType type) { // 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--); + while (!ip->func && i < p->exits.len) + { + ip = bc_vec_item(&p->exits, i); + i -= 1; + } // Make sure everything is hunky dory. assert(ip != NULL && (i < p->exits.len || ip->func)); @@ -1276,8 +1366,9 @@ static void bc_parse_loopExit(BcParse *p, BcLexType type) { * Parse a function (header). * @param p The parser. */ -static void bc_parse_func(BcParse *p) { - +static void +bc_parse_func(BcParse* p) +{ bool comma = false, voidfn; uint16_t flags; size_t idx; @@ -1299,8 +1390,8 @@ static void bc_parse_func(BcParse *p) { voidfn = (voidfn && p->l.t == BC_LEX_NAME); // With a void function, allow POSIX to complain and get a new token. - if (voidfn) { - + if (voidfn) + { bc_parse_err(p, BC_ERR_POSIX_VOID); // We can safely do this because the expected token should not overwrite @@ -1309,21 +1400,14 @@ static void bc_parse_func(BcParse *p) { } // Must have a left paren. - if (BC_ERR(p->l.t != BC_LEX_LPAREN)) - bc_parse_err(p, BC_ERR_PARSE_FUNC); + 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); @@ -1334,13 +1418,13 @@ static void bc_parse_func(BcParse *p) { 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) { - + 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) { - + if (p->l.t == BC_LEX_OP_MULTIPLY) + { t = BC_TYPE_REF; bc_lex_next(&p->l); @@ -1349,8 +1433,7 @@ static void bc_parse_func(BcParse *p) { } // 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); + 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; @@ -1361,8 +1444,8 @@ static void bc_parse_func(BcParse *p) { bc_lex_next(&p->l); // We are parsing an array parameter if this is true. - if (p->l.t == BC_LEX_LBRACKET) { - + 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; @@ -1370,14 +1453,18 @@ static void bc_parse_func(BcParse *p) { // 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); @@ -1405,8 +1492,9 @@ static void bc_parse_func(BcParse *p) { * Parse an auto list. * @param p The parser. */ -static void bc_parse_auto(BcParse *p) { - +static void +bc_parse_auto(BcParse* p) +{ bool comma, one; // Error if the auto keyword appeared in the wrong place. @@ -1419,8 +1507,8 @@ static void bc_parse_auto(BcParse *p) { one = (p->l.t == BC_LEX_NAME); // While we have a variable or array. - while (p->l.t == BC_LEX_NAME) { - + while (p->l.t == BC_LEX_NAME) + { BcType t; // Copy the name from the lexer, so we can use it again. @@ -1429,15 +1517,17 @@ static void bc_parse_auto(BcParse *p) { bc_lex_next(&p->l); // If we are parsing an array... - if (p->l.t == BC_LEX_LBRACKET) { - + 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); } @@ -1458,8 +1548,7 @@ static void bc_parse_auto(BcParse *p) { 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); + if (BC_ERR(!bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); } /** @@ -1467,9 +1556,10 @@ static void bc_parse_auto(BcParse *p) { * @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); +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); @@ -1480,15 +1570,15 @@ static void bc_parse_body(BcParse *p, bool brace) { // 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) { - + 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) { - + if (!p->auto_part) + { // Make sure this is true to not get a parse error. p->auto_part = true; @@ -1499,8 +1589,8 @@ static void bc_parse_body(BcParse *p, bool brace) { // Eat a newline. if (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); } - else { - + else + { // This is the easy part. size_t len = p->flags.len; @@ -1514,7 +1604,9 @@ static void bc_parse_body(BcParse *p, bool brace) { // 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); + } } } @@ -1523,20 +1615,23 @@ static void bc_parse_body(BcParse *p, bool brace) { * function definitions. * @param p The parser. */ -static void bc_parse_stmt(BcParse *p) { - +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) { + if (type == BC_LEX_NLINE) + { bc_lex_next(&p->l); return; } // Eat auto list. - if (type == BC_LEX_KW_AUTO) { + if (type == BC_LEX_KW_AUTO) + { bc_parse_auto(p); return; } @@ -1546,30 +1641,35 @@ static void bc_parse_stmt(BcParse *p) { // Everything but an else needs to be taken care of here, but else is // special. - if (type != BC_LEX_KW_ELSE) { - + if (type != BC_LEX_KW_ELSE) + { // After an if, no else found. - if (BC_PARSE_IF_END(p)) { - + 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) { - + else if (type == BC_LEX_LBRACE) + { // We need to start a body if we are not expecting one yet. - if (!BC_PARSE_BODY(p)) { + 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 { + else + { *(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_BRACE; bc_lex_next(&p->l); bc_parse_body(p, true); @@ -1582,7 +1682,8 @@ static void bc_parse_stmt(BcParse *p) { // 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)) { + else if (BC_PARSE_BODY(p) && !BC_PARSE_BRACE(p)) + { bc_parse_body(p, false); return; } @@ -1591,8 +1692,8 @@ static void bc_parse_stmt(BcParse *p) { len = p->flags.len; flags = BC_PARSE_TOP_FLAG(p); - switch (type) { - + switch (type) + { // All of these are valid for expressions. case BC_LEX_OP_INC: case BC_LEX_OP_DEC: @@ -1611,6 +1712,8 @@ static void bc_parse_stmt(BcParse *p) { #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: + case BC_LEX_KW_IS_NUMBER: + case BC_LEX_KW_IS_STRING: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_IRAND: #endif // BC_ENABLE_EXTRA_MATH @@ -1722,7 +1825,7 @@ static void bc_parse_stmt(BcParse *p) { { // Quit is a compile-time command. We don't exit directly, so the vm // can clean up. - vm.status = BC_STATUS_QUIT; + vm->status = BC_STATUS_QUIT; BC_JMP; break; } @@ -1739,38 +1842,128 @@ static void bc_parse_stmt(BcParse *p) { break; } - default: + case BC_LEX_EOF: + case BC_LEX_INVALID: + case BC_LEX_NEG: +#if BC_ENABLE_EXTRA_MATH + case BC_LEX_OP_TRUNC: +#endif // BC_ENABLE_EXTRA_MATH + 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_OR: + case BC_LEX_OP_BOOL_AND: + 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: + case BC_LEX_NLINE: + case BC_LEX_WHITESPACE: + case BC_LEX_RPAREN: + case BC_LEX_LBRACKET: + case BC_LEX_COMMA: + case BC_LEX_RBRACKET: + case BC_LEX_LBRACE: + case BC_LEX_KW_AUTO: + case BC_LEX_KW_DEFINE: +#if DC_ENABLED + case BC_LEX_EXTENDED_REGISTERS: + case BC_LEX_EQ_NO_REG: + case BC_LEX_COLON: + case BC_LEX_EXECUTE: + case BC_LEX_PRINT_STACK: + case BC_LEX_CLEAR_STACK: + case BC_LEX_REG_STACK_LEVEL: + case BC_LEX_STACK_LEVEL: + case BC_LEX_DUPLICATE: + case BC_LEX_SWAP: + case BC_LEX_POP: + case BC_LEX_STORE_IBASE: + case BC_LEX_STORE_OBASE: + case BC_LEX_STORE_SCALE: +#if BC_ENABLE_EXTRA_MATH + case BC_LEX_STORE_SEED: +#endif // BC_ENABLE_EXTRA_MATH + case BC_LEX_LOAD: + case BC_LEX_LOAD_POP: + case BC_LEX_STORE_PUSH: + case BC_LEX_PRINT_POP: + case BC_LEX_NQUIT: + case BC_LEX_EXEC_STACK_LENGTH: + case BC_LEX_SCALE_FACTOR: + case BC_LEX_ARRAY_LENGTH: +#endif // DC_ENABLED { 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 (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); -} + while (p->l.t == BC_LEX_SCOLON || p->l.t == BC_LEX_NLINE) + { + bc_lex_next(&p->l); + } -void bc_parse_parse(BcParse *p) { + // POSIX's grammar does not allow a function definition after a semicolon + // without a newline, so check specifically for that case and error if + // the POSIX standard flag is set. + if (p->l.last == BC_LEX_SCOLON && p->l.t == BC_LEX_KW_DEFINE && BC_IS_POSIX) + { + bc_parse_err(p, BC_ERR_POSIX_FUNC_AFTER_SEMICOLON); + } +} +void +bc_parse_parse(BcParse* p) +{ assert(p); - BC_SETJMP(exit); + BC_SETJMP_LOCKED(vm, 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))) { + else if (p->l.t == BC_LEX_KW_DEFINE) + { + if (BC_ERR(BC_PARSE_NO_EXEC(p))) + { bc_parse_endif(p); if (BC_ERR(BC_PARSE_NO_EXEC(p))) + { bc_parse_err(p, BC_ERR_PARSE_TOKEN); + } } bc_parse_func(p); } @@ -1780,13 +1973,14 @@ void bc_parse_parse(BcParse *p) { exit: - BC_SIG_MAYLOCK; - // We need to reset on error. - if (BC_ERR(((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig))) + if (BC_ERR(((vm->status && vm->status != BC_STATUS_QUIT) || vm->sig != 0))) + { bc_parse_reset(p); + } - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); + BC_SIG_MAYLOCK; } /** @@ -1800,15 +1994,16 @@ void bc_parse_parse(BcParse *p) { * 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) +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; + bool pfirst, rprn, array_last, done, get_token, assign; + bool bin_last, incdec, can_assign; // One of these *must* be true. assert(!(flags & BC_PARSE_PRINT) || !(flags & BC_PARSE_NEEDVAL)); @@ -1825,6 +2020,7 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // - 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. + // - array_last is an array item 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. @@ -1836,20 +2032,32 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, nparens = nrelops = 0; nexprs = 0; ops_bgn = p->ops.len; - rprn = done = get_token = assign = incdec = can_assign = false; + rprn = array_last = 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); + 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) { + // Make sure an array expression is not mixed with any others. However, + // a right parenthesis may end the expression, so we will need to take + // care of that right there. + if (BC_ERR(array_last && t != BC_LEX_RPAREN)) + { + bc_parse_err(p, BC_ERR_PARSE_EXPR); + } + switch (t) + { case BC_LEX_OP_INC: case BC_LEX_OP_DEC: { @@ -1872,7 +2080,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // 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. @@ -1918,10 +2128,13 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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 } - // Fallthrough. - BC_FALLTHROUGH case BC_LEX_OP_POWER: case BC_LEX_OP_MULTIPLY: @@ -1945,18 +2158,22 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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)) { - + 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); @@ -1975,7 +2192,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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; @@ -1992,21 +2211,34 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // 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) { + if (!nparens) + { done = true; get_token = false; break; } + // Now that we know the right paren has not ended the + // expression, make sure an array expression is not mixed with + // any others. + if (BC_ERR(array_last)) + { + bc_parse_err(p, BC_ERR_PARSE_EXPR); + } + nparens -= 1; rprn = true; get_token = bin_last = incdec = false; @@ -2023,7 +2255,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // 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); @@ -2038,13 +2272,16 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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); + array_last = (prev == BC_INST_ARRAY); nexprs += 1; flags &= ~(BC_PARSE_ARRAY); @@ -2055,7 +2292,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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); @@ -2078,7 +2317,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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); @@ -2094,6 +2335,8 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, case BC_LEX_KW_LENGTH: case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: + case BC_LEX_KW_IS_NUMBER: + case BC_LEX_KW_IS_STRING: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_IRAND: #endif // BC_ENABLE_EXTRA_MATH @@ -2101,7 +2344,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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); @@ -2128,11 +2373,15 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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); @@ -2148,7 +2397,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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. @@ -2166,7 +2417,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, { // 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); @@ -2177,13 +2430,64 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, break; } - default: + case BC_LEX_EOF: + case BC_LEX_INVALID: + case BC_LEX_NEG: + case BC_LEX_NLINE: + case BC_LEX_WHITESPACE: + case BC_LEX_LBRACKET: + case BC_LEX_COMMA: + case BC_LEX_RBRACKET: + case BC_LEX_LBRACE: + case BC_LEX_SCOLON: + case BC_LEX_RBRACE: + case BC_LEX_KW_AUTO: + case BC_LEX_KW_BREAK: + case BC_LEX_KW_CONTINUE: + case BC_LEX_KW_DEFINE: + case BC_LEX_KW_FOR: + case BC_LEX_KW_IF: + case BC_LEX_KW_LIMITS: + case BC_LEX_KW_RETURN: + case BC_LEX_KW_WHILE: + case BC_LEX_KW_HALT: + case BC_LEX_KW_PRINT: + case BC_LEX_KW_QUIT: + case BC_LEX_KW_STREAM: + case BC_LEX_KW_ELSE: +#if DC_ENABLED + case BC_LEX_EXTENDED_REGISTERS: + case BC_LEX_EQ_NO_REG: + case BC_LEX_COLON: + case BC_LEX_EXECUTE: + case BC_LEX_PRINT_STACK: + case BC_LEX_CLEAR_STACK: + case BC_LEX_REG_STACK_LEVEL: + case BC_LEX_STACK_LEVEL: + case BC_LEX_DUPLICATE: + case BC_LEX_SWAP: + case BC_LEX_POP: + case BC_LEX_STORE_IBASE: + case BC_LEX_STORE_OBASE: + case BC_LEX_STORE_SCALE: +#if BC_ENABLE_EXTRA_MATH + case BC_LEX_STORE_SEED: +#endif // BC_ENABLE_EXTRA_MATH + case BC_LEX_LOAD: + case BC_LEX_LOAD_POP: + case BC_LEX_STORE_PUSH: + case BC_LEX_PRINT_POP: + case BC_LEX_NQUIT: + case BC_LEX_EXEC_STACK_LENGTH: + case BC_LEX_SCALE_FACTOR: + case BC_LEX_ARRAY_LENGTH: +#endif // DC_ENABLED { -#ifndef NDEBUG +#if BC_DEBUG // We should never get here, even in debug builds. bc_parse_err(p, BC_ERR_PARSE_TOKEN); break; -#endif // NDEBUG +#endif // BC_DEBUG } } @@ -2192,14 +2496,16 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // Now that we have parsed the expression, we need to empty the operator // stack. - while (p->ops.len > ops_bgn) { - + 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)); @@ -2214,35 +2520,46 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, 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); + for (i = 0; i < next.len && t != next.tokens[i]; ++i) + { + continue; + } 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) { - + if (!(flags & BC_PARSE_NEEDVAL) && !pfirst) + { // We have the easy case if the last operator was an assignment // operator. - if (assign) { + 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)) { + 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); + 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 @@ -2262,8 +2579,8 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, } // If we might have to print... - if ((flags & BC_PARSE_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); @@ -2283,9 +2600,15 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // 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); + } + if (incdec) + { + while (p->l.t == BC_LEX_NLINE) + { + bc_lex_next(&p->l); + } } return BC_PARSE_STATUS_SUCCESS; @@ -2298,15 +2621,20 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, * @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) { - +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) { +void +bc_parse_expr(BcParse* p, uint8_t flags) +{ assert(p); bc_parse_expr_status(p, flags, bc_parse_next_read); } diff --git a/contrib/bc/src/data.c b/contrib/bc/src/data.c index 82475299ed7..bb1a6796f75 100644 --- a/contrib/bc/src/data.c +++ b/contrib/bc/src/data.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -66,12 +66,16 @@ const uchar dc_sig_msg_len = (uchar) (sizeof(dc_sig_msg) - 1); #endif // DC_ENABLED +// clang-format off + /// 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" + "Copyright (c) 2018-2024 Gavin D. Howard and contributors\n" + "Report bugs at: https://git.gavinhoward.com/gavin/bc\n\n" "This is free software with ABSOLUTELY NO WARRANTY.\n"; +// clang-format on + #ifdef __OpenBSD__ #if BC_ENABLE_EXTRA_MATH @@ -137,14 +141,22 @@ const char bc_pledge_end[] = ""; /// end. const BcOptLong bc_args_lopt[] = { + { "digit-clamp", BC_OPT_NONE, 'c' }, { "expression", BC_OPT_REQUIRED, 'e' }, { "file", BC_OPT_REQUIRED, 'f' }, { "help", BC_OPT_NONE, 'h' }, { "interactive", BC_OPT_NONE, 'i' }, + { "ibase", BC_OPT_REQUIRED, 'I' }, { "leading-zeroes", BC_OPT_NONE, 'z' }, { "no-line-length", BC_OPT_NONE, 'L' }, + { "obase", BC_OPT_REQUIRED, 'O' }, + { "no-digit-clamp", BC_OPT_NONE, 'C' }, { "no-prompt", BC_OPT_NONE, 'P' }, { "no-read-prompt", BC_OPT_NONE, 'R' }, + { "scale", BC_OPT_REQUIRED, 'S' }, +#if BC_ENABLE_EXTRA_MATH + { "seed", BC_OPT_REQUIRED, 'E' }, +#endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLED { "global-stacks", BC_OPT_BC_ONLY, 'g' }, { "mathlib", BC_OPT_BC_ONLY, 'l' }, @@ -162,11 +174,66 @@ const BcOptLong bc_args_lopt[] = { }; -/// The function header for error messages. -const char* const bc_err_func_header = "Function:"; +#if BC_ENABLE_OSSFUZZ + +const char* bc_fuzzer_args_c[] = { + "bc", + "-lqc", + "-e", + "seed = 82507683022933941343198991100880559238.7080266844215897551270760113" + "4734858017748592704189096562163085637164174146616055338762825421827784" + "566630725748836994171142578125", + NULL, +}; + +const char* dc_fuzzer_args_c[] = { + "dc", + "-xc", + "-e", + "82507683022933941343198991100880559238.7080266844215897551270760113" + "4734858017748592704189096562163085637164174146616055338762825421827784" + "566630725748836994171142578125j", + NULL, +}; + +const char* bc_fuzzer_args_C[] = { + "bc", + "-lqC", + "-e", + "seed = 82507683022933941343198991100880559238.7080266844215897551270760113" + "4734858017748592704189096562163085637164174146616055338762825421827784" + "566630725748836994171142578125", + NULL, +}; + +const char* dc_fuzzer_args_C[] = { + "dc", + "-xC", + "-e", + "82507683022933941343198991100880559238.7080266844215897551270760113" + "4734858017748592704189096562163085637164174146616055338762825421827784" + "566630725748836994171142578125j", + NULL, +}; + +const size_t bc_fuzzer_args_len = sizeof(bc_fuzzer_args_c) / sizeof(char*); + +#if BC_C11 + +_Static_assert(sizeof(bc_fuzzer_args_C) / sizeof(char*) == bc_fuzzer_args_len, + "Wrong number of bc fuzzer args"); + +_Static_assert(sizeof(dc_fuzzer_args_c) / sizeof(char*) == bc_fuzzer_args_len, + "Wrong number of dc fuzzer args"); -/// The line format string for error messages. -const char* const bc_err_line = ":%zu"; +_Static_assert(sizeof(dc_fuzzer_args_C) / sizeof(char*) == bc_fuzzer_args_len, + "Wrong number of dc fuzzer args"); + +#endif // BC_C11 + +#endif // BC_ENABLE_OSSFUZZ + +// clang-format off /// The default error category strings. const char *bc_errs[] = { @@ -179,18 +246,20 @@ const char *bc_errs[] = { #endif // BC_ENABLED }; +// clang-format on + /// 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_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_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, @@ -202,7 +271,7 @@ const uchar bc_err_ids[] = { 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 }; @@ -236,14 +305,17 @@ const char* const bc_err_msgs[] = { "stack has too few elements", "stack for register \"%s\" has too few elements", #else // DC_ENABLED - NULL, NULL, + 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, + NULL, + NULL, + NULL, #endif // BC_ENABLED "end of file", @@ -257,7 +329,7 @@ const char* const bc_err_msgs[] = { "bad print or stream statement", "bad function definition", ("bad assignment: left side must be scale, ibase, " - "obase, seed, last, var, or array element"), + "obase, seed, last, var, or array element"), "no auto variable found", "function parameter or auto \"%s%s\" already exists", "block end cannot be found", @@ -273,6 +345,7 @@ const char* const bc_err_msgs[] = { "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", + "POSIX requires a newline between a semicolon and a function definition", #if BC_ENABLE_EXTRA_MATH "POSIX does not allow exponential notation", #else @@ -294,15 +367,15 @@ const BcVecFree bc_vec_dtors[] = { bc_vec_free, bc_num_free, #if !BC_ENABLE_LIBRARY -#ifndef NDEBUG +#if BC_DEBUG bc_func_free, -#endif // NDEBUG +#endif // BC_DEBUG bc_slab_free, bc_const_free, bc_result_free, -#if BC_ENABLE_HISTORY +#if BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB bc_history_string_free, -#endif // BC_ENABLE_HISTORY +#endif // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB #else // !BC_ENABLE_LIBRARY bcl_num_destruct, #endif // !BC_ENABLE_LIBRARY @@ -310,7 +383,17 @@ const BcVecFree bc_vec_dtors[] = { #if !BC_ENABLE_LIBRARY -#if BC_ENABLE_HISTORY +#if BC_ENABLE_EDITLINE + +/// The normal path to the editrc. +const char bc_history_editrc[] = "/.editrc"; + +/// The length of the normal path to the editrc. +const size_t bc_history_editrc_len = sizeof(bc_history_editrc) - 1; + +#endif // BC_ENABLE_EDITLINE + +#if BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB /// 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; @@ -320,351 +403,279 @@ 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 }; +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 char bc_history_tab[] = "\t"; 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 }, + { 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]); +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, + 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 +const size_t bc_history_combo_chars_len = sizeof(bc_history_combo_chars) / + sizeof(bc_history_combo_chars[0]); +#endif // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB /// The human-readable name of the main function in bc source code. const char bc_func_main[] = "(main)"; @@ -761,6 +772,8 @@ const char* bc_inst_names[] = { "BC_INST_SCALE_FUNC", "BC_INST_SQRT", "BC_INST_ABS", + "BC_INST_IS_NUMBER", + "BC_INST_IS_STRING", #if BC_ENABLE_EXTRA_MATH "BC_INST_IRAND", #endif // BC_ENABLE_EXTRA_MATH @@ -858,6 +871,8 @@ const BcLexKeyword bc_lex_kws[] = { BC_LEX_KW_ENTRY("print", 5, false), BC_LEX_KW_ENTRY("sqrt", 4, true), BC_LEX_KW_ENTRY("abs", 3, false), + BC_LEX_KW_ENTRY("is_number", 9, false), + BC_LEX_KW_ENTRY("is_string", 9, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("irand", 5, false), #endif // BC_ENABLE_EXTRA_MATH @@ -891,8 +906,8 @@ const size_t bc_lex_kws_len = sizeof(bc_lex_kws) / sizeof(BcLexKeyword); // 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."); +_Static_assert(sizeof(bc_lex_kws) / sizeof(BcLexKeyword) == BC_LEX_NKWS, + "BC_LEX_NKWS is wrong."); #endif // BC_C11 @@ -930,13 +945,13 @@ const uint8_t bc_parse_exprs[] = { 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, true, true, true), - // Starts with BC_LEX_KW_STREAM. - BC_PARSE_EXPR_ENTRY(false, false, 0, 0, 0, 0, 0, 0) + // Starts with BC_LEX_KW_QUIT. + BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, true), + + // Starts with BC_LEX_KW_GLOBAL_STACKS. + BC_PARSE_EXPR_ENTRY(true, true, false, false, 0, 0, 0, 0) #else // BC_ENABLE_EXTRA_MATH @@ -953,33 +968,35 @@ const uint8_t bc_parse_exprs[] = { 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), + BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, false), - // Starts with BC_LEX_KW_MAXSCALE, - BC_PARSE_EXPR_ENTRY(true, true, true, true, true, false, false, 0) + // Starts with BC_LEX_KW_MAXIBASE. + BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, false), + + // Starts with BC_LEX_KW_ELSE. + BC_PARSE_EXPR_ENTRY(false, 0, 0, 0, 0, 0, 0, 0) #endif // BC_ENABLE_EXTRA_MATH }; -/// An array of data for operators that correspond to token types. +/// An array of data for operators that correspond to token types. Note that a +/// lower precedence *value* means a higher precedence. 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), + 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), + 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), + 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(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 @@ -989,16 +1006,19 @@ const uchar bc_parse_ops[] = { // 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); +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); +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); +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. @@ -1016,8 +1036,8 @@ const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET); const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON); /// The valid next tokens for read expressions. -const BcParseNext bc_parse_next_read = - BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF); +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. @@ -1029,9 +1049,10 @@ const BcParseNext bc_parse_next_builtin = BC_PARSE_NEXT(1, BC_LEX_COMMA); /// 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_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, }; @@ -1055,26 +1076,49 @@ const uchar dc_lex_tokens[] = { #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH - BC_LEX_OP_MODULUS, BC_LEX_INVALID, + 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, + 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, + 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 @@ -1086,20 +1130,39 @@ const uchar dc_lex_tokens[] = { #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_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, + 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 @@ -1111,70 +1174,96 @@ const uchar dc_lex_tokens[] = { #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_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_KW_IS_STRING, + BC_LEX_KW_IS_NUMBER, + 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. +/// @a 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, + BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED - BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED - BC_INST_INVALID, BC_INST_BOOL_NOT, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + BC_INST_LENGTH, BC_INST_PRINT, + BC_INST_SQRT, BC_INST_ABS, + BC_INST_IS_NUMBER, BC_INST_IS_STRING, #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, + 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, + BC_INST_MAXIBASE, BC_INST_MAXOBASE, + BC_INST_MAXSCALE, #if BC_ENABLE_EXTRA_MATH BC_INST_MAXRAND, #endif // BC_ENABLE_EXTRA_MATH @@ -1182,18 +1271,22 @@ const uchar dc_parse_insts[] = { #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, + BC_INST_LEADING_ZERO, BC_INST_PRINT_STREAM, + BC_INST_INVALID, BC_INST_EXTENDED_REGISTERS, + 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, + 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 @@ -1206,6 +1299,8 @@ const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER; #endif // BC_ENABLE_EXTRA_MATH +// clang-format off + #if BC_LONG_BIT >= 64 /// A constant array for the max of a bigdig number as a BcDig array. @@ -1244,6 +1339,8 @@ const BcDig bc_num_bigdigMax2[] = { #endif // BC_LONG_BIT >= 64 +// clang-format on + /// The size of the bigdig max array. const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig); @@ -1253,6 +1350,8 @@ 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"; +// clang-format off + /// An array for easy conversion from exponent to power of 10. const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1] = { 1, @@ -1269,12 +1368,15 @@ const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1] = { #endif // BC_BASE_DIGS > 4 }; +// clang-format on + #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, + 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 @@ -1283,8 +1385,8 @@ const BcNumBinaryOp bc_program_ops[] = { /// 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, + 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 @@ -1293,7 +1395,8 @@ const BcNumBinaryOpReq bc_program_opReqs[] = { /// An array of unary operator functions corresponding to the order of the /// instructions. const BcProgramUnary bc_program_unarys[] = { - bc_program_negate, bc_program_not, + bc_program_negate, + bc_program_not, #if BC_ENABLE_EXTRA_MATH bc_program_trunc, #endif // BC_ENABLE_EXTRA_MATH diff --git a/contrib/bc/src/dc.c b/contrib/bc/src/dc.c index 67bc3e16c3c..37419acd4bd 100644 --- a/contrib/bc/src/dc.c +++ b/contrib/bc/src/dc.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -45,19 +45,21 @@ * @param argc The number of arguments. * @param argv The arguments. */ -void dc_main(int argc, char *argv[]) { - +BcStatus +dc_main(int argc, const char* argv[]) +{ // All of these just set dc-specific items in BcVm. - vm.read_ret = BC_INST_POP_EXEC; - vm.help = dc_help; - vm.sigmsg = dc_sig_msg; - vm.siglen = dc_sig_msg_len; + vm->read_ret = BC_INST_POP_EXEC; + vm->help = dc_help; + vm->sigmsg = dc_sig_msg; + vm->siglen = dc_sig_msg_len; - vm.next = dc_lex_token; - vm.parse = dc_parse_parse; - vm.expr = dc_parse_expr; + vm->next = dc_lex_token; + vm->parse = dc_parse_parse; + vm->expr = dc_parse_expr; - bc_vm_boot(argc, argv); + return bc_vm_boot(argc, argv); } + #endif // DC_ENABLED diff --git a/contrib/bc/src/dc_fuzzer.c b/contrib/bc/src/dc_fuzzer.c new file mode 100644 index 00000000000..adaf486a668 --- /dev/null +++ b/contrib/bc/src/dc_fuzzer.c @@ -0,0 +1,112 @@ +/* + * ***************************************************************************** + * + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2018-2024 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 entry point for libFuzzer when fuzzing dc. + * + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +uint8_t* bc_fuzzer_data; + +/// A boolean about whether we should use -c (false) or -C (true). +static bool dc_C; + +int +LLVMFuzzerInitialize(int* argc, char*** argv) +{ + BC_UNUSED(argc); + + if (argv == NULL || *argv == NULL) + { + dc_C = false; + } + else + { + char* name; + + // Get the basename + name = strrchr((*argv)[0], BC_FILE_SEP); + name = name == NULL ? (*argv)[0] : name + 1; + + // Figure out which to use. + dc_C = (strcmp(name, "dc_fuzzer_C") == 0); + } + + return 0; +} + +int +LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) +{ + BcStatus s; + + // I've already tested empty input, so just ignore. + if (Size == 0 || Data[0] == '\0') return 0; + + // Clear the global. This is to ensure a clean start. + memset(vm, 0, sizeof(BcVm)); + + // Make sure to set the name. + vm->name = "dc"; + + BC_SIG_LOCK; + + // We *must* do this here. Otherwise, other code could not jump out all of + // the way. + bc_vec_init(&vm->jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); + + BC_SETJMP_LOCKED(vm, exit); + + // Create a string with the data. + bc_fuzzer_data = bc_vm_malloc(Size + 1); + memcpy(bc_fuzzer_data, Data, Size); + bc_fuzzer_data[Size] = '\0'; + + s = dc_main((int) (bc_fuzzer_args_len - 1), + dc_C ? dc_fuzzer_args_C : dc_fuzzer_args_c); + +exit: + + BC_SIG_MAYLOCK; + + free(bc_fuzzer_data); + + return s == BC_STATUS_SUCCESS || s == BC_STATUS_QUIT ? 0 : -1; +} diff --git a/contrib/bc/src/dc_lex.c b/contrib/bc/src/dc_lex.c index 5c6950ba969..d5131b45331 100644 --- a/contrib/bc/src/dc_lex.c +++ b/contrib/bc/src/dc_lex.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -40,7 +40,9 @@ #include #include -bool dc_lex_negCommand(BcLex *l) { +bool +dc_lex_negCommand(BcLex* l) +{ char c = l->buf[l->i]; return !BC_LEX_NUM_CHAR(c, false, false); } @@ -50,11 +52,12 @@ bool dc_lex_negCommand(BcLex *l) { * extended-register extension is implemented. * @param l The lexer. */ -static void dc_lex_register(BcLex *l) { - +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])) { - + if (DC_X && isspace(l->buf[l->i - 1])) + { char c; // Eat the whitespace. @@ -63,18 +66,22 @@ static void dc_lex_register(BcLex *l) { // 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 { - + 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); @@ -90,8 +97,9 @@ static void dc_lex_register(BcLex *l) { * characters. Oh, and dc strings need to check for escaped brackets. * @param l The lexer. */ -static void dc_lex_string(BcLex *l) { - +static void +dc_lex_string(BcLex* l) +{ size_t depth, nls, i; char c; bool got_more; @@ -100,25 +108,29 @@ static void dc_lex_string(BcLex *l) { l->t = BC_LEX_STR; bc_vec_popAll(&l->str); - do { - + do + { depth = 1; nls = 0; got_more = false; - assert(!l->is_stdin || l->buf == vm.buffer.v); +#if !BC_ENABLE_OSSFUZZ + assert(l->mode != BC_MODE_STDIN || l->buf == vm->buffer.v); +#endif // !BC_ENABLE_OSSFUZZ // 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) { - + for (i = l->i; (c = l->buf[i]) && depth; ++i) + { // Check for escaped brackets and set the depths as appropriate. - if (c == '\\') { + if (c == '\\') + { c = l->buf[++i]; if (!c) break; } - else { + else + { depth += (c == '['); depth -= (c == ']'); } @@ -129,15 +141,24 @@ static void dc_lex_string(BcLex *l) { 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); - } + if (BC_ERR(c == '\0' && depth)) + { + if (!vm->eof && l->mode != BC_MODE_FILE) + { + got_more = bc_lex_readLine(l); + } - } while (got_more && depth); + 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)) { + if (BC_ERR(c == '\0' && depth)) + { l->i = i; bc_lex_err(l, BC_ERR_PARSE_STRING); } @@ -152,17 +173,21 @@ static void dc_lex_string(BcLex *l) { * Lexes a dc token. This is the dc implementation of BcLexNext. * @param l The lexer. */ -void dc_lex_token(BcLex *l) { - +void +dc_lex_token(BcLex* l) +{ char c = l->buf[l->i++], c2; size_t i; + BC_SIG_ASSERT_LOCKED; + // 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) { - + 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]) { + if (l->last == dc_lex_regs[i]) + { dc_lex_register(l); return; } @@ -178,8 +203,8 @@ void dc_lex_token(BcLex *l) { // This is the workhorse of the lexer when more complicated things are // needed. - switch (c) { - + switch (c) + { case '\0': case '\n': case '\t': @@ -221,7 +246,9 @@ void dc_lex_token(BcLex *l) { // 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; @@ -253,6 +280,7 @@ void dc_lex_token(BcLex *l) { c2 = l->buf[l->i]; if (c2 == 'l') l->t = BC_LEX_KW_LINE_LENGTH; + else if (c2 == 'x') l->t = BC_LEX_EXTENDED_REGISTERS; else if (c2 == 'z') l->t = BC_LEX_KW_LEADING_ZERO; else bc_lex_invalidChar(l, c2); diff --git a/contrib/bc/src/dc_parse.c b/contrib/bc/src/dc_parse.c index b9b5afb66c4..1996120461a 100644 --- a/contrib/bc/src/dc_parse.c +++ b/contrib/bc/src/dc_parse.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -50,8 +50,9 @@ * @param p The parser. * @param var True if the parser is for a variable, false otherwise. */ -static void dc_parse_register(BcParse *p, bool var) { - +static void +dc_parse_register(BcParse* p, bool var) +{ bc_lex_next(&p->l); if (p->l.t != BC_LEX_NAME) bc_parse_err(p, BC_ERR_PARSE_TOKEN); @@ -62,7 +63,9 @@ static void dc_parse_register(BcParse *p, bool var) { * Parses a dc string. * @param p The parser. */ -static inline void dc_parse_string(BcParse *p) { +static inline void +dc_parse_string(BcParse* p) +{ bc_parse_addString(p); bc_lex_next(&p->l); } @@ -75,8 +78,9 @@ static inline void dc_parse_string(BcParse *p) { * a global. * @param store True if the operation is a store, false otherwise. */ -static void dc_parse_mem(BcParse *p, uchar inst, bool name, bool store) { - +static void +dc_parse_mem(BcParse* p, uchar inst, bool name, bool store) +{ // Push the instruction. bc_parse_push(p, inst); @@ -85,7 +89,8 @@ static void dc_parse_mem(BcParse *p, uchar inst, bool name, bool store) { // Stores use the bc assign infrastructure, but they need to do a swap // first. - if (store) { + if (store) + { bc_parse_push(p, BC_INST_SWAP); bc_parse_push(p, BC_INST_ASSIGN_NO_VAL); } @@ -98,8 +103,9 @@ static void dc_parse_mem(BcParse *p, uchar inst, bool name, bool store) { * @param p The parser. * @param inst The instruction for the condition. */ -static void dc_parse_cond(BcParse *p, uchar inst) { - +static void +dc_parse_cond(BcParse* p, uchar inst) +{ // Push the instruction for the condition and the conditional execution. bc_parse_push(p, inst); bc_parse_push(p, BC_INST_EXEC_COND); @@ -110,7 +116,8 @@ static void dc_parse_cond(BcParse *p, uchar inst) { bc_lex_next(&p->l); // If the next token is an else, parse the else. - if (p->l.t == BC_LEX_KW_ELSE) { + if (p->l.t == BC_LEX_KW_ELSE) + { dc_parse_register(p, true); bc_lex_next(&p->l); } @@ -124,13 +131,14 @@ static void dc_parse_cond(BcParse *p, uchar inst) { * @param t The token to parse. * @param flags The flags that say what is allowed or not. */ -static void dc_parse_token(BcParse *p, BcLexType t, uint8_t flags) { - +static void +dc_parse_token(BcParse* p, BcLexType t, uint8_t flags) +{ uchar inst; bool assign, get_token = false; - switch (t) { - + switch (t) + { case BC_LEX_OP_REL_EQ: case BC_LEX_OP_REL_LE: case BC_LEX_OP_REL_GE: @@ -161,16 +169,18 @@ static void dc_parse_token(BcParse *p, BcLexType t, uint8_t flags) { // This tells us whether or not the neg is for a command or at the // beginning of a number. If it's a command, push it. Otherwise, // fallthrough and parse the number. - if (dc_lex_negCommand(&p->l)) { + if (dc_lex_negCommand(&p->l)) + { bc_parse_push(p, BC_INST_NEG); get_token = true; break; } bc_lex_next(&p->l); + + // Fallthrough. + BC_FALLTHROUGH } - // Fallthrough. - BC_FALLTHROUGH case BC_LEX_NUMBER: { @@ -187,7 +197,9 @@ static void dc_parse_token(BcParse *p, BcLexType t, uint8_t flags) { { // Make sure the read is not recursive. if (BC_ERR(flags & BC_PARSE_NOREAD)) + { bc_parse_err(p, BC_ERR_EXEC_REC_READ); + } else bc_parse_push(p, BC_INST_READ); get_token = true; @@ -243,7 +255,113 @@ static void dc_parse_token(BcParse *p, BcLexType t, uint8_t flags) { break; } - default: + case BC_LEX_EOF: + case BC_LEX_INVALID: +#if BC_ENABLED + case BC_LEX_OP_INC: + case BC_LEX_OP_DEC: +#endif // BC_ENABLED + case BC_LEX_OP_BOOL_NOT: +#if BC_ENABLE_EXTRA_MATH + case BC_LEX_OP_TRUNC: +#endif // BC_ENABLE_EXTRA_MATH + 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: + case BC_LEX_OP_MINUS: +#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_BOOL_OR: + case BC_LEX_OP_BOOL_AND: +#if BC_ENABLED + 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 +#endif // BC_ENABLED + case BC_LEX_NLINE: + case BC_LEX_WHITESPACE: + case BC_LEX_LPAREN: + case BC_LEX_RPAREN: + case BC_LEX_LBRACKET: + case BC_LEX_COMMA: + case BC_LEX_RBRACKET: + case BC_LEX_LBRACE: + case BC_LEX_NAME: + case BC_LEX_RBRACE: +#if BC_ENABLED + case BC_LEX_KW_AUTO: + case BC_LEX_KW_BREAK: + case BC_LEX_KW_CONTINUE: + case BC_LEX_KW_DEFINE: + case BC_LEX_KW_FOR: + case BC_LEX_KW_IF: + case BC_LEX_KW_LIMITS: + case BC_LEX_KW_RETURN: + case BC_LEX_KW_WHILE: + case BC_LEX_KW_HALT: + case BC_LEX_KW_LAST: +#endif // BC_ENABLED + case BC_LEX_KW_IBASE: + 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_LENGTH: + case BC_LEX_KW_PRINT: + case BC_LEX_KW_SQRT: + case BC_LEX_KW_ABS: + case BC_LEX_KW_IS_NUMBER: + case BC_LEX_KW_IS_STRING: +#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_QUIT: +#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: +#if BC_ENABLED + case BC_LEX_KW_GLOBAL_STACKS: +#endif // BC_ENABLED + case BC_LEX_KW_LEADING_ZERO: + case BC_LEX_KW_STREAM: + case BC_LEX_KW_ELSE: + case BC_LEX_EXTENDED_REGISTERS: + case BC_LEX_EQ_NO_REG: + case BC_LEX_EXECUTE: + case BC_LEX_PRINT_STACK: + case BC_LEX_CLEAR_STACK: + case BC_LEX_STACK_LEVEL: + case BC_LEX_DUPLICATE: + case BC_LEX_SWAP: + case BC_LEX_POP: + case BC_LEX_PRINT_POP: + case BC_LEX_NQUIT: + case BC_LEX_EXEC_STACK_LENGTH: + case BC_LEX_SCALE_FACTOR: { // All other tokens should be taken care of by the caller, or they // actually *are* invalid. @@ -254,8 +372,9 @@ static void dc_parse_token(BcParse *p, BcLexType t, uint8_t flags) { if (get_token) bc_lex_next(&p->l); } -void dc_parse_expr(BcParse *p, uint8_t flags) { - +void +dc_parse_expr(BcParse* p, uint8_t flags) +{ BcInst inst; BcLexType t; bool need_expr, have_expr = false; @@ -267,10 +386,11 @@ void dc_parse_expr(BcParse *p, uint8_t flags) { // designed. // While we don't have EOF... - while ((t = p->l.t) != BC_LEX_EOF) { - + while ((t = p->l.t) != BC_LEX_EOF) + { // Eat newline. - if (t == BC_LEX_NLINE) { + if (t == BC_LEX_NLINE) + { bc_lex_next(&p->l); continue; } @@ -281,7 +401,8 @@ void dc_parse_expr(BcParse *p, uint8_t flags) { // If the instruction is invalid, that means we have to do some harder // parsing. So if not invalid, just push the instruction; otherwise, // parse the token. - if (inst != BC_INST_INVALID) { + if (inst != BC_INST_INVALID) + { bc_parse_push(p, inst); bc_lex_next(&p->l); } @@ -295,14 +416,17 @@ void dc_parse_expr(BcParse *p, uint8_t flags) { // indicate that it is executing a string. if (BC_ERR(need_expr && !have_expr)) bc_err(BC_ERR_EXEC_READ_EXPR); else if (p->l.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL)) + { bc_parse_push(p, BC_INST_POP_EXEC); + } } -void dc_parse_parse(BcParse *p) { - +void +dc_parse_parse(BcParse* p) +{ assert(p != NULL); - BC_SETJMP(exit); + BC_SETJMP_LOCKED(vm, exit); // If we have EOF, someone called this function one too many times. // Otherwise, parse. @@ -311,11 +435,10 @@ void dc_parse_parse(BcParse *p) { exit: - BC_SIG_MAYLOCK; - // Need to reset if there was an error. - if (BC_SIG_EXC) bc_parse_reset(p); + if (BC_SIG_EXC(vm)) bc_parse_reset(p); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); + BC_SIG_MAYLOCK; } #endif // DC_ENABLED diff --git a/contrib/bc/src/file.c b/contrib/bc/src/file.c index 35a4647dfab..697fca8cf29 100644 --- a/contrib/bc/src/file.c +++ b/contrib/bc/src/file.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -44,22 +44,26 @@ #include #include +#if !BC_ENABLE_LINE_LIB + /** * Translates an integer into a string. * @param val The value to translate. * @param buf The return parameter. */ -static void bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH]) +static void +bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH]) { char buf2[BC_FILE_ULL_LENGTH]; size_t i, len; // We need to make sure the entire thing is zeroed. + // NOLINTNEXTLINE memset(buf2, 0, BC_FILE_ULL_LENGTH); // The i = 1 is to ensure that there is a null byte at the end. - for (i = 1; val; ++i) { - + for (i = 1; val; ++i) + { unsigned long long mod = val % 10; buf2[i] = ((char) mod) + '0'; @@ -69,7 +73,10 @@ static void bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH]) len = i; // Since buf2 is reversed, reverse it into buf. - for (i = 0; i < len; ++i) buf[i] = buf2[len - i - 1]; + for (i = 0; i < len; ++i) + { + buf[i] = buf2[len - i - 1]; + } } /** @@ -80,22 +87,27 @@ static void bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH]) * @return A status indicating error or success. We could have a fatal I/O * error or EOF. */ -static BcStatus bc_file_output(int fd, const char *buf, size_t n) { - +static BcStatus +bc_file_output(int fd, const char* buf, size_t n) +{ size_t bytes = 0; sig_atomic_t lock; BC_SIG_TRYLOCK(lock); // While the number of bytes written is less than intended... - while (bytes < n) { - + while (bytes < n) + { // Write. ssize_t written = write(fd, buf + bytes, n - bytes); // Check for error and return, if any. if (BC_ERR(written == -1)) + { + BC_SIG_TRYUNLOCK(lock); + return errno == EPIPE ? BC_STATUS_EOF : BC_STATUS_ERROR_FATAL; + } bytes += (size_t) written; } @@ -105,18 +117,31 @@ static BcStatus bc_file_output(int fd, const char *buf, size_t n) { return BC_STATUS_SUCCESS; } -BcStatus bc_file_flushErr(BcFile *restrict f, BcFlushType type) +#endif // !BC_ENABLE_LINE_LIB + +BcStatus +bc_file_flushErr(BcFile* restrict f, BcFlushType type) { BcStatus s; - // If there is stuff to output... - if (f->len) { + BC_SIG_ASSERT_LOCKED; + +#if BC_ENABLE_LINE_LIB + // Just flush and propagate the error. + if (fflush(f->f) == EOF) s = BC_STATUS_ERROR_FATAL; + else s = BC_STATUS_SUCCESS; + +#else // BC_ENABLE_LINE_LIB + + // If there is stuff to output... + if (f->len) + { #if BC_ENABLE_HISTORY // If history is enabled... - if (BC_TTY) { - + if (BC_TTY) + { // If we have been told to save the extras, and there *are* // extras... if (f->buf[f->len - 1] != '\n' && @@ -126,16 +151,20 @@ BcStatus bc_file_flushErr(BcFile *restrict f, BcFlushType type) size_t i; // Look for the last newline. - for (i = f->len - 2; i < f->len && f->buf[i] != '\n'; --i); + for (i = f->len - 2; i < f->len && f->buf[i] != '\n'; --i) + { + continue; + } i += 1; // Save the extras. - bc_vec_string(&vm.history.extras, f->len - i, f->buf + i); + bc_vec_string(&vm->history.extras, f->len - i, f->buf + i); } // Else clear the extras if told to. - else if (type >= BC_FLUSH_NO_EXTRAS_CLEAR) { - bc_vec_popAll(&vm.history.extras); + else if (type >= BC_FLUSH_NO_EXTRAS_CLEAR) + { + bc_vec_popAll(&vm->history.extras); } } #endif // BC_ENABLE_HISTORY @@ -146,146 +175,272 @@ BcStatus bc_file_flushErr(BcFile *restrict f, BcFlushType type) } else s = BC_STATUS_SUCCESS; +#endif // BC_ENABLE_LINE_LIB + return s; } -void bc_file_flush(BcFile *restrict f, BcFlushType type) { +void +bc_file_flush(BcFile* restrict f, BcFlushType type) +{ + BcStatus s; + sig_atomic_t lock; - BcStatus s = bc_file_flushErr(f, type); + BC_SIG_TRYLOCK(lock); - // If we have an error... - if (BC_ERR(s)) { + s = bc_file_flushErr(f, type); + // If we have an error... + if (BC_ERR(s)) + { // For EOF, set it and jump. - if (s == BC_STATUS_EOF) { - vm.status = (sig_atomic_t) s; + if (s == BC_STATUS_EOF) + { + vm->status = (sig_atomic_t) s; + BC_SIG_TRYUNLOCK(lock); BC_JMP; } + // Make sure to handle non-fatal I/O properly. + else if (!f->errors_fatal) + { + bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); + } // Blow up on fatal error. Okay, not blow up, just quit. - else bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); + else exit(BC_STATUS_ERROR_FATAL); } + + BC_SIG_TRYUNLOCK(lock); } -void bc_file_write(BcFile *restrict f, BcFlushType type, - const char *buf, size_t n) +#if !BC_ENABLE_LINE_LIB + +void +bc_file_write(BcFile* restrict f, BcFlushType type, const char* buf, size_t n) { + sig_atomic_t lock; + + BC_SIG_TRYLOCK(lock); + // If we have enough to flush, do it. - if (n > f->cap - f->len) { + if (n > f->cap - f->len) + { bc_file_flush(f, type); assert(!f->len); } // If the output is large enough to flush by itself, just output it. // Otherwise, put it into the buffer. - if (BC_UNLIKELY(n > f->cap - f->len)) bc_file_output(f->fd, buf, n); - else { + if (BC_UNLIKELY(n > f->cap - f->len)) + { + BcStatus s = bc_file_output(f->fd, buf, n); + + if (BC_ERR(s)) + { + // For EOF, set it and jump. + if (s == BC_STATUS_EOF) + { + vm->status = (sig_atomic_t) s; + BC_SIG_TRYUNLOCK(lock); + BC_JMP; + } + // Make sure to handle non-fatal I/O properly. + else if (!f->errors_fatal) + { + bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); + } + // Blow up on fatal error. Okay, not blow up, just quit. + else exit(BC_STATUS_ERROR_FATAL); + } + } + else + { + // NOLINTNEXTLINE memcpy(f->buf + f->len, buf, n); f->len += n; } + + BC_SIG_TRYUNLOCK(lock); } -void bc_file_printf(BcFile *restrict f, const char *fmt, ...) +#endif // BC_ENABLE_LINE_LIB + +void +bc_file_printf(BcFile* restrict f, const char* fmt, ...) { va_list args; + sig_atomic_t lock; + + BC_SIG_TRYLOCK(lock); va_start(args, fmt); bc_file_vprintf(f, fmt, args); va_end(args); -} - -void bc_file_vprintf(BcFile *restrict f, const char *fmt, va_list args) { - char *percent; - const char *ptr = fmt; - char buf[BC_FILE_ULL_LENGTH]; - - // This is a poor man's printf(). While I could look up algorithms to make - // it as fast as possible, and should when I write the standard library for - // a new language, for bc, outputting is not the bottleneck. So we cheese it - // for now. - - // Find each percent sign. - while ((percent = strchr(ptr, '%')) != NULL) { + BC_SIG_TRYUNLOCK(lock); +} - char c; +void +bc_file_vprintf(BcFile* restrict f, const char* fmt, va_list args) +{ + BC_SIG_ASSERT_LOCKED; - // If the percent sign is not where we are, write what's inbetween to - // the buffer. - if (percent != ptr) { - size_t len = (size_t) (percent - ptr); - bc_file_write(f, bc_flush_none, ptr, len); +#if BC_ENABLE_LINE_LIB + + { + int r; + + // This mess is to silence a warning. +#if BC_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#endif // BC_CLANG + r = vfprintf(f->f, fmt, args); +#if BC_CLANG +#pragma clang diagnostic pop +#endif // BC_CLANG + + // Just print and propagate the error. + if (BC_ERR(r < 0)) + { + // Make sure to handle non-fatal I/O properly. + if (!f->errors_fatal) + { + bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); + } + else + { + exit(BC_STATUS_ERROR_FATAL); + } } + } - c = percent[1]; +#else // BC_ENABLE_LINE_LIB - // We only parse some format specifiers, the ones bc uses. If you add - // more, you need to make sure to add them here. - if (c == 'c') { + { + char* percent; + const char* ptr = fmt; + char buf[BC_FILE_ULL_LENGTH]; - uchar uc = (uchar) va_arg(args, int); + // This is a poor man's printf(). While I could look up algorithms to + // make it as fast as possible, and should when I write the standard + // library for a new language, for bc, outputting is not the bottleneck. + // So we cheese it for now. - bc_file_putchar(f, bc_flush_none, uc); - } - else if (c == 's') { + // Find each percent sign. + while ((percent = strchr(ptr, '%')) != NULL) + { + char c; - char *s = va_arg(args, char*); + // If the percent sign is not where we are, write what's inbetween + // to the buffer. + if (percent != ptr) + { + size_t len = (size_t) (percent - ptr); + bc_file_write(f, bc_flush_none, ptr, len); + } - bc_file_puts(f, bc_flush_none, s); - } -#if BC_DEBUG_CODE - // We only print signed integers in debug code. - else if (c == 'd') { + c = percent[1]; - int d = va_arg(args, int); + // We only parse some format specifiers, the ones bc uses. If you + // add more, you need to make sure to add them here. + if (c == 'c') + { + uchar uc = (uchar) va_arg(args, int); - // Take care of negative. Let's not worry about overflow. - if (d < 0) { - bc_file_putchar(f, bc_flush_none, '-'); - d = -d; + bc_file_putchar(f, bc_flush_none, uc); } + else if (c == 's') + { + char* s = va_arg(args, char*); - // Either print 0 or translate and print. - if (!d) bc_file_putchar(f, bc_flush_none, '0'); - else { - bc_file_ultoa((unsigned long long) d, buf); - bc_file_puts(f, bc_flush_none, buf); + bc_file_puts(f, bc_flush_none, s); } - } -#endif // BC_DEBUG_CODE - else { - - unsigned long long ull; - - // These are the ones that it expects from here. Fortunately, all of - // these are unsigned types, so they can use the same code, more or - // less. - assert((c == 'l' || c == 'z') && percent[2] == 'u'); - - if (c == 'z') ull = (unsigned long long) va_arg(args, size_t); - else ull = (unsigned long long) va_arg(args, unsigned long); - - // Either print 0 or translate and print. - if (!ull) bc_file_putchar(f, bc_flush_none, '0'); - else { - bc_file_ultoa(ull, buf); - bc_file_puts(f, bc_flush_none, buf); +#if BC_DEBUG + // We only print signed integers in debug code. + else if (c == 'd') + { + int d = va_arg(args, int); + + // Take care of negative. Let's not worry about overflow. + if (d < 0) + { + bc_file_putchar(f, bc_flush_none, '-'); + d = -d; + } + + // Either print 0 or translate and print. + if (!d) bc_file_putchar(f, bc_flush_none, '0'); + else + { + bc_file_ultoa((unsigned long long) d, buf); + bc_file_puts(f, bc_flush_none, buf); + } } +#endif // BC_DEBUG + else + { + unsigned long long ull; + + // These are the ones that it expects from here. Fortunately, + // all of these are unsigned types, so they can use the same + // code, more or less. + assert((c == 'l' || c == 'z') && percent[2] == 'u'); + + if (c == 'z') ull = (unsigned long long) va_arg(args, size_t); + else ull = (unsigned long long) va_arg(args, unsigned long); + + // Either print 0 or translate and print. + if (!ull) bc_file_putchar(f, bc_flush_none, '0'); + else + { + bc_file_ultoa(ull, buf); + bc_file_puts(f, bc_flush_none, buf); + } + } + + // Increment to the next spot after the specifier. + ptr = percent + 2 + (c == 'l' || c == 'z'); } - // Increment to the next spot after the specifier. - ptr = percent + 2 + (c == 'l' || c == 'z'); + // If we get here, there are no more percent signs, so we just output + // whatever is left. + if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr); } - // If we get here, there are no more percent signs, so we just output - // whatever is left. - if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr); +#endif // BC_ENABLE_LINE_LIB } -void bc_file_puts(BcFile *restrict f, BcFlushType type, const char *str) { +void +bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str) +{ +#if BC_ENABLE_LINE_LIB + // This is used because of flushing issues with using bc_file_write() when + // bc is using a line library. It's also using printf() because puts() + // writes a newline. + bc_file_printf(f, "%s", str); +#else // BC_ENABLE_LINE_LIB bc_file_write(f, type, str, strlen(str)); +#endif // BC_ENABLE_LINE_LIB } -void bc_file_putchar(BcFile *restrict f, BcFlushType type, uchar c) { +void +bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c) +{ + sig_atomic_t lock; + + BC_SIG_TRYLOCK(lock); + +#if BC_ENABLE_LINE_LIB + + if (BC_ERR(fputc(c, f->f) == EOF)) + { + // This is here to prevent a stack overflow from unbounded recursion. + if (f->f == stderr) exit(BC_STATUS_ERROR_FATAL); + + bc_err(BC_ERR_FATAL_IO_ERR); + } + +#else // BC_ENABLE_LINE_LIB if (f->len == f->cap) bc_file_flush(f, type); @@ -293,19 +448,41 @@ void bc_file_putchar(BcFile *restrict f, BcFlushType type, uchar c) { f->buf[f->len] = (char) c; f->len += 1; + +#endif // BC_ENABLE_LINE_LIB + + BC_SIG_TRYUNLOCK(lock); } -void bc_file_init(BcFile *f, int fd, char *buf, size_t cap) { +#if BC_ENABLE_LINE_LIB +void +bc_file_init(BcFile* f, FILE* file, bool errors_fatal) +{ + BC_SIG_ASSERT_LOCKED; + f->f = file; + f->errors_fatal = errors_fatal; +} + +#else // BC_ENABLE_LINE_LIB + +void +bc_file_init(BcFile* f, int fd, char* buf, size_t cap, bool errors_fatal) +{ BC_SIG_ASSERT_LOCKED; f->fd = fd; f->buf = buf; f->len = 0; f->cap = cap; + f->errors_fatal = errors_fatal; } -void bc_file_free(BcFile *f) { +#endif // BC_ENABLE_LINE_LIB + +void +bc_file_free(BcFile* f) +{ BC_SIG_ASSERT_LOCKED; bc_file_flush(f, bc_flush_none); } diff --git a/contrib/bc/src/history.c b/contrib/bc/src/history.c index b5ba0758075..32a19f71d77 100644 --- a/contrib/bc/src/history.c +++ b/contrib/bc/src/history.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -144,6 +144,269 @@ #if BC_ENABLE_HISTORY +#if BC_ENABLE_EDITLINE + +#include +#include +#include + +#include +#include + +sigjmp_buf bc_history_jmpbuf; +volatile sig_atomic_t bc_history_inlinelib; + +static char* bc_history_prompt; +static char bc_history_no_prompt[] = ""; +static HistEvent bc_history_event; +static bool bc_history_use_prompt; + +static char* +bc_history_promptFunc(EditLine* el) +{ + BC_UNUSED(el); + return BC_PROMPT && bc_history_use_prompt ? bc_history_prompt : + bc_history_no_prompt; +} + +void +bc_history_init(BcHistory* h) +{ + BcVec v; + char* home; + + home = getenv("HOME"); + + // This will hold the true path to the editrc. + bc_vec_init(&v, 1, BC_DTOR_NONE); + + // Initialize the path to the editrc. This is done manually because the + // libedit I used to test was failing with a NULL argument for the path, + // which was supposed to automatically do $HOME/.editrc. But it was failing, + // so I set it manually. + if (home == NULL) + { + bc_vec_string(&v, bc_history_editrc_len - 1, bc_history_editrc + 1); + } + else + { + bc_vec_string(&v, strlen(home), home); + bc_vec_concat(&v, bc_history_editrc); + } + + h->hist = history_init(); + if (BC_ERR(h->hist == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); + + h->el = el_init(vm->name, stdin, stdout, stderr); + if (BC_ERR(h->el == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); + + // I want history and a prompt. + history(h->hist, &bc_history_event, H_SETSIZE, 100); + history(h->hist, &bc_history_event, H_SETUNIQUE, 1); + el_set(h->el, EL_EDITOR, "emacs"); + el_set(h->el, EL_HIST, history, h->hist); + el_set(h->el, EL_PROMPT, bc_history_promptFunc); + + // I also want to get the user's .editrc. + el_source(h->el, v.v); + + bc_vec_free(&v); + + h->badTerm = false; + bc_history_prompt = NULL; +} + +void +bc_history_free(BcHistory* h) +{ + if (BC_PROMPT && bc_history_prompt != NULL) free(bc_history_prompt); + el_end(h->el); + history_end(h->hist); +} + +BcStatus +bc_history_line(BcHistory* h, BcVec* vec, const char* prompt) +{ + BcStatus s = BC_STATUS_SUCCESS; + const char* line; + int len; + + BC_SIG_LOCK; + + // If the jump happens here, then a SIGINT occurred. + if (sigsetjmp(bc_history_jmpbuf, 0)) + { + bc_vec_string(vec, 1, "\n"); + goto end; + } + + // This is so the signal handler can handle line libraries properly. + bc_history_inlinelib = 1; + + if (BC_PROMPT) + { + // Make sure to set the prompt. + if (bc_history_prompt != NULL) + { + if (strcmp(bc_history_prompt, prompt)) + { + free(bc_history_prompt); + bc_history_prompt = bc_vm_strdup(prompt); + } + } + else bc_history_prompt = bc_vm_strdup(prompt); + } + + bc_history_use_prompt = true; + + line = NULL; + len = -1; + errno = EINTR; + + // Get the line. + // + // XXX: Why have a macro here? Because macOS needs to be special. Honestly, + // it's starting to feel special like Windows at this point. Anyway, the + // second SIGWINCH signal of multiple will return a valid line length on + // macOS, so we need to allow for that on macOS. However, FreeBSD's editline + // is different and will mess up the terminal if we do it that way. + // + // There is one limitation with this, however: Ctrl+D won't work on macOS. + // But it's because of macOS that this problem exists, and I can't really do + // anything about it. So macOS should fix their broken editline; once they + // do, I'll fix Ctrl+D on macOS. + while (BC_HISTORY_INVALID_LINE(line, len)) + { + line = el_gets(h->el, &len); + bc_history_use_prompt = false; + } + + // If there is no line... + if (BC_ERR(line == NULL)) + { + // If this is true, there was an error. Otherwise, it's just EOF. + if (len == -1) + { + if (errno == ENOMEM) bc_err(BC_ERR_FATAL_ALLOC_ERR); + bc_err(BC_ERR_FATAL_IO_ERR); + } + else + { + bc_file_printf(&vm->fout, "\n"); + s = BC_STATUS_EOF; + } + } + // If there is a line... + else + { + bc_vec_string(vec, strlen(line), line); + + if (strcmp(line, "") && strcmp(line, "\n")) + { + history(h->hist, &bc_history_event, H_ENTER, line); + } + + s = BC_STATUS_SUCCESS; + } + +end: + + bc_history_inlinelib = 0; + + BC_SIG_UNLOCK; + + return s; +} + +#else // BC_ENABLE_EDITLINE + +#if BC_ENABLE_READLINE + +#include +#include +#include + +#include +#include + +sigjmp_buf bc_history_jmpbuf; +volatile sig_atomic_t bc_history_inlinelib; + +void +bc_history_init(BcHistory* h) +{ + h->line = NULL; + h->badTerm = false; + + // I want no tab completion. + rl_bind_key('\t', rl_insert); +} + +void +bc_history_free(BcHistory* h) +{ + if (h->line != NULL) free(h->line); +} + +BcStatus +bc_history_line(BcHistory* h, BcVec* vec, const char* prompt) +{ + BcStatus s = BC_STATUS_SUCCESS; + size_t len; + + BC_SIG_LOCK; + + // If the jump happens here, then a SIGINT occurred. + if (sigsetjmp(bc_history_jmpbuf, 0)) + { + bc_vec_string(vec, 1, "\n"); + goto end; + } + + // This is so the signal handler can handle line libraries properly. + bc_history_inlinelib = 1; + + // Get rid of the last line. + if (h->line != NULL) + { + free(h->line); + h->line = NULL; + } + + // Get the line. + h->line = readline(BC_PROMPT ? prompt : ""); + + // If there was a line, add it to the history. Otherwise, just return an + // empty line. Oh, and NULL actually means EOF. + if (h->line != NULL && h->line[0]) + { + add_history(h->line); + + len = strlen(h->line); + + bc_vec_expand(vec, len + 2); + + bc_vec_string(vec, len, h->line); + bc_vec_concat(vec, "\n"); + } + else if (h->line == NULL) + { + bc_file_printf(&vm->fout, "%s\n", "^D"); + s = BC_STATUS_EOF; + } + else bc_vec_string(vec, 1, "\n"); + +end: + + bc_history_inlinelib = 0; + + BC_SIG_UNLOCK; + + return s; +} + +#else // BC_ENABLE_READLINE + #include #include #include @@ -175,7 +438,7 @@ BcFile bc_history_debug_fp; /// A buffer for the above file. -char *bc_history_debug_buf; +char* bc_history_debug_buf; #endif // BC_DEBUG_CODE @@ -184,12 +447,13 @@ char *bc_history_debug_buf; * @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) { - +static bool +bc_history_wchar(uint32_t cp) +{ size_t i; - for (i = 0; i < bc_history_wchars_len; ++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. @@ -197,7 +461,9 @@ static bool bc_history_wchar(uint32_t cp) { // Test this range. if (bc_history_wchars[i][0] <= cp && cp <= bc_history_wchars[i][1]) + { return true; + } } return false; @@ -208,12 +474,13 @@ static bool bc_history_wchar(uint32_t cp) { * @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) { - +static bool +bc_history_comboChar(uint32_t cp) +{ size_t i; - for (i = 0; i < bc_history_combo_chars_len; ++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; @@ -228,9 +495,14 @@ static bool bc_history_comboChar(uint32_t cp) { * @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) { +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); + for (pos -= 1; pos < end && (buf[pos] & 0xC0) == 0x80; --pos) + { + continue; + } return end - (pos >= end ? 0 : pos); } @@ -241,47 +513,53 @@ static size_t bc_history_prevCharLen(const char *buf, size_t pos) { * @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) { - +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) { + if ((byte & 0x80) == 0) + { *cp = byte; return 1; } - else if ((byte & 0xE0) == 0xC0) { - - if (len >= 2) { + else if ((byte & 0xE0) == 0xC0) + { + if (len >= 2) + { *cp = (((uint32_t) (s[0] & 0x1F)) << 6) | - ((uint32_t) (s[1] & 0x3F)); + ((uint32_t) (s[1] & 0x3F)); return 2; } } - else if ((byte & 0xF0) == 0xE0) { - - if (len >= 3) { + 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)); + (((uint32_t) (s[1] & 0x3F)) << 6) | + ((uint32_t) (s[2] & 0x3F)); return 3; } } - else if ((byte & 0xF8) == 0xF0) { - - if (len >= 4) { + 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)); + (((uint32_t) (s[1] & 0x3F)) << 12) | + (((uint32_t) (s[2] & 0x3F)) << 6) | + ((uint32_t) (s[3] & 0x3F)); return 4; } } - else { + else + { *cp = 0xFFFD; return 1; } @@ -300,20 +578,22 @@ static size_t bc_history_codePoint(const char *s, size_t len, uint32_t *cp) { * @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) +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)) { - + if (bc_history_comboChar(cp)) + { BC_UNREACHABLE +#if !BC_CLANG if (col_len != NULL) *col_len = 0; return 0; +#endif // !BC_CLANG } // Store the width of the character on screen. @@ -322,8 +602,8 @@ static size_t bc_history_nextLen(const char *buf, size_t buf_len, pos += len; // Find the first non-combining character. - while (pos < buf_len) { - + while (pos < buf_len) + { len = bc_history_codePoint(buf + pos, buf_len - pos, &cp); if (!bc_history_comboChar(cp)) return pos - beg; @@ -340,13 +620,14 @@ static size_t bc_history_nextLen(const char *buf, size_t buf_len, * @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) { - +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) { - + while (pos > 0) + { uint32_t cp; size_t len = bc_history_prevCharLen(buf, pos); @@ -361,7 +642,9 @@ static size_t bc_history_prevLen(const char *buf, size_t pos) { BC_UNREACHABLE +#if !BC_CLANG return 0; +#endif // BC_CLANG } /** @@ -371,18 +654,21 @@ static size_t bc_history_prevLen(const char *buf, size_t pos) { * @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) { - +static ssize_t +bc_history_read(char* buf, size_t n) +{ ssize_t ret; - BC_SIG_LOCK; + BC_SIG_ASSERT_LOCKED; #ifndef _WIN32 - do { + do + { // We don't care about being interrupted. ret = read(STDIN_FILENO, buf, n); - } while (ret == EINTR); + } + while (ret == EINTR); #else // _WIN32 @@ -392,12 +678,10 @@ static ssize_t bc_history_read(char *buf, size_t n) { good = ReadConsole(hn, buf, (DWORD) n, &read, NULL); - ret = (read != n) ? -1 : 1; + ret = (read != n || !good) ? -1 : 1; #endif // _WIN32 - BC_SIG_UNLOCK; - return ret; } @@ -409,49 +693,68 @@ static ssize_t bc_history_read(char *buf, size_t n) { * @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) +static BcStatus +bc_history_readCode(char* buf, size_t buf_len, uint32_t* cp, size_t* nread) { ssize_t n; + uchar byte; assert(buf_len >= 1); + BC_SIG_LOCK; + // Read a byte. n = bc_history_read(buf, 1); + + BC_SIG_UNLOCK; + if (BC_ERR(n <= 0)) goto err; // Get the byte. - uchar byte = ((uchar*) buf)[0]; + 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) { - + if ((byte & 0x80) != 0) + { + if ((byte & 0xE0) == 0xC0) + { assert(buf_len >= 2); + BC_SIG_LOCK; + n = bc_history_read(buf + 1, 1); + BC_SIG_UNLOCK; + if (BC_ERR(n <= 0)) goto err; } - else if ((byte & 0xF0) == 0xE0) { - + else if ((byte & 0xF0) == 0xE0) + { assert(buf_len >= 3); + BC_SIG_LOCK; + n = bc_history_read(buf + 1, 2); + BC_SIG_UNLOCK; + if (BC_ERR(n <= 0)) goto err; } - else if ((byte & 0xF8) == 0xF0) { - + else if ((byte & 0xF8) == 0xF0) + { assert(buf_len >= 3); + BC_SIG_LOCK; + n = bc_history_read(buf + 1, 3); + BC_SIG_UNLOCK; + if (BC_ERR(n <= 0)) goto err; } - else { + else + { n = -1; goto err; } @@ -477,13 +780,14 @@ static BcStatus bc_history_readCode(char *buf, size_t buf_len, * @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) { - +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) { - + while (off < pos && off < buf_len) + { size_t col_len, len; len = bc_history_nextLen(buf, buf_len, off, &col_len); @@ -500,16 +804,19 @@ static size_t bc_history_colPos(const char *buf, size_t buf_len, size_t pos) { * not able to understand basic escape sequences. * @return True if the terminal is a bad terminal. */ -static inline bool bc_history_isBadTerm(void) { - +static inline bool +bc_history_isBadTerm(void) +{ size_t i; bool ret = false; - char *term = bc_vm_getenv("TERM"); + 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); @@ -520,8 +827,9 @@ static inline bool bc_history_isBadTerm(void) { * Enables raw mode (1960's black magic). * @param h The history data. */ -static void bc_history_enableRaw(BcHistory *h) { - +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(). @@ -536,7 +844,9 @@ static void bc_history_enableRaw(BcHistory *h) { BC_SIG_LOCK; if (BC_ERR(tcgetattr(STDIN_FILENO, &h->orig_termios) == -1)) + { bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); + } BC_SIG_UNLOCK; @@ -562,9 +872,11 @@ static void bc_history_enableRaw(BcHistory *h) { BC_SIG_LOCK; // Put terminal in raw mode after flushing. - do { + do + { err = tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); - } while (BC_ERR(err < 0) && errno == EINTR); + } + while (BC_ERR(err < 0) && errno == EINTR); BC_SIG_UNLOCK; @@ -578,8 +890,9 @@ static void bc_history_enableRaw(BcHistory *h) { * Disables raw mode. * @param h The history data. */ -static void bc_history_disableRaw(BcHistory *h) { - +static void +bc_history_disableRaw(BcHistory* h) +{ sig_atomic_t lock; if (!h->rawMode) return; @@ -588,7 +901,9 @@ static void bc_history_disableRaw(BcHistory *h) { #ifndef _WIN32 if (BC_ERR(tcsetattr(STDIN_FILENO, TCSAFLUSH, &h->orig_termios) != -1)) + { h->rawMode = false; + } #endif // _WIN32 BC_SIG_TRYUNLOCK(lock); @@ -600,18 +915,23 @@ static void bc_history_disableRaw(BcHistory *h) { * cursor. * @return The horizontal cursor position. */ -static size_t bc_history_cursorPos(void) { - +static size_t +bc_history_cursorPos(void) +{ char buf[BC_HIST_SEQ_SIZE]; - char *ptr, *ptr2; + char* ptr; + char* ptr2; size_t cols, rows, i; + BC_SIG_ASSERT_LOCKED; + // Report cursor location. - bc_file_write(&vm.fout, bc_flush_none, "\x1b[6n", 4); - bc_file_flush(&vm.fout, bc_flush_none); + 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) { + for (i = 0; i < sizeof(buf) - 1; ++i) + { if (bc_history_read(buf + i, 1) != 1 || buf[i] == 'R') break; } @@ -641,21 +961,19 @@ static size_t bc_history_cursorPos(void) { * if it fails. * @return The number of columns in the terminal. */ -static size_t bc_history_columns(void) { +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)) { + ret = ioctl(vm->fout.fd, TIOCGWINSZ, &ws); + if (BC_ERR(ret == -1 || !ws.ws_col)) + { // Calling ioctl() failed. Try to query the terminal itself. size_t start, cols; @@ -664,15 +982,16 @@ static size_t bc_history_columns(void) { 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); + 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); + if (cols > start) + { + bc_file_printf(&vm->fout, "\x1b[%zuD", cols - start); + bc_file_flush(&vm->fout, bc_flush_none); } return cols; @@ -685,7 +1004,9 @@ static size_t bc_history_columns(void) { CONSOLE_SCREEN_BUFFER_INFO csbi; if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) + { return 80; + } return ((size_t) (csbi.srWindow.Right)) - csbi.srWindow.Left + 1; @@ -699,14 +1020,18 @@ static size_t bc_history_columns(void) { * @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) { - +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++]; + while (off < plen) + { + buf[buf_len++] = prompt[off++]; + } return bc_history_colPos(buf, buf_len, buf_len); } @@ -716,16 +1041,19 @@ static size_t bc_history_promptColLen(const char *prompt, size_t plen) { * cursor position, and number of columns of the terminal. * @param h The history data. */ -static void bc_history_refresh(BcHistory *h) { - +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); + BC_SIG_ASSERT_LOCKED; - // Get to the prompt column position from the left. - while(h->pcol + bc_history_colPos(buf, len, pos) >= h->cols) { + 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; @@ -735,15 +1063,17 @@ static void bc_history_refresh(BcHistory *h) { // 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); + 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) { - + if (h->extras.len > 1) + { extras_len = h->extras.len - 1; bc_vec_grow(&h->buf, extras_len); @@ -751,28 +1081,30 @@ static void bc_history_refresh(BcHistory *h) { len += extras_len; pos += extras_len; - bc_file_write(&vm.fout, bc_flush_none, h->extras.v, 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); + 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); + 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); + 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); + if (pos >= h->buf.len - extras_len) bc_vec_grow(&h->buf, pos + extras_len); - // Move cursor to original position. + // Move cursor to original position. Do NOT move the putchar of '\r' to the + // printf with colpos. That causes a bug where the cursor will go to the end + // of the line when there is no prompt. + bc_file_putchar(&vm->fout, bc_flush_none, '\r'); 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); + if (colpos) bc_file_printf(&vm->fout, "\x1b[%zuC", colpos); - bc_file_flush(&vm.fout, bc_flush_none); + bc_file_flush(&vm->fout, bc_flush_none); } /** @@ -781,13 +1113,16 @@ static void bc_history_refresh(BcHistory *h) { * @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) +static void +bc_history_edit_insert(BcHistory* h, const char* cbuf, size_t clen) { + BC_SIG_ASSERT_LOCKED; + bc_vec_grow(&h->buf, clen); // If we are at the end of the line... - if (h->pos == BC_HIST_BUF_LEN(h)) { - + if (h->pos == BC_HIST_BUF_LEN(h)) + { size_t colpos = 0, len; // Copy into the buffer. @@ -804,16 +1139,16 @@ static void bc_history_edit_insert(BcHistory *h, const char *cbuf, size_t clen) colpos += bc_history_colPos(h->buf.v, len, len); // Do we have the trivial case? - if (colpos < h->cols) { - + 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); + bc_file_write(&vm->fout, bc_flush_none, cbuf, clen); + bc_file_flush(&vm->fout, bc_flush_none); } else bc_history_refresh(h); } - else { - + else + { // Amount that we need to move. size_t amt = BC_HIST_BUF_LEN(h) - h->pos; @@ -834,7 +1169,10 @@ static void bc_history_edit_insert(BcHistory *h, const char *cbuf, size_t clen) * Moves the cursor to the left. * @param h The history data. */ -static void bc_history_edit_left(BcHistory *h) { +static void +bc_history_edit_left(BcHistory* h) +{ + BC_SIG_ASSERT_LOCKED; // Stop at the left end. if (h->pos <= 0) return; @@ -847,8 +1185,11 @@ static void bc_history_edit_left(BcHistory *h) { /** * Moves the cursor to the right. * @param h The history data. -*/ -static void bc_history_edit_right(BcHistory *h) { + */ +static void +bc_history_edit_right(BcHistory* h) +{ + BC_SIG_ASSERT_LOCKED; // Stop at the right end. if (h->pos == BC_HIST_BUF_LEN(h)) return; @@ -862,16 +1203,25 @@ static void bc_history_edit_right(BcHistory *h) { * Moves the cursor to the end of the current word. * @param h The history data. */ -static void bc_history_edit_wordEnd(BcHistory *h) { - +static void +bc_history_edit_wordEnd(BcHistory* h) +{ size_t len = BC_HIST_BUF_LEN(h); + BC_SIG_ASSERT_LOCKED; + // 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; + 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); } @@ -880,16 +1230,25 @@ static void bc_history_edit_wordEnd(BcHistory *h) { * Moves the cursor to the start of the current word. * @param h The history data. */ -static void bc_history_edit_wordStart(BcHistory *h) { - +static void +bc_history_edit_wordStart(BcHistory* h) +{ size_t len = BC_HIST_BUF_LEN(h); + BC_SIG_ASSERT_LOCKED; + // 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; + 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); } @@ -898,7 +1257,10 @@ static void bc_history_edit_wordStart(BcHistory *h) { * Moves the cursor to the start of the line. * @param h The history data. */ -static void bc_history_edit_home(BcHistory *h) { +static void +bc_history_edit_home(BcHistory* h) +{ + BC_SIG_ASSERT_LOCKED; // Stop at the beginning. if (!h->pos) return; @@ -912,7 +1274,10 @@ static void bc_history_edit_home(BcHistory *h) { * Moves the cursor to the end of the line. * @param h The history data. */ -static void bc_history_edit_end(BcHistory *h) { +static void +bc_history_edit_end(BcHistory* h) +{ + BC_SIG_ASSERT_LOCKED; // Stop at the end of the line. if (h->pos == BC_HIST_BUF_LEN(h)) return; @@ -928,15 +1293,17 @@ static void bc_history_edit_end(BcHistory *h) { * @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) { +static void +bc_history_edit_next(BcHistory* h, bool dir) +{ + const char* dup; + const char* str; - const char *dup, *str; + BC_SIG_ASSERT_LOCKED; // 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 = ""; @@ -944,17 +1311,17 @@ static void bc_history_edit_next(BcHistory *h, bool dir) { // 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) { + if (h->idx == SIZE_MAX) + { h->idx = 0; return; } - else if (h->idx >= h->history.len) { + else if (h->idx >= h->history.len) + { h->idx = h->history.len - 1; return; } @@ -976,10 +1343,13 @@ static void bc_history_edit_next(BcHistory *h, bool dir) { * position. Basically, this is what happens with the "Delete" keyboard key. * @param h The history data. */ -static void bc_history_edit_delete(BcHistory *h) { - +static void +bc_history_edit_delete(BcHistory* h) +{ size_t chlen, len = BC_HIST_BUF_LEN(h); + BC_SIG_ASSERT_LOCKED; + // If there is no character, skip. if (!len || h->pos >= len) return; @@ -1001,10 +1371,13 @@ static void bc_history_edit_delete(BcHistory *h) { * space. Basically, this is what happens with the "Backspace" keyboard key. * @param h The history data. */ -static void bc_history_edit_backspace(BcHistory *h) { - +static void +bc_history_edit_backspace(BcHistory* h) +{ size_t chlen, len = BC_HIST_BUF_LEN(h); + BC_SIG_ASSERT_LOCKED; + // If there are no characters, skip. if (!h->pos || !len) return; @@ -1027,16 +1400,25 @@ static void bc_history_edit_backspace(BcHistory *h) { * current word. * @param h The history data. */ -static void bc_history_edit_deletePrevWord(BcHistory *h) { - +static void +bc_history_edit_deletePrevWord(BcHistory* h) +{ size_t diff, old_pos = h->pos; + BC_SIG_ASSERT_LOCKED; + // 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; + 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; + } // Get the difference in position. diff = old_pos - h->pos; @@ -1055,16 +1437,25 @@ static void bc_history_edit_deletePrevWord(BcHistory *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) { - +static void +bc_history_edit_deleteNextWord(BcHistory* h) +{ size_t next_end = h->pos, len = BC_HIST_BUF_LEN(h); + BC_SIG_ASSERT_LOCKED; + // 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; + while (next_end < len && isspace(h->buf.v[next_end])) + { + next_end += 1; + } + while (next_end < len && !isspace(h->buf.v[next_end])) + { + next_end += 1; + } // Move the stuff into position. memmove(h->buf.v + h->pos, h->buf.v + next_end, len - next_end); @@ -1079,11 +1470,17 @@ static void bc_history_edit_deleteNextWord(BcHistory *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) { - +static void +bc_history_swap(BcHistory* h) +{ size_t pcl, ncl; char auxb[5]; + BC_SIG_ASSERT_LOCKED; + + // If there are no characters, skip. + if (!h->pos) return; + // 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); @@ -1091,8 +1488,8 @@ static void bc_history_swap(BcHistory *h) { // 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) { - + 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); @@ -1110,8 +1507,9 @@ static void bc_history_swap(BcHistory *h) { * @param h The history data. * @param sig The signal to raise. */ -static void bc_history_raise(BcHistory *h, int sig) { - +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); @@ -1122,54 +1520,91 @@ static void bc_history_raise(BcHistory *h, int sig) { * escape codes; otherwise, it will be confusing. * @param h The history data. */ -static void bc_history_escape(BcHistory *h) { - +static void +bc_history_escape(BcHistory* h) +{ char c, seq[3]; + BC_SIG_ASSERT_LOCKED; + // 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 != '[' && 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 { - + 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 == '[') { - + if (c == '[') + { c = seq[1]; - if (c >= '0' && c <= '9') { - + 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] == ';') { - + if (seq[2] == '~') + { + switch (c) + { + case '1': + { + bc_history_edit_home(h); + break; + } + + case '3': + { + bc_history_edit_delete(h); + break; + } + + case '4': + { + bc_history_edit_end(h); + break; + } + + default: + { + break; + } + } + } + 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) { - + else + { + switch (c) + { // Up. case 'A': { @@ -1223,10 +1658,10 @@ static void bc_history_escape(BcHistory *h) { } } // ESC O sequences. - else { - - switch (seq[1]) { - + else + { + switch (seq[1]) + { case 'A': { bc_history_edit_next(h, BC_HIST_PREV); @@ -1272,23 +1707,21 @@ static void bc_history_escape(BcHistory *h) { * @param h The history data. * @param line The line to add. */ -static void bc_history_add(BcHistory *h, char *line) { +static void +bc_history_add(BcHistory* h, char* line) +{ + BC_SIG_ASSERT_LOCKED; // If there is something already there... - if (h->history.len) { - + if (h->history.len) + { // Get the previous. - char *s = *((char**) bc_vec_item_rev(&h->history, 0)); + char* s = *((char**) bc_vec_item_rev(&h->history, 0)); // Check for, and discard, duplicates. - if (!strcmp(s, line)) { - - BC_SIG_LOCK; - + if (!strcmp(s, line)) + { free(line); - - BC_SIG_UNLOCK; - return; } } @@ -1301,15 +1734,18 @@ static void bc_history_add(BcHistory *h, char *line) { * because we don't want it allocating. * @param h The history data. */ -static void bc_history_add_empty(BcHistory *h) { +static void +bc_history_add_empty(BcHistory* h) +{ + const char* line = ""; - const char *line = ""; + BC_SIG_ASSERT_LOCKED; // If there is something already there... - if (h->history.len) { - + if (h->history.len) + { // Get the previous. - char *s = *((char**) bc_vec_item_rev(&h->history, 0)); + char* s = *((char**) bc_vec_item_rev(&h->history, 0)); // Check for, and discard, duplicates. if (!s[0]) return; @@ -1322,7 +1758,10 @@ static void bc_history_add_empty(BcHistory *h) { * Resets the history state to nothing. * @param h The history data. */ -static void bc_history_reset(BcHistory *h) { +static void +bc_history_reset(BcHistory* h) +{ + BC_SIG_ASSERT_LOCKED; h->oldcolpos = h->pos = h->idx = 0; h->cols = bc_history_columns(); @@ -1340,10 +1779,13 @@ static void bc_history_reset(BcHistory *h) { * @param h The history data. * @param c The control character to print. */ -static void bc_history_printCtrl(BcHistory *h, unsigned int c) { +static void +bc_history_printCtrl(BcHistory* h, unsigned int c) +{ + char str[3] = { '^', 'A', '\0' }; + const char newline[2] = { '\n', '\0' }; - char str[3] = "^A"; - const char newline[2] = "\n"; + BC_SIG_ASSERT_LOCKED; // Set the correct character. str[1] = (char) (c + 'A' - BC_ACTION_CTRL_A); @@ -1351,19 +1793,19 @@ static void bc_history_printCtrl(BcHistory *h, unsigned int c) { // Concatenate the string. bc_vec_concat(&h->buf, str); + h->pos = BC_HIST_BUF_LEN(h); bc_history_refresh(h); // Pop the string. bc_vec_npop(&h->buf, sizeof(str)); bc_vec_pushByte(&h->buf, '\0'); + h->pos = 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_file_write(&vm->fout, bc_flush_none, newline, sizeof(newline) - 1); bc_history_refresh(h); } } @@ -1376,45 +1818,53 @@ static void bc_history_printCtrl(BcHistory *h, unsigned int c) { * @param prompt The prompt. * @return BC_STATUS_SUCCESS or BC_STATUS_EOF. */ -static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { +static BcStatus +bc_history_edit(BcHistory* h, const char* prompt) +{ + BC_SIG_LOCK; 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); + // bc_file_write(&vm->fout, bc_flush_none, h->extras.v, h->extras.len - 1); // Write the prompt if desired. - if (BC_PROMPT) { - + 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); + 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 (;;) { - + for (;;) + { BcStatus s; char cbuf[32]; unsigned int c = 0; size_t nread = 0; + BC_SIG_UNLOCK; + // Read a code. s = bc_history_readCode(cbuf, sizeof(cbuf), &c, &nread); if (BC_ERR(s)) return s; - switch (c) { + BC_SIG_LOCK; + switch (c) + { case BC_ACTION_LINE_FEED: case BC_ACTION_ENTER: { // Return the line. bc_vec_pop(&h->history); + BC_SIG_UNLOCK; return s; } @@ -1426,27 +1876,27 @@ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { 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; + if (!BC_SIGINT) + { + vm->status = BC_STATUS_QUIT; + BC_SIG_UNLOCK; 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_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: @@ -1455,14 +1905,22 @@ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { break; } -#ifndef _WIN32 - // Act as end-of-file. + // Act as end-of-file or delete-forward-char. case BC_ACTION_CTRL_D: { - bc_history_printCtrl(h, c); - return BC_STATUS_EOF; + // Act as EOF if there's no chacters, otherwise emulate Emacs + // delete next character to match historical gnu bc behavior. + if (BC_HIST_BUF_LEN(h) == 0) + { + bc_history_printCtrl(h, c); + BC_SIG_UNLOCK; + return BC_STATUS_EOF; + } + + bc_history_edit_delete(h); + + break; } -#endif // _WIN32 // Swaps current character with previous. case BC_ACTION_CTRL_T: @@ -1538,7 +1996,7 @@ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { // Clear screen. case BC_ACTION_CTRL_L: { - bc_file_write(&vm.fout, bc_flush_none, "\x1b[H\x1b[2J", 7); + bc_file_write(&vm->fout, bc_flush_none, "\x1b[H\x1b[2J", 7); bc_history_refresh(h); break; } @@ -1562,9 +2020,12 @@ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { 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; + vm->status = BC_STATUS_QUIT; + BC_SIG_UNLOCK; BC_JMP; #endif // _WIN32 } @@ -1575,6 +2036,8 @@ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { } } + BC_SIG_UNLOCK; + return BC_STATUS_SUCCESS; } @@ -1583,7 +2046,9 @@ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { * does not work on Windows. * @param h The history data. */ -static inline bool bc_history_stdinHasData(BcHistory *h) { +static inline bool +bc_history_stdinHasData(BcHistory* h) +{ #ifndef _WIN32 int n; return pselect(1, &h->rdset, NULL, NULL, &h->ts, &h->sigmask) > 0 || @@ -1593,45 +2058,46 @@ static inline bool bc_history_stdinHasData(BcHistory *h) { #endif // _WIN32 } -BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt) { - +BcStatus +bc_history_line(BcHistory* h, BcVec* vec, const char* prompt) +{ BcStatus s; char* line; - assert(vm.fout.len == 0); + assert(vm->fout.len == 0); bc_history_enableRaw(h); - do { - + 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_file_write(&vm->fout, bc_flush_none, "\n", 1); + bc_file_flush(&vm->fout, bc_flush_none); - BC_SIG_LOCK; + BC_SIG_LOCK; + // If we actually have data... + if (h->buf.v[0]) + { // 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); + BC_SIG_UNLOCK; + // 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)); + } + while (!s && bc_history_stdinHasData(h)); assert(!s || s == BC_STATUS_EOF); @@ -1640,13 +2106,17 @@ BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt) { return s; } -void bc_history_string_free(void *str) { - char *s = *((char**) str); +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) { +void +bc_history_init(BcHistory* h) +{ #ifdef _WIN32 HANDLE out, in; @@ -1657,6 +2127,9 @@ void bc_history_init(BcHistory *h) { h->rawMode = false; h->badTerm = bc_history_isBadTerm(); + // Just don't initialize with a bad terminal. + if (h->badTerm) return; + #ifdef _WIN32 h->orig_in = 0; @@ -1665,25 +2138,38 @@ void bc_history_init(BcHistory *h) { 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)) + // Set the code pages. + SetConsoleCP(CP_UTF8); + SetConsoleOutputCP(CP_UTF8); + + // Get the original modes. + if (!GetConsoleMode(in, &h->orig_in) || !GetConsoleMode(out, &h->orig_out)) + { + // Just mark it as a bad terminal on error. + h->badTerm = true; + return; + } + else + { + // Set the new modes. + DWORD reqOut = h->orig_out | ENABLE_VIRTUAL_TERMINAL_PROCESSING; + DWORD reqIn = h->orig_in | ENABLE_VIRTUAL_TERMINAL_INPUT; + + // The input handle requires turning *off* some modes. That's why + // history didn't work before; I didn't read the documentation + // closely enough to see that most modes were automaticall enabled, + // and they need to be turned off. + reqOut |= DISABLE_NEWLINE_AUTO_RETURN | ENABLE_PROCESSED_OUTPUT; + reqIn &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT); + reqIn &= ~(ENABLE_PROCESSED_INPUT); + + // Set the modes; if there was an error, assume a bad terminal and + // quit. + if (!SetConsoleMode(in, reqIn) || !SetConsoleMode(out, reqOut)) { 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 @@ -1702,7 +2188,9 @@ void bc_history_init(BcHistory *h) { #endif // _WIN32 } -void bc_history_free(BcHistory *h) { +void +bc_history_free(BcHistory* h) +{ BC_SIG_ASSERT_LOCKED; #ifndef _WIN32 bc_history_disableRaw(h); @@ -1710,11 +2198,11 @@ void bc_history_free(BcHistory *h) { SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), h->orig_in); SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), h->orig_out); #endif // _WIN32 -#ifndef NDEBUG +#if BC_DEBUG bc_vec_free(&h->buf); bc_vec_free(&h->history); bc_vec_free(&h->extras); -#endif // NDEBUG +#endif // BC_DEBUG } #if BC_DEBUG_CODE @@ -1724,8 +2212,9 @@ void bc_history_free(BcHistory *h) { * scan codes on screen for debugging / development purposes. * @param h The history data. */ -void bc_history_printKeyCodes(BcHistory *h) { - +void +bc_history_printKeyCodes(BcHistory* h) +{ char quit[4]; bc_vm_printf("Linenoise key codes debugging mode.\n" @@ -1735,8 +2224,8 @@ void bc_history_printKeyCodes(BcHistory *h) { bc_history_enableRaw(h); memset(quit, ' ', 4); - while(true) { - + while (true) + { char c; ssize_t nread; @@ -1750,12 +2239,12 @@ void bc_history_printKeyCodes(BcHistory *h) { 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); + 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_file_flush(&vm->fout, bc_flush_none); } bc_history_disableRaw(h); @@ -1763,3 +2252,7 @@ void bc_history_printKeyCodes(BcHistory *h) { #endif // BC_DEBUG_CODE #endif // BC_ENABLE_HISTORY + +#endif // BC_ENABLE_READLINE + +#endif // BC_ENABLE_EDITLINE diff --git a/contrib/bc/src/lang.c b/contrib/bc/src/lang.c index 8532ebc66d7..7968bcbd9df 100644 --- a/contrib/bc/src/lang.c +++ b/contrib/bc/src/lang.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -41,9 +41,10 @@ #include #include -void bc_const_free(void *constant) { - - BcConst *c = constant; +void +bc_const_free(void* constant) +{ + BcConst* c = constant; BC_SIG_ASSERT_LOCKED; @@ -53,8 +54,8 @@ void bc_const_free(void *constant) { } #if BC_ENABLED -void bc_func_insert(BcFunc *f, BcProgram *p, char *name, - BcType type, size_t line) +void +bc_func_insert(BcFunc* f, BcProgram* p, char* name, BcType type, size_t line) { BcAuto a; size_t i, idx; @@ -66,15 +67,15 @@ void bc_func_insert(BcFunc *f, BcProgram *p, char *name, idx = bc_program_search(p, name, type == BC_TYPE_VAR); // Search through all of the other autos/parameters. - for (i = 0; i < f->autos.len; ++i) { - + for (i = 0; i < f->autos.len; ++i) + { // Get the auto. - BcAuto *aptr = bc_vec_item(&f->autos, i); + BcAuto* aptr = bc_vec_item(&f->autos, i); // If they match, barf. - if (BC_ERR(idx == aptr->idx && type == aptr->type)) { - - const char *array = type == BC_TYPE_ARRAY ? "[]" : ""; + if (BC_ERR(idx == aptr->idx && type == aptr->type)) + { + const char* array = type == BC_TYPE_ARRAY ? "[]" : ""; bc_error(BC_ERR_PARSE_DUP_LOCAL, line, name, array); } @@ -89,23 +90,20 @@ void bc_func_insert(BcFunc *f, BcProgram *p, char *name, } #endif // BC_ENABLED -void bc_func_init(BcFunc *f, const char *name) { - +void +bc_func_init(BcFunc* f, const char* name) +{ BC_SIG_ASSERT_LOCKED; assert(f != NULL && name != NULL); bc_vec_init(&f->code, sizeof(uchar), BC_DTOR_NONE); - bc_vec_init(&f->consts, sizeof(BcConst), BC_DTOR_CONST); - - bc_vec_init(&f->strs, sizeof(char*), BC_DTOR_NONE); - #if BC_ENABLED // Only bc needs these things. - if (BC_IS_BC) { - + if (BC_IS_BC) + { bc_vec_init(&f->autos, sizeof(BcAuto), BC_DTOR_NONE); bc_vec_init(&f->labels, sizeof(size_t), BC_DTOR_NONE); @@ -118,20 +116,17 @@ void bc_func_init(BcFunc *f, const char *name) { f->name = name; } -void bc_func_reset(BcFunc *f) { - +void +bc_func_reset(BcFunc* f) +{ BC_SIG_ASSERT_LOCKED; assert(f != NULL); bc_vec_popAll(&f->code); - bc_vec_popAll(&f->consts); - - bc_vec_popAll(&f->strs); - #if BC_ENABLED - if (BC_IS_BC) { - + if (BC_IS_BC) + { bc_vec_popAll(&f->autos); bc_vec_popAll(&f->labels); @@ -141,32 +136,30 @@ void bc_func_reset(BcFunc *f) { #endif // BC_ENABLED } -#ifndef NDEBUG -void bc_func_free(void *func) { - - BcFunc *f = (BcFunc*) func; +#if BC_DEBUG || BC_ENABLE_MEMCHECK +void +bc_func_free(void* func) +{ + BcFunc* f = (BcFunc*) func; BC_SIG_ASSERT_LOCKED; assert(f != NULL); bc_vec_free(&f->code); - bc_vec_free(&f->consts); - - bc_vec_free(&f->strs); - #if BC_ENABLED - if (BC_IS_BC) { - + if (BC_IS_BC) + { bc_vec_free(&f->autos); bc_vec_free(&f->labels); } #endif // BC_ENABLED } -#endif // NDEBUG - -void bc_array_init(BcVec *a, bool nums) { +#endif // BC_DEBUG || BC_ENABLE_MEMCHECK +void +bc_array_init(BcVec* a, bool nums) +{ BC_SIG_ASSERT_LOCKED; // Set the proper vector. @@ -177,8 +170,9 @@ void bc_array_init(BcVec *a, bool nums) { bc_array_expand(a, 1); } -void bc_array_copy(BcVec *d, const BcVec *s) { - +void +bc_array_copy(BcVec* d, const BcVec* s) +{ size_t i; BC_SIG_ASSERT_LOCKED; @@ -196,21 +190,27 @@ void bc_array_copy(BcVec *d, const BcVec *s) { bc_vec_expand(d, s->cap); d->len = s->len; - for (i = 0; i < s->len; ++i) { - - BcNum *dnum, *snum; + for (i = 0; i < s->len; ++i) + { + BcNum* dnum; + BcNum* snum; dnum = bc_vec_item(d, i); snum = bc_vec_item(s, i); // We have to create a copy of the number as well. - if (BC_PROG_STR(snum)) memcpy(dnum, snum, sizeof(BcNum)); + if (BC_PROG_STR(snum)) + { + // NOLINTNEXTLINE + memcpy(dnum, snum, sizeof(BcNum)); + } else bc_num_createCopy(dnum, snum); } } -void bc_array_expand(BcVec *a, size_t len) { - +void +bc_array_expand(BcVec* a, size_t len) +{ assert(a != NULL); BC_SIG_ASSERT_LOCKED; @@ -218,36 +218,41 @@ void bc_array_expand(BcVec *a, size_t len) { bc_vec_expand(a, len); // If this is true, then we have a num array. - if (a->size == sizeof(BcNum) && a->dtor == BC_DTOR_NUM) { - + if (a->size == sizeof(BcNum) && a->dtor == BC_DTOR_NUM) + { // Initialize numbers until we reach the target. - while (len > a->len) { - BcNum *n = bc_vec_pushEmpty(a); + while (len > a->len) + { + BcNum* n = bc_vec_pushEmpty(a); bc_num_init(n, BC_NUM_DEF_SIZE); } } - else { - + else + { assert(a->size == sizeof(BcVec) && a->dtor == BC_DTOR_VEC); // Recursively initialize arrays until we reach the target. Having the // second argument of bc_array_init() be true will activate the base // case, so we're safe. - while (len > a->len) { - BcVec *v = bc_vec_pushEmpty(a); + while (len > a->len) + { + BcVec* v = bc_vec_pushEmpty(a); bc_array_init(v, true); } } } -void bc_result_clear(BcResult *r) { +void +bc_result_clear(BcResult* r) +{ r->t = BC_RESULT_TEMP; bc_num_clear(&r->d.n); } #if DC_ENABLED -void bc_result_copy(BcResult *d, BcResult *src) { - +void +bc_result_copy(BcResult* d, BcResult* src) +{ assert(d != NULL && src != NULL); BC_SIG_ASSERT_LOCKED; @@ -256,8 +261,8 @@ void bc_result_copy(BcResult *d, BcResult *src) { d->t = src->t; // Yes, it depends on what type. - switch (d->t) { - + switch (d->t) + { case BC_RESULT_TEMP: case BC_RESULT_IBASE: case BC_RESULT_SCALE: @@ -274,12 +279,14 @@ void bc_result_copy(BcResult *d, BcResult *src) { case BC_RESULT_ARRAY: case BC_RESULT_ARRAY_ELEM: { + // NOLINTNEXTLINE memcpy(&d->d.loc, &src->d.loc, sizeof(BcLoc)); break; } case BC_RESULT_STR: { + // NOLINTNEXTLINE memcpy(&d->d.n, &src->d.n, sizeof(BcNum)); break; } @@ -295,26 +302,27 @@ void bc_result_copy(BcResult *d, BcResult *src) { case BC_RESULT_VOID: case BC_RESULT_LAST: { -#ifndef NDEBUG +#if BC_DEBUG // We should *never* try copying either of these. abort(); -#endif // NDEBUG +#endif // BC_DEBUG } #endif // BC_ENABLED } } #endif // DC_ENABLED -void bc_result_free(void *result) { - - BcResult *r = (BcResult*) result; +void +bc_result_free(void* result) +{ + BcResult* r = (BcResult*) result; BC_SIG_ASSERT_LOCKED; assert(r != NULL); - switch (r->t) { - + switch (r->t) + { case BC_RESULT_TEMP: case BC_RESULT_IBASE: case BC_RESULT_SCALE: diff --git a/contrib/bc/src/lex.c b/contrib/bc/src/lex.c index f8b32451aef..37e52c33fff 100644 --- a/contrib/bc/src/lex.c +++ b/contrib/bc/src/lex.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -42,20 +42,28 @@ #include #include -void bc_lex_invalidChar(BcLex *l, char c) { +void +bc_lex_invalidChar(BcLex* l, char c) +{ l->t = BC_LEX_INVALID; bc_lex_verr(l, BC_ERR_PARSE_CHAR, c); } -void bc_lex_lineComment(BcLex *l) { +void +bc_lex_lineComment(BcLex* l) +{ l->t = BC_LEX_WHITESPACE; - while (l->i < l->len && l->buf[l->i] != '\n') l->i += 1; + while (l->i < l->len && l->buf[l->i] != '\n') + { + l->i += 1; + } } -void bc_lex_comment(BcLex *l) { - +void +bc_lex_comment(BcLex* l) +{ size_t i, nlines = 0; - const char *buf; + const char* buf; bool end = false, got_more; char c; @@ -65,25 +73,35 @@ void bc_lex_comment(BcLex *l) { // This loop is complex because it might need to request more data from // stdin if the comment is not ended. This loop is taken until the comment // is finished or we have EOF. - do { - + do + { buf = l->buf; got_more = false; // If we are in stdin mode, the buffer must be the one used for stdin. - assert(!vm.is_stdin || buf == vm.buffer.v); +#if !BC_ENABLE_OSSFUZZ + assert(vm->mode != BC_MODE_STDIN || buf == vm->buffer.v); +#endif // !BC_ENABLE_OSSFUZZ // Find the end of the comment. - for (i = l->i; !end; i += !end) { - + for (i = l->i; !end; i += !end) + { // While we don't have an asterisk, eat, but increment nlines. - for (; (c = buf[i]) && c != '*'; ++i) nlines += (c == '\n'); + for (; (c = buf[i]) && c != '*'; ++i) + { + nlines += (c == '\n'); + } // If this is true, we need to request more data. - if (BC_ERR(!c || buf[i + 1] == '\0')) { - - // Read more. - if (!vm.eof && l->is_stdin) got_more = bc_lex_readLine(l); + if (BC_ERR(!c || buf[i + 1] == '\0')) + { +#if !BC_ENABLE_OSSFUZZ + // Read more, if possible. + if (!vm->eof && l->mode != BC_MODE_FILE) + { + got_more = bc_lex_readLine(l); + } +#endif // !BC_ENABLE_OSSFUZZ break; } @@ -91,11 +109,12 @@ void bc_lex_comment(BcLex *l) { // If this turns true, we found the end. Yay! end = (buf[i + 1] == '/'); } - - } while (got_more && !end); + } + while (got_more && !end); // If we didn't find the end, barf. - if (!end) { + if (!end) + { l->i = i; bc_lex_err(l, BC_ERR_PARSE_COMMENT); } @@ -104,17 +123,23 @@ void bc_lex_comment(BcLex *l) { l->line += nlines; } -void bc_lex_whitespace(BcLex *l) { - +void +bc_lex_whitespace(BcLex* l) +{ char c; l->t = BC_LEX_WHITESPACE; // Eat. We don't eat newlines because they can be special. - for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]); + for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]) + { + continue; + } } -void bc_lex_commonTokens(BcLex *l, char c) { +void +bc_lex_commonTokens(BcLex* l, char c) +{ if (!c) l->t = BC_LEX_EOF; else if (c == '\n') l->t = BC_LEX_NLINE; else bc_lex_whitespace(l); @@ -127,9 +152,10 @@ void bc_lex_commonTokens(BcLex *l, char c) { * @param int_only Whether this function should only look for an integer. This * is used to implement the exponent of scientific notation. */ -static size_t bc_lex_num(BcLex *l, char start, bool int_only) { - - const char *buf = l->buf + l->i; +static size_t +bc_lex_num(BcLex* l, char start, bool int_only) +{ + const char* buf = l->buf + l->i; size_t i; char c; bool last_pt, pt = (start == '.'); @@ -139,16 +165,20 @@ static size_t bc_lex_num(BcLex *l, char start, bool int_only) { // thus far, or whether it is a backslash followed by a newline. I can do // i+1 on the buffer because the buffer must have a nul byte. for (i = 0; (c = buf[i]) && (BC_LEX_NUM_CHAR(c, pt, int_only) || - (c == '\\' && buf[i + 1] == '\n')); ++i) + (c == '\\' && buf[i + 1] == '\n')); + ++i) { // I don't need to test that the next character is a newline because // the loop condition above ensures that. - if (c == '\\') { - + if (c == '\\') + { i += 2; // Make sure to eat whitespace at the beginning of the line. - while(isspace(buf[i]) && buf[i] != '\n') i += 1; + while (isspace(buf[i]) && buf[i] != '\n') + { + i += 1; + } c = buf[i]; @@ -172,8 +202,9 @@ static size_t bc_lex_num(BcLex *l, char start, bool int_only) { return i; } -void bc_lex_number(BcLex *l, char start) { - +void +bc_lex_number(BcLex* l, char start) +{ l->t = BC_LEX_NUMBER; // Make sure the string is clear. @@ -188,8 +219,8 @@ void bc_lex_number(BcLex *l, char start) { char c = l->buf[l->i]; // Do we have a number in scientific notation? - if (c == 'e') { - + if (c == 'e') + { #if BC_ENABLED // Barf for POSIX. if (BC_IS_POSIX) bc_lex_err(l, BC_ERR_POSIX_EXP_NUM); @@ -201,7 +232,8 @@ void bc_lex_number(BcLex *l, char start) { c = l->buf[l->i]; // Check for negative specifically because bc_lex_num() does not. - if (c == BC_LEX_NEG_CHAR) { + if (c == BC_LEX_NEG_CHAR) + { bc_vec_push(&l->str, &c); l->i += 1; c = l->buf[l->i]; @@ -209,7 +241,9 @@ void bc_lex_number(BcLex *l, char start) { // We must have a number character, so barf if not. if (BC_ERR(!BC_LEX_NUM_CHAR(c, false, true))) + { bc_lex_verr(l, BC_ERR_PARSE_CHAR, c); + } // Parse the exponent. l->i += bc_lex_num(l, 0, true); @@ -220,16 +254,20 @@ void bc_lex_number(BcLex *l, char start) { bc_vec_pushByte(&l->str, '\0'); } -void bc_lex_name(BcLex *l) { - +void +bc_lex_name(BcLex* l) +{ size_t i = 0; - const char *buf = l->buf + l->i - 1; + const char* buf = l->buf + l->i - 1; char c = buf[i]; l->t = BC_LEX_NAME; // Should be obvious. It's looking for valid characters. - while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i]; + while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') + { + c = buf[++i]; + } // Set the string to the identifier. bc_vec_string(&l->str, i, buf); @@ -238,25 +276,34 @@ void bc_lex_name(BcLex *l) { l->i += i - 1; } -void bc_lex_init(BcLex *l) { +void +bc_lex_init(BcLex* l) +{ BC_SIG_ASSERT_LOCKED; assert(l != NULL); bc_vec_init(&l->str, sizeof(char), BC_DTOR_NONE); } -void bc_lex_free(BcLex *l) { +void +bc_lex_free(BcLex* l) +{ BC_SIG_ASSERT_LOCKED; assert(l != NULL); bc_vec_free(&l->str); } -void bc_lex_file(BcLex *l, const char *file) { +void +bc_lex_file(BcLex* l, const char* file) +{ assert(l != NULL && file != NULL); l->line = 1; - vm.file = file; + vm->file = file; } -void bc_lex_next(BcLex *l) { +void +bc_lex_next(BcLex* l) +{ + BC_SIG_ASSERT_LOCKED; assert(l != NULL); @@ -275,9 +322,11 @@ void bc_lex_next(BcLex *l) { // Loop until failure or we don't have whitespace. This // is so the parser doesn't get inundated with whitespace. - do { - vm.next(l); - } while (l->t == BC_LEX_WHITESPACE); + do + { + vm->next(l); + } + while (l->t == BC_LEX_WHITESPACE); } /** @@ -287,25 +336,76 @@ void bc_lex_next(BcLex *l) { * @param text The text. * @param len The length of the text. */ -static void bc_lex_fixText(BcLex *l, const char *text, size_t len) { +static void +bc_lex_fixText(BcLex* l, const char* text, size_t len) +{ l->buf = text; l->len = len; } -bool bc_lex_readLine(BcLex *l) { +bool +bc_lex_readLine(BcLex* l) +{ + bool good; - bool good = bc_vm_readLine(false); + // These are reversed because they should be already locked, but + // bc_vm_readLine() needs them to be unlocked. + BC_SIG_UNLOCK; - bc_lex_fixText(l, vm.buffer.v, vm.buffer.len - 1); + // Make sure we read from the appropriate place. + switch (l->mode) + { + case BC_MODE_EXPRS: + { + good = bc_vm_readBuf(false); + break; + } + + case BC_MODE_FILE: + { + good = false; + break; + } + +#if !BC_ENABLE_OSSFUZZ + + case BC_MODE_STDIN: + { + good = bc_vm_readLine(false); + break; + } + +#endif // !BC_ENABLE_OSSFUZZ + +#ifdef __GNUC__ +#ifndef __clang__ + default: + { + // We should never get here. + abort(); + } +#endif // __clang__ +#endif // __GNUC__ + } + + BC_SIG_LOCK; + + bc_lex_fixText(l, vm->buffer.v, vm->buffer.len - 1); return good; } -void bc_lex_text(BcLex *l, const char *text, bool is_stdin) { +void +bc_lex_text(BcLex* l, const char* text, BcMode mode) +{ + BC_SIG_ASSERT_LOCKED; + assert(l != NULL && text != NULL); + bc_lex_fixText(l, text, strlen(text)); l->i = 0; l->t = l->last = BC_LEX_INVALID; - l->is_stdin = is_stdin; + l->mode = mode; + bc_lex_next(l); } diff --git a/contrib/bc/src/library.c b/contrib/bc/src/library.c index e0bd3ee98b8..5451e91684a 100644 --- a/contrib/bc/src/library.c +++ b/contrib/bc/src/library.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -45,233 +45,443 @@ #include #include +#ifndef _WIN32 +#include +#endif // _WIN32 + // 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. +// Also, there are a bunch of BC_UNSETJMP 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. + +#if BC_ENABLE_MEMCHECK + +BC_NORETURN void +bcl_invalidGeneration(void) +{ + abort(); +} + +BC_NORETURN void +bcl_nonexistentNum(void) +{ + abort(); +} + +BC_NORETURN void +bcl_numIdxOutOfRange(void) +{ + abort(); +} + +#endif // BC_ENABLE_MEMCHECK + +static BclTls* tls = NULL; +static BclTls tls_real; + +BclError +bcl_start(void) +{ +#ifndef _WIN32 -void bcl_handleSignal(void) { + int r; - // Signal already in flight, or bc is not executing. - if (vm.sig || !vm.running) return; + if (tls != NULL) return BCL_ERROR_NONE; + + r = pthread_key_create(&tls_real, NULL); + if (BC_ERR(r != 0)) return BCL_ERROR_FATAL_ALLOC_ERR; + +#else // _WIN32 + + if (tls != NULL) return BCL_ERROR_NONE; + + tls_real = TlsAlloc(); + if (BC_ERR(tls_real == TLS_OUT_OF_INDEXES)) + { + return BCL_ERROR_FATAL_ALLOC_ERR; + } - vm.sig = 1; +#endif // _WIN32 - assert(vm.jmp_bufs.len); + tls = &tls_real; - if (!vm.sig_lock) BC_JMP; + return BCL_ERROR_NONE; } -bool bcl_running(void) { - return vm.running != 0; +/** + * Sets the thread-specific data for the thread. + * @param vm The @a BcVm to set as the thread data. + * @return An error code, if any. + */ +static BclError +bcl_setspecific(BcVm* vm) +{ +#ifndef _WIN32 + + int r; + + assert(tls != NULL); + + r = pthread_setspecific(tls_real, vm); + if (BC_ERR(r != 0)) return BCL_ERROR_FATAL_ALLOC_ERR; + +#else // _WIN32 + + bool r; + + assert(tls != NULL); + + r = TlsSetValue(tls_real, vm); + if (BC_ERR(!r)) return BCL_ERROR_FATAL_ALLOC_ERR; + +#endif // _WIN32 + + return BCL_ERROR_NONE; } -BclError bcl_init(void) { +BcVm* +bcl_getspecific(void) +{ + BcVm* vm; + +#ifndef _WIN32 + + vm = pthread_getspecific(tls_real); + +#else // _WIN32 + + vm = TlsGetValue(tls_real); + +#endif // _WIN32 + + return vm; +} +BclError +bcl_init(void) +{ BclError e = BCL_ERROR_NONE; + BcVm* vm; + + assert(tls != NULL); + + vm = bcl_getspecific(); + if (vm != NULL) + { + assert(vm->refs >= 1); + + vm->refs += 1; + + return e; + } + + vm = bc_vm_malloc(sizeof(BcVm)); + if (BC_ERR(vm == NULL)) return BCL_ERROR_FATAL_ALLOC_ERR; + + e = bcl_setspecific(vm); + if (BC_ERR(e != BCL_ERROR_NONE)) + { + free(vm); + return e; + } - vm.refs += 1; + memset(vm, 0, sizeof(BcVm)); - if (vm.refs > 1) return e; + vm->refs += 1; + + assert(vm->refs == 1); // 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; + vm->ctxts.v = NULL; + vm->jmp_bufs.v = NULL; + vm->out.v = NULL; - BC_SIG_LOCK; + vm->abrt = false; + vm->leading_zeroes = false; + vm->digit_clamp = true; // The jmp_bufs always has to be initialized first. - bc_vec_init(&vm.jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); + bc_vec_init(&vm->jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); - BC_FUNC_HEADER_INIT(err); + BC_FUNC_HEADER(vm, err); bc_vm_init(); - bc_vec_init(&vm.ctxts, sizeof(BclContext), BC_DTOR_NONE); - bc_vec_init(&vm.out, sizeof(uchar), BC_DTOR_NONE); + bc_vec_init(&vm->ctxts, sizeof(BclContext), BC_DTOR_NONE); + bc_vec_init(&vm->out, sizeof(uchar), BC_DTOR_NONE); + +#if BC_ENABLE_EXTRA_MATH - // We need to seed this in case /dev/random and /dev/urandm don't work. + // We need to seed this in case /dev/random and /dev/urandom don't work. srand((unsigned int) time(NULL)); - bc_rand_init(&vm.rng); + bc_rand_init(&vm->rng); + +#endif // BC_ENABLE_EXTRA_MATH 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); + BC_FUNC_FOOTER(vm, e); - assert(!vm.running && !vm.sig && !vm.sig_lock); + // This is why we had to set them to NULL. + if (BC_ERR(vm != NULL && 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); + bcl_setspecific(NULL); + free(vm); + } return e; } -BclError bcl_pushContext(BclContext ctxt) { - +BclError +bcl_pushContext(BclContext ctxt) +{ BclError e = BCL_ERROR_NONE; + BcVm* vm = bcl_getspecific(); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_push(&vm.ctxts, &ctxt); + bc_vec_push(&vm->ctxts, &ctxt); err: - BC_FUNC_FOOTER_UNLOCK(e); + + BC_FUNC_FOOTER(vm, e); return e; } -void bcl_popContext(void) { - if (vm.ctxts.len) bc_vec_pop(&vm.ctxts); +void +bcl_popContext(void) +{ + BcVm* vm = bcl_getspecific(); + + 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)); +static BclContext +bcl_contextHelper(BcVm* vm) +{ + if (!vm->ctxts.len) return NULL; + return *((BclContext*) bc_vec_top(&vm->ctxts)); } -void bcl_free(void) { +BclContext +bcl_context(void) +{ + BcVm* vm = bcl_getspecific(); + return bcl_contextHelper(vm); +} +void +bcl_free(void) +{ size_t i; + BcVm* vm = bcl_getspecific(); - vm.refs -= 1; - - if (vm.refs) return; + vm->refs -= 1; + if (vm->refs) return; - BC_SIG_LOCK; +#if BC_ENABLE_EXTRA_MATH + bc_rand_free(&vm->rng); +#endif // BC_ENABLE_EXTRA_MATH + bc_vec_free(&vm->out); - 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)); + 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_vec_free(&vm->ctxts); bc_vm_atexit(); - BC_SIG_UNLOCK; + free(vm); + bcl_setspecific(NULL); +} - memset(&vm, 0, sizeof(BcVm)); +void +bcl_end(void) +{ +#ifndef _WIN32 + + // We ignore the return value. + pthread_key_delete(tls_real); + +#else // _WIN32 + + // We ignore the return value. + TlsFree(tls_real); + +#endif // _WIN32 - assert(!vm.running && !vm.sig && !vm.sig_lock); + tls = NULL; } -void bcl_gc(void) { - BC_SIG_LOCK; +void +bcl_gc(void) +{ bc_vm_freeTemps(); - BC_SIG_UNLOCK; } -bool bcl_abortOnFatalError(void) { - return vm.abrt; +bool +bcl_abortOnFatalError(void) +{ + BcVm* vm = bcl_getspecific(); + + return vm->abrt; } -void bcl_setAbortOnFatalError(bool abrt) { - vm.abrt = abrt; +void +bcl_setAbortOnFatalError(bool abrt) +{ + BcVm* vm = bcl_getspecific(); + + vm->abrt = abrt; +} + +bool +bcl_leadingZeroes(void) +{ + BcVm* vm = bcl_getspecific(); + + return vm->leading_zeroes; } -bool bcl_leadingZeroes(void) { - return vm.leading_zeroes; +void +bcl_setLeadingZeroes(bool leadingZeroes) +{ + BcVm* vm = bcl_getspecific(); + + vm->leading_zeroes = leadingZeroes; } -void bcl_setLeadingZeroes(bool leadingZeroes) { - vm.leading_zeroes = leadingZeroes; +bool +bcl_digitClamp(void) +{ + BcVm* vm = bcl_getspecific(); + + return vm->digit_clamp; } -BclContext bcl_ctxt_create(void) { +void +bcl_setDigitClamp(bool digitClamp) +{ + BcVm* vm = bcl_getspecific(); + + vm->digit_clamp = digitClamp; +} +BclContext +bcl_ctxt_create(void) +{ + BcVm* vm = bcl_getspecific(); BclContext ctxt = NULL; - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, 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->nums, sizeof(BclNum), BC_DTOR_BCL_NUM); bc_vec_init(&ctxt->free_nums, sizeof(BclNumber), BC_DTOR_NONE); ctxt->scale = 0; ctxt->ibase = 10; - ctxt->obase= 10; + ctxt->obase = 10; err: - if (BC_ERR(vm.err && ctxt != NULL)) { + + 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); + BC_FUNC_FOOTER_NO_ERR(vm); return ctxt; } -void bcl_ctxt_free(BclContext ctxt) { - BC_SIG_LOCK; +void +bcl_ctxt_free(BclContext ctxt) +{ bc_vec_free(&ctxt->free_nums); bc_vec_free(&ctxt->nums); free(ctxt); - BC_SIG_UNLOCK; } -void bcl_ctxt_freeNums(BclContext ctxt) { +void +bcl_ctxt_freeNums(BclContext ctxt) +{ bc_vec_popAll(&ctxt->nums); bc_vec_popAll(&ctxt->free_nums); } -size_t bcl_ctxt_scale(BclContext ctxt) { +size_t +bcl_ctxt_scale(BclContext ctxt) +{ return ctxt->scale; } -void bcl_ctxt_setScale(BclContext ctxt, size_t scale) { +void +bcl_ctxt_setScale(BclContext ctxt, size_t scale) +{ ctxt->scale = scale; } -size_t bcl_ctxt_ibase(BclContext ctxt) { +size_t +bcl_ctxt_ibase(BclContext ctxt) +{ return ctxt->ibase; } -void bcl_ctxt_setIbase(BclContext ctxt, size_t 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) { +size_t +bcl_ctxt_obase(BclContext ctxt) +{ return ctxt->obase; } -void bcl_ctxt_setObase(BclContext ctxt, size_t obase) { +void +bcl_ctxt_setObase(BclContext ctxt, size_t obase) +{ ctxt->obase = obase; } -BclError bcl_err(BclNumber n) { - +BclError +bcl_err(BclNumber n) +{ BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ERR(ctxt); + BC_CHECK_CTXT_ERR(vm, ctxt); + + // We need to clear the top byte in memcheck mode. We can do this because + // the parameter is a copy. + BCL_CLEAR_GEN(n); // 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 >= ctxt->nums.len) + { if (n.i > 0 - (size_t) BCL_ERROR_NELEMS) return (BclError) (0 - n.i); else return BCL_ERROR_INVALID_NUM; } @@ -284,14 +494,15 @@ BclError bcl_err(BclNumber n) { * @param n The BcNum to insert. * @return The resulting BclNumber from the insert. */ -static BclNumber bcl_num_insert(BclContext ctxt, BcNum *restrict n) { - +static BclNumber +bcl_num_insert(BclContext ctxt, BclNum* restrict n) +{ BclNumber idx; // If there is a free spot... - if (ctxt->free_nums.len) { - - BcNum *ptr; + if (ctxt->free_nums.len) + { + BclNum* ptr; // Get the index of the free spot and remove it. idx = *((BclNumber*) bc_vec_top(&ctxt->free_nums)); @@ -299,39 +510,58 @@ static BclNumber bcl_num_insert(BclContext ctxt, BcNum *restrict n) { // Copy the number into the spot. ptr = bc_vec_item(&ctxt->nums, idx.i); - memcpy(ptr, n, sizeof(BcNum)); + + memcpy(BCL_NUM_NUM(ptr), n, sizeof(BcNum)); + +#if BC_ENABLE_MEMCHECK + + ptr->gen_idx += 1; + + if (ptr->gen_idx == UCHAR_MAX) + { + ptr->gen_idx = 0; + } + + idx.i |= (ptr->gen_idx << ((sizeof(size_t) - 1) * CHAR_BIT)); + +#endif // BC_ENABLE_MEMCHECK } - else { - // Just push the number onto the vector. + else + { +#if BC_ENABLE_MEMCHECK + n->gen_idx = 0; +#endif // BC_ENABLE_MEMCHECK + + // Just push the number onto the vector because the generation index is + // 0. 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) { - +BclNumber +bcl_num_create(void) +{ BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - bc_num_init(&n, BC_NUM_DEF_SIZE); + bc_num_init(BCL_NUM_NUM_NP(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); + BC_FUNC_FOOTER(vm, e); + BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } @@ -342,569 +572,758 @@ BclNumber bcl_num_create(void) { * @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; +static void +bcl_num_dtor(BclContext ctxt, BclNumber n, BclNum* restrict num) +{ + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); - assert(num != NULL && num->num != NULL); + BCL_CLEAR_GEN(n); bcl_num_destruct(num); bc_vec_push(&ctxt->free_nums, &n); -} -void bcl_num_free(BclNumber n) { +#if BC_ENABLE_MEMCHECK + num->n.num = NULL; +#endif // BC_ENABLE_MEMCHECK +} - BcNum *num; +void +bcl_num_free(BclNumber n) +{ + BclNum* num; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - BC_SIG_LOCK; + BCL_CHECK_NUM_VALID(ctxt, n); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - num = BC_NUM(ctxt, n); + num = BCL_NUM(ctxt, n); bcl_num_dtor(ctxt, n, num); - - BC_SIG_UNLOCK; } -BclError bcl_copy(BclNumber d, BclNumber s) { - +BclError +bcl_copy(BclNumber d, BclNumber s) +{ BclError e = BCL_ERROR_NONE; - BcNum *dest, *src; + BclNum* dest; + BclNum* src; BclContext ctxt; + BcVm* vm = bcl_getspecific(); + + BC_CHECK_CTXT_ERR(vm, ctxt); - BC_CHECK_CTXT_ERR(ctxt); + BCL_CHECK_NUM_VALID(ctxt, d); + BCL_CHECK_NUM_VALID(ctxt, s); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - assert(d.i < ctxt->nums.len && s.i < ctxt->nums.len); + assert(BCL_NO_GEN(d) < ctxt->nums.len); + assert(BCL_NO_GEN(s) < ctxt->nums.len); - dest = BC_NUM(ctxt, d); - src = BC_NUM(ctxt, s); + dest = BCL_NUM(ctxt, d); + src = BCL_NUM(ctxt, s); assert(dest != NULL && src != NULL); - assert(dest->num != NULL && src->num != NULL); + assert(BCL_NUM_ARRAY(dest) != NULL && BCL_NUM_ARRAY(src) != NULL); - bc_num_copy(dest, src); + bc_num_copy(BCL_NUM_NUM(dest), BCL_NUM_NUM(src)); err: - BC_FUNC_FOOTER_UNLOCK(e); - assert(!vm.running && !vm.sig && !vm.sig_lock); + BC_FUNC_FOOTER(vm, e); return e; } -BclNumber bcl_dup(BclNumber s) { - +BclNumber +bcl_dup(BclNumber s) +{ BclError e = BCL_ERROR_NONE; - BcNum *src, dest; + BclNum *src, dest; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); + + BC_CHECK_CTXT(vm, ctxt); - BC_CHECK_CTXT(ctxt); + BCL_CHECK_NUM_VALID(ctxt, s); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(s.i < ctxt->nums.len); + assert(BCL_NO_GEN(s) < ctxt->nums.len); - src = BC_NUM(ctxt, s); + src = BCL_NUM(ctxt, s); - assert(src != NULL && src->num != NULL); + assert(src != NULL && BCL_NUM_NUM(src) != NULL); // Copy the number. - bc_num_clear(&dest); - bc_num_createCopy(&dest, src); + bc_num_clear(BCL_NUM_NUM(&dest)); + bc_num_createCopy(BCL_NUM_NUM(&dest), BCL_NUM_NUM(src)); err: - BC_FUNC_FOOTER_UNLOCK(e); - BC_MAYBE_SETUP(ctxt, e, dest, idx); - assert(!vm.running && !vm.sig && !vm.sig_lock); + BC_FUNC_FOOTER(vm, e); + BC_MAYBE_SETUP(ctxt, e, dest, idx); return idx; } -void bcl_num_destruct(void *num) { - - BcNum *n = (BcNum*) num; +void +bcl_num_destruct(void* num) +{ + BclNum* n = (BclNum*) num; assert(n != NULL); - if (n->num == NULL) return; + if (BCL_NUM_ARRAY(n) == NULL) return; - bc_num_free(num); - bc_num_clear(num); + bc_num_free(BCL_NUM_NUM(n)); + bc_num_clear(BCL_NUM_NUM(n)); } -bool bcl_num_neg(BclNumber n) { - - BcNum *num; +bool +bcl_num_neg(BclNumber n) +{ + BclNum* num; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - num = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(num != NULL && num->num != NULL); + num = BCL_NUM(ctxt, n); - return BC_NUM_NEG(num) != 0; -} + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); -void bcl_num_setNeg(BclNumber n, bool neg) { + return BC_NUM_NEG(BCL_NUM_NUM(num)) != 0; +} - BcNum *num; +void +bcl_num_setNeg(BclNumber n, bool neg) +{ + BclNum* num; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - num = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(num != NULL && num->num != NULL); + num = BCL_NUM(ctxt, n); - num->rdx = BC_NUM_NEG_VAL(num, neg); -} + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); -size_t bcl_num_scale(BclNumber n) { + BCL_NUM_NUM(num)->rdx = BC_NUM_NEG_VAL(BCL_NUM_NUM(num), neg); +} - BcNum *num; +size_t +bcl_num_scale(BclNumber n) +{ + BclNum* num; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - num = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(num != NULL && num->num != NULL); + num = BCL_NUM(ctxt, n); - return bc_num_scale(num); -} + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); -BclError bcl_num_setScale(BclNumber n, size_t scale) { + return bc_num_scale(BCL_NUM_NUM(num)); +} +BclError +bcl_num_setScale(BclNumber n, size_t scale) +{ BclError e = BCL_ERROR_NONE; - BcNum *nptr; + BclNum* nptr; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ERR(ctxt); + BC_CHECK_CTXT_ERR(vm, ctxt); BC_CHECK_NUM_ERR(ctxt, n); - BC_FUNC_HEADER(err); + BCL_CHECK_NUM_VALID(ctxt, n); - assert(n.i < ctxt->nums.len); + BC_FUNC_HEADER(vm, err); - nptr = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(nptr != NULL && nptr->num != NULL); + nptr = BCL_NUM(ctxt, n); - if (scale > nptr->scale) bc_num_extend(nptr, scale - nptr->scale); - else if (scale < nptr->scale) bc_num_truncate(nptr, nptr->scale - scale); + assert(nptr != NULL && BCL_NUM_ARRAY(nptr) != NULL); + + if (scale > BCL_NUM_NUM(nptr)->scale) + { + bc_num_extend(BCL_NUM_NUM(nptr), scale - BCL_NUM_NUM(nptr)->scale); + } + else if (scale < BCL_NUM_NUM(nptr)->scale) + { + bc_num_truncate(BCL_NUM_NUM(nptr), BCL_NUM_NUM(nptr)->scale - scale); + } err: - BC_SIG_MAYLOCK; - BC_FUNC_FOOTER(e); - assert(!vm.running && !vm.sig && !vm.sig_lock); + BC_FUNC_FOOTER(vm, e); return e; } -size_t bcl_num_len(BclNumber n) { - - BcNum *num; +size_t +bcl_num_len(BclNumber n) +{ + BclNum* num; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - num = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(num != NULL && num->num != NULL); + num = BCL_NUM(ctxt, n); - return bc_num_len(num); -} + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); -BclError bcl_bigdig(BclNumber n, BclBigDig *result) { + return bc_num_len(BCL_NUM_NUM(num)); +} +static BclError +bcl_bigdig_helper(BclNumber n, BclBigDig* result, bool destruct) +{ BclError e = BCL_ERROR_NONE; - BcNum *num; + BclNum* num; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ERR(ctxt); + BC_CHECK_CTXT_ERR(vm, ctxt); - BC_FUNC_HEADER_LOCK(err); + BCL_CHECK_NUM_VALID(ctxt, n); - assert(n.i < ctxt->nums.len); + BC_FUNC_HEADER(vm, err); + + assert(BCL_NO_GEN(n) < ctxt->nums.len); assert(result != NULL); - num = BC_NUM(ctxt, n); + num = BCL_NUM(ctxt, n); - assert(num != NULL && num->num != NULL); + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); - *result = bc_num_bigdig(num); + *result = bc_num_bigdig(BCL_NUM_NUM(num)); err: - bcl_num_dtor(ctxt, n, num); - BC_FUNC_FOOTER_UNLOCK(e); - assert(!vm.running && !vm.sig && !vm.sig_lock); + if (destruct) + { + bcl_num_dtor(ctxt, n, num); + } + + BC_FUNC_FOOTER(vm, e); return e; } -BclNumber bcl_bigdig2num(BclBigDig val) { +BclError +bcl_bigdig(BclNumber n, BclBigDig* result) +{ + return bcl_bigdig_helper(n, result, true); +} + +BclError +bcl_bigdig_keep(BclNumber n, BclBigDig* result) +{ + return bcl_bigdig_helper(n, result, false); +} +BclNumber +bcl_bigdig2num(BclBigDig val) +{ BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - bc_num_createFromBigdig(&n, val); + bc_num_createFromBigdig(BCL_NUM_NUM_NP(n), val); err: - BC_FUNC_FOOTER_UNLOCK(e); - BC_MAYBE_SETUP(ctxt, e, n, idx); - assert(!vm.running && !vm.sig && !vm.sig_lock); + BC_FUNC_FOOTER(vm, e); + BC_MAYBE_SETUP(ctxt, e, n, idx); 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. + * @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. + * @param destruct True if the parameters should be consumed, false otherwise. + * @return The result of the operation. */ -static BclNumber bcl_binary(BclNumber a, BclNumber b, const BcNumBinaryOp op, - const BcNumBinaryOpReq req) +static BclNumber +bcl_binary(BclNumber a, BclNumber b, const BcNumBinaryOp op, + const BcNumBinaryOpReq req, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum *aptr, *bptr; - BcNum c; + BclNum* aptr; + BclNum* bptr; + BclNum c; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_CHECK_NUM(ctxt, b); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len && BCL_NO_GEN(b) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); assert(aptr != NULL && bptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL); + assert(BCL_NUM_ARRAY(aptr) != NULL && BCL_NUM_ARRAY(bptr) != NULL); // Clear and initialize the result. - bc_num_clear(&c); - bc_num_init(&c, req(aptr, bptr, ctxt->scale)); + bc_num_clear(BCL_NUM_NUM_NP(c)); + bc_num_init(BCL_NUM_NUM_NP(c), + req(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), ctxt->scale)); - BC_SIG_UNLOCK; - - op(aptr, bptr, &c, ctxt->scale); + op(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), BCL_NUM_NUM_NP(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); + if (destruct) + { + // 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_FUNC_FOOTER(vm, 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_add(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_add, bc_num_addReq, true); +} + +BclNumber +bcl_add_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_add, bc_num_addReq, false); } -BclNumber bcl_sub(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_sub, bc_num_addReq); +BclNumber +bcl_sub(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_sub, bc_num_addReq, true); } -BclNumber bcl_mul(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_mul, bc_num_mulReq); +BclNumber +bcl_sub_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_sub, bc_num_addReq, false); } -BclNumber bcl_div(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_div, bc_num_divReq); +BclNumber +bcl_mul(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_mul, bc_num_mulReq, true); +} + +BclNumber +bcl_mul_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_mul, bc_num_mulReq, false); +} + +BclNumber +bcl_div(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_div, bc_num_divReq, true); +} + +BclNumber +bcl_div_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_div, bc_num_divReq, false); +} + +BclNumber +bcl_mod(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_mod, bc_num_divReq, true); +} + +BclNumber +bcl_mod_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_mod, bc_num_divReq, false); +} + +BclNumber +bcl_pow(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_pow, bc_num_powReq, true); } -BclNumber bcl_mod(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_mod, bc_num_divReq); +BclNumber +bcl_pow_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_pow, bc_num_powReq, false); } -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, true); } -BclNumber bcl_lshift(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_lshift, bc_num_placesReq); +BclNumber +bcl_lshift_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_lshift, bc_num_placesReq, false); } -BclNumber bcl_rshift(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq); +BclNumber +bcl_rshift(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq, true); } -BclNumber bcl_sqrt(BclNumber a) { +BclNumber +bcl_rshift_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq, false); +} +static BclNumber +bcl_sqrt_helper(BclNumber a, bool destruct) +{ BclError e = BCL_ERROR_NONE; - BcNum *aptr; - BcNum b; + BclNum* aptr; + BclNum b; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); - BC_FUNC_HEADER(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); + aptr = BCL_NUM(ctxt, a); - bc_num_sqrt(aptr, &b, ctxt->scale); + bc_num_sqrt(BCL_NUM_NUM(aptr), BCL_NUM_NUM_NP(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); + if (destruct) + { + bcl_num_dtor(ctxt, a, aptr); + } + + BC_FUNC_FOOTER(vm, e); + BC_MAYBE_SETUP(ctxt, e, b, idx); return idx; } -BclError bcl_divmod(BclNumber a, BclNumber b, BclNumber *c, BclNumber *d) { +BclNumber +bcl_sqrt(BclNumber a) +{ + return bcl_sqrt_helper(a, true); +} + +BclNumber +bcl_sqrt_keep(BclNumber a) +{ + return bcl_sqrt_helper(a, false); +} +static BclError +bcl_divmod_helper(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d, + bool destruct) +{ BclError e = BCL_ERROR_NONE; size_t req; - BcNum *aptr, *bptr; - BcNum cnum, dnum; + BclNum* aptr; + BclNum* bptr; + BclNum cnum, dnum; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ERR(ctxt); + BC_CHECK_CTXT_ERR(vm, ctxt); BC_CHECK_NUM_ERR(ctxt, a); BC_CHECK_NUM_ERR(ctxt, b); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 2); + BCL_GROW_NUMS(ctxt); assert(c != NULL && d != NULL); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); assert(aptr != NULL && bptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL); + assert(BCL_NUM_ARRAY(aptr) != NULL && BCL_NUM_ARRAY(bptr) != NULL); - bc_num_clear(&cnum); - bc_num_clear(&dnum); + bc_num_clear(BCL_NUM_NUM_NP(cnum)); + bc_num_clear(BCL_NUM_NUM_NP(dnum)); - req = bc_num_divReq(aptr, bptr, ctxt->scale); + req = bc_num_divReq(BCL_NUM_NUM(aptr), BCL_NUM_NUM(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_init(BCL_NUM_NUM_NP(cnum), req); + BC_UNSETJMP(vm); + BC_SETJMP(vm, err); + bc_num_init(BCL_NUM_NUM_NP(dnum), req); - bc_num_divmod(aptr, bptr, &cnum, &dnum, ctxt->scale); + bc_num_divmod(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), BCL_NUM_NUM_NP(cnum), + BCL_NUM_NUM_NP(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 (destruct) + { + // 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)) { - + if (BC_ERR(vm->err)) + { // Free the results. - if (cnum.num != NULL) bc_num_free(&cnum); - if (dnum.num != NULL) bc_num_free(&dnum); + if (BCL_NUM_ARRAY_NP(cnum) != NULL) bc_num_free(&cnum); + if (BCL_NUM_ARRAY_NP(cnum) != 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); + BC_FUNC_FOOTER(vm, e); } - else { - - BC_FUNC_FOOTER(e); + else + { + BC_FUNC_FOOTER(vm, 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 +bcl_divmod(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d) +{ + return bcl_divmod_helper(a, b, c, d, true); +} + +BclError +bcl_divmod_keep(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d) +{ + return bcl_divmod_helper(a, b, c, d, false); +} +static BclNumber +bcl_modexp_helper(BclNumber a, BclNumber b, BclNumber c, bool destruct) +{ BclError e = BCL_ERROR_NONE; size_t req; - BcNum *aptr, *bptr, *cptr; - BcNum d; + BclNum* aptr; + BclNum* bptr; + BclNum* cptr; + BclNum d; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_CHECK_NUM(ctxt, b); BC_CHECK_NUM(ctxt, c); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len); - assert(c.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len && BCL_NO_GEN(b) < ctxt->nums.len); + assert(BCL_NO_GEN(c) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); - cptr = BC_NUM(ctxt, c); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); + cptr = BCL_NUM(ctxt, c); assert(aptr != NULL && bptr != NULL && cptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL && cptr->num != NULL); + assert(BCL_NUM_NUM(aptr) != NULL && BCL_NUM_NUM(bptr) != NULL && + BCL_NUM_NUM(cptr) != NULL); // Prepare the result. - bc_num_clear(&d); + bc_num_clear(BCL_NUM_NUM_NP(d)); - req = bc_num_divReq(aptr, cptr, 0); + req = bc_num_divReq(BCL_NUM_NUM(aptr), BCL_NUM_NUM(cptr), 0); // Initialize the result. - bc_num_init(&d, req); + bc_num_init(BCL_NUM_NUM_NP(d), req); - BC_SIG_UNLOCK; - - bc_num_modexp(aptr, bptr, cptr, &d); + bc_num_modexp(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), BCL_NUM_NUM(cptr), + BCL_NUM_NUM_NP(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); + if (destruct) + { + // 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_FUNC_FOOTER(vm, 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) { +BclNumber +bcl_modexp(BclNumber a, BclNumber b, BclNumber c) +{ + return bcl_modexp_helper(a, b, c, true); +} - BcNum *aptr, *bptr; +BclNumber +bcl_modexp_keep(BclNumber a, BclNumber b, BclNumber c) +{ + return bcl_modexp_helper(a, b, c, false); +} + +ssize_t +bcl_cmp(BclNumber a, BclNumber b) +{ + BclNum* aptr; + BclNum* bptr; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, a); + BCL_CHECK_NUM_VALID(ctxt, b); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); + assert(BCL_NO_GEN(a) < ctxt->nums.len && BCL_NO_GEN(b) < ctxt->nums.len); + + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); assert(aptr != NULL && bptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL); + assert(BCL_NUM_NUM(aptr) != NULL && BCL_NUM_NUM(bptr)); - return bc_num_cmp(aptr, bptr); + return bc_num_cmp(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr)); } -void bcl_zero(BclNumber n) { - - BcNum *nptr; +void +bcl_zero(BclNumber n) +{ + BclNum* nptr; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - nptr = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(nptr != NULL && nptr->num != NULL); + nptr = BCL_NUM(ctxt, n); - bc_num_zero(nptr); -} + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); -void bcl_one(BclNumber n) { + bc_num_zero(BCL_NUM_NUM(nptr)); +} - BcNum *nptr; +void +bcl_one(BclNumber n) +{ + BclNum* nptr; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ASSERT(ctxt); + BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - nptr = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(nptr != NULL && nptr->num != NULL); + nptr = BCL_NUM(ctxt, n); - bc_num_one(nptr); -} + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); -BclNumber bcl_parse(const char *restrict val) { + bc_num_one(BCL_NUM_NUM(nptr)); +} +BclNumber +bcl_parse(const char* restrict val) +{ BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); bool neg; - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); assert(val != NULL); @@ -914,129 +1333,161 @@ BclNumber bcl_parse(const char *restrict val) { if (neg) val += 1; - if (!bc_num_strValid(val)) { - vm.err = BCL_ERROR_PARSE_INVALID_STR; + 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_clear(BCL_NUM_NUM_NP(n)); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); - bc_num_parse(&n, val, (BcBigDig) ctxt->ibase); + bc_num_parse(BCL_NUM_NUM_NP(n), val, (BcBigDig) ctxt->ibase); // Set the negative. +#if BC_ENABLE_MEMCHECK + n.n.rdx = BC_NUM_NEG_VAL(BCL_NUM_NUM_NP(n), neg); +#else // BC_ENABLE_MEMCHECK n.rdx = BC_NUM_NEG_VAL_NP(n, neg); +#endif // BC_ENABLE_MEMCHECK err: - BC_SIG_MAYLOCK; - BC_FUNC_FOOTER(e); - BC_MAYBE_SETUP(ctxt, e, n, idx); - assert(!vm.running && !vm.sig && !vm.sig_lock); + BC_FUNC_FOOTER(vm, e); + BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } -char* bcl_string(BclNumber n) { - - BcNum *nptr; - char *str = NULL; +static char* +bcl_string_helper(BclNumber n, bool destruct) +{ + BclNum* nptr; + char* str = NULL; BclContext ctxt; + BcVm* vm = bcl_getspecific(); + + BC_CHECK_CTXT_ASSERT(vm, ctxt); - BC_CHECK_CTXT_ASSERT(ctxt); + BCL_CHECK_NUM_VALID(ctxt, n); - if (BC_ERR(n.i >= ctxt->nums.len)) return str; + if (BC_ERR(BCL_NO_GEN(n) >= ctxt->nums.len)) return str; - BC_FUNC_HEADER(err); + BC_FUNC_HEADER(vm, err); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - nptr = BC_NUM(ctxt, n); + nptr = BCL_NUM(ctxt, n); - assert(nptr != NULL && nptr->num != NULL); + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); // Clear the buffer. - bc_vec_popAll(&vm.out); + 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; + bc_num_print(BCL_NUM_NUM(nptr), (BcBigDig) ctxt->obase, false); + bc_vec_pushByte(&vm->out, '\0'); // Just dup the string; the caller is responsible for it. - str = bc_vm_strdup(vm.out.v); + str = bc_vm_strdup(vm->out.v); err: - // Eat the operand. - bcl_num_dtor(ctxt, n, nptr); - - BC_FUNC_FOOTER_NO_ERR; + if (destruct) + { + // Eat the operand. + bcl_num_dtor(ctxt, n, nptr); + } - assert(!vm.running && !vm.sig && !vm.sig_lock); + BC_FUNC_FOOTER_NO_ERR(vm); return str; } -BclNumber bcl_irand(BclNumber a) { +char* +bcl_string(BclNumber n) +{ + return bcl_string_helper(n, true); +} +char* +bcl_string_keep(BclNumber n) +{ + return bcl_string_helper(n, false); +} + +#if BC_ENABLE_EXTRA_MATH + +static BclNumber +bcl_irand_helper(BclNumber a, bool destruct) +{ BclError e = BCL_ERROR_NONE; - BcNum *aptr; - BcNum b; + BclNum* aptr; + BclNum b; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); + aptr = BCL_NUM(ctxt, a); - assert(aptr != NULL && aptr->num != NULL); + assert(aptr != NULL && BCL_NUM_NUM(aptr) != NULL); // Clear and initialize the result. - bc_num_clear(&b); - bc_num_init(&b, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(b)); + bc_num_init(BCL_NUM_NUM_NP(b), BC_NUM_DEF_SIZE); - BC_SIG_UNLOCK; - - bc_num_irand(aptr, &b, &vm.rng); + bc_num_irand(BCL_NUM_NUM(aptr), BCL_NUM_NUM_NP(b), &vm->rng); err: - BC_SIG_MAYLOCK; - // Eat the operand. - bcl_num_dtor(ctxt, a, aptr); + if (destruct) + { + // Eat the operand. + bcl_num_dtor(ctxt, a, aptr); + } - BC_FUNC_FOOTER(e); + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, b, idx); - assert(!vm.running && !vm.sig && !vm.sig_lock); - return idx; } +BclNumber +bcl_irand(BclNumber a) +{ + return bcl_irand_helper(a, true); +} + +BclNumber +bcl_irand_keep(BclNumber a) +{ + return bcl_irand_helper(a, false); +} + /** * 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) { - +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]; + BcVm* vm = bcl_getspecific(); // Set up temporaries. bc_num_setup(&exp, exp_digs, BC_NUM_BIGDIG_LOG10); @@ -1050,57 +1501,50 @@ static void bcl_frandHelper(BcNum *restrict b, size_t 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; + BC_SETJMP(vm, err); // Generate the number. bc_num_pow(&ten, &exp, &pow, 0); - bc_num_irand(&pow, b, &vm.rng); + 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; + BC_LONGJMP_CONT(vm); } -BclNumber bcl_frand(size_t places) { - +BclNumber +bcl_frand(size_t places) +{ BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); // Clear and initialize the number. - bc_num_clear(&n); - bc_num_init(&n, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(n)); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); - BC_SIG_UNLOCK; - - bcl_frandHelper(&n, places); + bcl_frandHelper(BCL_NUM_NUM_NP(n), places); err: - BC_SIG_MAYLOCK; - BC_FUNC_FOOTER(e); + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, n, idx); - assert(!vm.running && !vm.sig && !vm.sig_lock); - return idx; } @@ -1111,171 +1555,214 @@ BclNumber bcl_frand(size_t places) { * @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) +static void +bcl_ifrandHelper(BcNum* restrict a, BcNum* restrict b, size_t places) { BcNum ir, fr; + BcVm* vm = bcl_getspecific(); // 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_SETJMP(vm, err); - BC_SIG_UNLOCK; - - bc_num_irand(a, &ir, &vm.rng); + 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; + BC_LONGJMP_CONT(vm); } -BclNumber bcl_ifrand(BclNumber a, size_t places) { - +static BclNumber +bcl_ifrand_helper(BclNumber a, size_t places, bool destruct) +{ BclError e = BCL_ERROR_NONE; - BcNum *aptr; - BcNum b; + BclNum* aptr; + BclNum b; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); + aptr = BCL_NUM(ctxt, a); - assert(aptr != NULL && aptr->num != NULL); + assert(aptr != NULL && BCL_NUM_NUM(aptr) != NULL); // Clear and initialize the number. - bc_num_clear(&b); - bc_num_init(&b, BC_NUM_DEF_SIZE); - - BC_SIG_UNLOCK; + bc_num_clear(BCL_NUM_NUM_NP(b)); + bc_num_init(BCL_NUM_NUM_NP(b), BC_NUM_DEF_SIZE); - bcl_ifrandHelper(aptr, &b, places); + bcl_ifrandHelper(BCL_NUM_NUM(aptr), BCL_NUM_NUM_NP(b), places); err: - BC_SIG_MAYLOCK; - // Eat the oprand. - bcl_num_dtor(ctxt, a, aptr); + if (destruct) + { + // Eat the oprand. + bcl_num_dtor(ctxt, a, aptr); + } - BC_FUNC_FOOTER(e); + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, b, idx); - assert(!vm.running && !vm.sig && !vm.sig_lock); - return idx; } -BclError bcl_rand_seedWithNum(BclNumber n) { +BclNumber +bcl_ifrand(BclNumber a, size_t places) +{ + return bcl_ifrand_helper(a, places, true); +} + +BclNumber +bcl_ifrand_keep(BclNumber a, size_t places) +{ + return bcl_ifrand_helper(a, places, false); +} +static BclError +bcl_rand_seedWithNum_helper(BclNumber n, bool destruct) +{ BclError e = BCL_ERROR_NONE; - BcNum *nptr; + BclNum* nptr; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT_ERR(ctxt); + BC_CHECK_CTXT_ERR(vm, ctxt); BC_CHECK_NUM_ERR(ctxt, n); - BC_FUNC_HEADER(err); + BC_FUNC_HEADER(vm, err); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - nptr = BC_NUM(ctxt, n); + nptr = BCL_NUM(ctxt, n); - assert(nptr != NULL && nptr->num != NULL); + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); - bc_num_rng(nptr, &vm.rng); + bc_num_rng(BCL_NUM_NUM(nptr), &vm->rng); err: - BC_SIG_MAYLOCK; - BC_FUNC_FOOTER(e); - assert(!vm.running && !vm.sig && !vm.sig_lock); + if (destruct) + { + // Eat the oprand. + bcl_num_dtor(ctxt, n, nptr); + } + + BC_FUNC_FOOTER(vm, e); return e; } -BclError bcl_rand_seed(unsigned char seed[BCL_SEED_SIZE]) { +BclError +bcl_rand_seedWithNum(BclNumber n) +{ + return bcl_rand_seedWithNum_helper(n, true); +} + +BclError +bcl_rand_seedWithNum_keep(BclNumber n) +{ + return bcl_rand_seedWithNum_helper(n, false); +} +BclError +bcl_rand_seed(unsigned char seed[BCL_SEED_SIZE]) +{ BclError e = BCL_ERROR_NONE; size_t i; ulong vals[BCL_SEED_ULONGS]; + BcVm* vm = bcl_getspecific(); - BC_FUNC_HEADER(err); + BC_FUNC_HEADER(vm, err); // Fill the array. - for (i = 0; i < BCL_SEED_SIZE; ++i) { - ulong val = ((ulong) seed[i]) << (((ulong) CHAR_BIT) * - (i % sizeof(ulong))); + 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]); + bc_rand_seed(&vm->rng, vals[0], vals[1], vals[2], vals[3]); err: - BC_SIG_MAYLOCK; - BC_FUNC_FOOTER(e); + + BC_FUNC_FOOTER(vm, e); + return e; } -void bcl_rand_reseed(void) { - bc_rand_srand(bc_vec_top(&vm.rng.v)); -} +void +bcl_rand_reseed(void) +{ + BcVm* vm = bcl_getspecific(); -BclNumber bcl_rand_seed2num(void) { + bc_rand_srand(bc_vec_top(&vm->rng.v)); +} +BclNumber +bcl_rand_seed2num(void) +{ BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; + BcVm* vm = bcl_getspecific(); - BC_CHECK_CTXT(ctxt); + BC_CHECK_CTXT(vm, ctxt); - BC_FUNC_HEADER_LOCK(err); + BC_FUNC_HEADER(vm, err); // Clear and initialize the number. - bc_num_clear(&n); - bc_num_init(&n, BC_NUM_DEF_SIZE); - - BC_SIG_UNLOCK; + bc_num_clear(BCL_NUM_NUM_NP(n)); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); - bc_num_createFromRNG(&n, &vm.rng); + bc_num_createFromRNG(BCL_NUM_NUM_NP(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); + BC_FUNC_FOOTER(vm, e); + BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } -BclRandInt bcl_rand_int(void) { - return (BclRandInt) bc_rand_int(&vm.rng); +BclRandInt +bcl_rand_int(void) +{ + BcVm* vm = bcl_getspecific(); + + return (BclRandInt) bc_rand_int(&vm->rng); } -BclRandInt bcl_rand_bounded(BclRandInt bound) { +BclRandInt +bcl_rand_bounded(BclRandInt bound) +{ + BcVm* vm = bcl_getspecific(); + if (bound <= 1) return 0; - return (BclRandInt) bc_rand_bounded(&vm.rng, (BcRand) bound); + return (BclRandInt) bc_rand_bounded(&vm->rng, (BcRand) bound); } +#endif // BC_ENABLE_EXTRA_MATH + #endif // BC_ENABLE_LIBRARY diff --git a/contrib/bc/src/main.c b/contrib/bc/src/main.c index 38c87a415f2..da4c2715602 100644 --- a/contrib/bc/src/main.c +++ b/contrib/bc/src/main.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -37,7 +37,9 @@ #include #include +#if BC_ENABLE_NLS #include +#endif // BC_ENABLE_NLS #ifndef _WIN32 #include @@ -51,46 +53,76 @@ #include #include -int main(int argc, char *argv[]) { - - char *name; +int +main(int argc, const char* argv[]) +{ + BcStatus s; + char* name; size_t len = strlen(BC_EXECPREFIX); +#if BC_ENABLE_NLS // Must set the locale properly in order to have the right error messages. - vm.locale = setlocale(LC_ALL, ""); + vm->locale = setlocale(LC_ALL, ""); +#endif // BC_ENABLE_NLS // Set the start pledge(). bc_pledge(bc_pledge_start, NULL); - // Figure out the name of the calculator we are using. We can't use basename - // because it's not portable, but yes, this is stripping off the directory. - name = strrchr(argv[0], BC_FILE_SEP); - vm.name = (name == NULL) ? argv[0] : name + 1; + // Sometimes, argv[0] can be NULL. Better make sure to be robust against it. + if (argv[0] != NULL) + { + // Figure out the name of the calculator we are using. We can't use + // basename because it's not portable, but yes, this is stripping off + // the directory. + name = strrchr(argv[0], BC_FILE_SEP); + vm->name = (name == NULL) ? argv[0] : name + 1; + } + else + { +#if !DC_ENABLED + vm->name = "bc"; +#elif !BC_ENABLED + vm->name = "dc"; +#else + // Just default to bc in that case. + vm->name = "bc"; +#endif + } // If the name is longer than the length of the prefix, skip the prefix. - if (strlen(vm.name) > len) vm.name += len; + if (strlen(vm->name) > len) vm->name += len; BC_SIG_LOCK; // We *must* do this here. Otherwise, other code could not jump out all of // the way. - bc_vec_init(&vm.jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); + bc_vec_init(&vm->jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); - BC_SETJMP_LOCKED(exit); + BC_SETJMP_LOCKED(vm, exit); +#if BC_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-qual" +#endif // BC_CLANG #if !DC_ENABLED - bc_main(argc, argv); + s = bc_main(argc, (const char**) argv); #elif !BC_ENABLED - dc_main(argc, argv); + s = dc_main(argc, (const char**) argv); #else - // BC_IS_BC uses vm.name, which was set above. So we're good. - if (BC_IS_BC) bc_main(argc, argv); - else dc_main(argc, argv); + // BC_IS_BC uses vm->name, which was set above. So we're good. + if (BC_IS_BC) s = bc_main(argc, (const char**) argv); + else s = dc_main(argc, (const char**) argv); #endif +#if BC_CLANG +#pragma clang diagnostic pop +#endif // BC_CLANG + + vm->status = (sig_atomic_t) s; exit: BC_SIG_MAYLOCK; - // Ensure we exit appropriately. - return bc_vm_atexit((int) vm.status); + s = bc_vm_atexit((BcStatus) vm->status); + + return (int) s; } diff --git a/contrib/bc/src/num.c b/contrib/bc/src/num.c index dc3f63ab076..83f84edb91f 100644 --- a/contrib/bc/src/num.c +++ b/contrib/bc/src/num.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -44,11 +44,15 @@ #include #include #include +#if BC_ENABLE_LIBRARY +#include +#endif // BC_ENABLE_LIBRARY // 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); +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. @@ -56,7 +60,9 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale); * @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) { +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; @@ -68,7 +74,9 @@ static inline size_t bc_num_mulOverflow(size_t a, size_t b) { * @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) { +static inline ssize_t +bc_num_neg(size_t n, bool neg) +{ return (((ssize_t) n) ^ -((ssize_t) neg)) + neg; } @@ -77,7 +85,9 @@ static inline ssize_t bc_num_neg(size_t n, bool neg) { * @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) { +ssize_t +bc_num_cmpZero(const BcNum* n) +{ return bc_num_neg((n)->len != 0, BC_NUM_NEG(n)); } @@ -86,7 +96,9 @@ ssize_t bc_num_cmpZero(const BcNum *n) { * @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) { +static inline size_t +bc_num_int(const BcNum* n) +{ return n->len ? n->len - BC_NUM_RDX_VAL(n) : 0; } @@ -95,14 +107,15 @@ static inline size_t bc_num_int(const BcNum *n) { * @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) { - +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) { - + if (req > n->cap) + { BC_SIG_LOCK; n->num = bc_vm_realloc(n->num, BC_NUM_SIZE(req)); @@ -117,17 +130,23 @@ static void bc_num_expand(BcNum *restrict n, size_t req) { * @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) { +static inline 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) { +void +bc_num_zero(BcNum* restrict n) +{ bc_num_setToZero(n, 0); } -void bc_num_one(BcNum *restrict n) { +void +bc_num_one(BcNum* restrict n) +{ bc_num_zero(n); n->len = 1; n->num[0] = 1; @@ -138,15 +157,19 @@ void bc_num_one(BcNum *restrict n) { * limbs are zero. * @param n The number to clean. */ -static void bc_num_clean(BcNum *restrict n) { - +static void +bc_num_clean(BcNum* restrict n) +{ // Reduce the length. - while (BC_NUM_NONZERO(n) && !n->num[n->len - 1]) n->len -= 1; + while (BC_NUM_NONZERO(n) && !n->num[n->len - 1]) + { + n->len -= 1; + } // Special cases. if (BC_NUM_ZERO(n)) n->rdx = 0; - else { - + 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; @@ -161,10 +184,18 @@ static void bc_num_clean(BcNum *restrict n) { * @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) { +static size_t +bc_num_log10(size_t i) +{ size_t len; - for (len = 1; i; i /= BC_BASE, ++len); + + for (len = 1; i; i /= BC_BASE, ++len) + { + continue; + } + assert(len - 1 <= BC_BASE_DIGS + 1); + return len - 1; } @@ -175,19 +206,43 @@ static size_t bc_num_log10(size_t i) { * @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) { +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); } +/** + * Returns the power of 10 that the least significant limb should be multiplied + * by to put its digits in the right place. For example, if the scale only + * reaches 8 places into the limb, this will return 1 (because it should be + * multiplied by 10^1) to put the number in the correct place. + * @param scale The scale. + * @return The power of 10 that the least significant limb should be + * multiplied by + */ +static inline size_t +bc_num_leastSigPow(size_t scale) +{ + size_t digs; + + digs = scale % BC_BASE_DIGS; + digs = digs != 0 ? BC_BASE_DIGS - digs : 0; + + return bc_num_pow10[digs]; +} + /** * 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) { +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; @@ -202,14 +257,54 @@ static size_t bc_num_intDigits(const BcNum *n) { * @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) { +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); + + for (i = len - 1; i < len && !n->num[i]; --i) + { + continue; + } + assert(i + 1 > 0); + return i + 1; } +#if BC_ENABLE_EXTRA_MATH + +/** + * Returns the power of 10 that a number with an absolute value less than 1 + * needs to be multiplied by in order to be greater than 1 or less than -1. + * @param n The number. + * @return The power of 10 that a number greater than 1 and less than -1 must + * be multiplied by to be greater than 1 or less than -1. + */ +static size_t +bc_num_negPow10(const BcNum* restrict n) +{ + // Figure out how many limbs after the decimal point is zero. + size_t i, places, 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. + return places + (BC_NUM_RDX_VAL(n) - (idx + 1)) * BC_BASE_DIGS; +} + +#endif // BC_ENABLE_EXTRA_MATH + /** * Performs a one-limb add with a carry. * @param a The first limb. @@ -218,11 +313,12 @@ static size_t bc_num_nonZeroLen(const BcNum *restrict n) { * carry out from this add. * @return The resulting limb sum. */ -static BcDig bc_num_addDigits(BcDig a, BcDig b, bool *carry) { - +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); + assert(a < BC_BASE_POW && a >= 0); + assert(b < BC_BASE_POW && b >= 0); a += b + *carry; *carry = (a >= BC_BASE_POW); @@ -242,10 +338,11 @@ static BcDig bc_num_addDigits(BcDig a, BcDig b, bool *carry) { * 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); +static BcDig +bc_num_subDigits(BcDig a, BcDig b, bool* carry) +{ + assert(a < BC_BASE_POW && a >= 0); + assert(b < BC_BASE_POW && b >= 0); b += *carry; *carry = (a < b); @@ -263,16 +360,22 @@ static BcDig bc_num_subDigits(BcDig a, BcDig b, bool *carry) { * @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) +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); + 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); + for (; carry; ++i) + { + a[i] = bc_num_addDigits(a[i], 0, &carry); + } } /** @@ -281,16 +384,22 @@ static void bc_num_addArrays(BcDig *restrict a, const BcDig *restrict b, * @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) +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); + 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); + for (; carry; ++i) + { + a[i] = bc_num_subDigits(a[i], 0, &carry); + } } /** @@ -300,8 +409,8 @@ static void bc_num_subArrays(BcDig *restrict a, const BcDig *restrict b, * @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) +static void +bc_num_mulArray(const BcNum* restrict a, BcBigDig b, BcNum* restrict c) { size_t i; BcBigDig carry = 0; @@ -312,10 +421,12 @@ static void bc_num_mulArray(const BcNum *restrict a, BcBigDig b, 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. + // NOLINTNEXTLINE memset(c->num, 0, BC_NUM_SIZE(c->cap)); // Actual multiplication loop. - for (i = 0; i < a->len; ++i) { + 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; @@ -325,6 +436,7 @@ static void bc_num_mulArray(const BcNum *restrict a, BcBigDig b, // Finishing touches. c->num[i] = (BcDig) carry; + assert(c->num[i] >= 0 && c->num[i] < BC_BASE_POW); c->len = a->len; c->len += (carry != 0); @@ -344,8 +456,9 @@ static void bc_num_mulArray(const BcNum *restrict a, BcBigDig b, * @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) +static void +bc_num_divArray(const BcNum* restrict a, BcBigDig b, BcNum* restrict c, + BcBigDig* rem) { size_t i; BcBigDig carry = 0; @@ -353,10 +466,12 @@ static void bc_num_divArray(const BcNum *restrict a, BcBigDig b, assert(c->cap >= a->len); // Actual division loop. - for (i = a->len - 1; i < a->len; --i) { + 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); + assert(c->num[i] >= 0 && c->num[i] < BC_BASE_POW); carry = in % b; } @@ -378,19 +493,24 @@ static void bc_num_divArray(const BcNum *restrict a, BcBigDig b, * @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) +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); + for (i = len - 1; i < len && !(c = a[i] - b[i]); --i) + { + continue; + } return bc_num_neg(i + 1, c < 0); } -ssize_t bc_num_cmp(const BcNum *a, const BcNum *b) { - +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; + BcDig* max_num; + BcDig* min_num; bool a_max, neg = false; ssize_t cmp; @@ -402,7 +522,8 @@ ssize_t bc_num_cmp(const BcNum *a, const BcNum *b) { // 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(a)) + { if (BC_NUM_NEG(b)) neg = true; else return -1; } @@ -422,13 +543,15 @@ ssize_t bc_num_cmp(const BcNum *a, const BcNum *b) { a_max = (ardx > brdx); // Set variables based on the above. - if (a_max) { + if (a_max) + { min = brdx; diff = ardx - brdx; max_num = a->num + diff; min_num = b->num; } - else { + else + { min = ardx; diff = brdx - ardx; max_num = b->num + diff; @@ -443,15 +566,17 @@ ssize_t bc_num_cmp(const BcNum *a, const BcNum *b) { // 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) { + 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) { - +void +bc_num_truncate(BcNum* restrict n, size_t places) +{ size_t nrdx, places_rdx; if (!places) return; @@ -468,20 +593,19 @@ void bc_num_truncate(BcNum *restrict n, size_t 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)) { - + 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]; + // limb, then gets the power for that. + pow = bc_num_leastSigPow(n->scale); n->len -= places_rdx; // We have to move limbs to maintain invariants. The limbs must begin at // the beginning of the BcNum array. + // NOLINTNEXTLINE memmove(n->num, n->num + places_rdx, BC_NUM_SIZE(n->len)); // Clear the lower part of the last digit. @@ -491,14 +615,16 @@ void bc_num_truncate(BcNum *restrict n, size_t places) { } } -void bc_num_extend(BcNum *restrict n, size_t places) { - +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)) { + if (BC_NUM_ZERO(n)) + { n->scale += places; return; } @@ -510,9 +636,12 @@ void bc_num_extend(BcNum *restrict n, size_t places) { // 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) { + if (places_rdx) + { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); + // NOLINTNEXTLINE memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); + // NOLINTNEXTLINE memset(n->num, 0, BC_NUM_SIZE(places_rdx)); } @@ -527,8 +656,8 @@ void bc_num_extend(BcNum *restrict n, size_t places) { /** * Retires (finishes) a multiplication or division operation. */ -static void bc_num_retireMul(BcNum *restrict n, size_t scale, - bool neg1, bool neg2) +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); @@ -547,16 +676,17 @@ static void bc_num_retireMul(BcNum *restrict n, size_t scale, * @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) +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) { - + if (idx < n->len) + { // Set the fields first. b->len = n->len - idx; a->len = idx; @@ -569,7 +699,9 @@ static void bc_num_split(const BcNum *restrict n, size_t idx, // Copy the arrays. This is not necessary for safety, but it is faster, // for some reason. + // NOLINTNEXTLINE memcpy(b->num, n->num + idx, BC_NUM_SIZE(b->len)); + // NOLINTNEXTLINE memcpy(a->num, n->num, BC_NUM_SIZE(idx)); bc_num_clean(b); @@ -586,8 +718,9 @@ static void bc_num_split(const BcNum *restrict n, size_t idx, * @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) { - +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; @@ -603,15 +736,20 @@ static void bc_num_shiftRdx(const BcNum *restrict n, BcNum *restrict r) { * 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; +static size_t +bc_num_shiftZero(BcNum* restrict n) +{ + // This is volatile to quiet a GCC warning about longjmp() clobbering. + volatile 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); + for (i = 0; i < n->len && !n->num[i]; ++i) + { + continue; + } n->len -= i; n->num += i; @@ -625,7 +763,9 @@ static size_t bc_num_shiftZero(BcNum *restrict n) { * @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) { +static void +bc_num_unshiftZero(BcNum* restrict n, size_t places_rdx) +{ n->len += places_rdx; n->num -= places_rdx; } @@ -638,11 +778,12 @@ static void bc_num_unshiftZero(BcNum *restrict n, size_t places_rdx) { * @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) { - +static void +bc_num_shift(BcNum* restrict n, BcBigDig dig) +{ size_t i, len = n->len; BcBigDig carry = 0, pow; - BcDig *ptr = n->num; + BcDig* ptr = n->num; assert(dig < BC_BASE_DIGS); @@ -652,12 +793,14 @@ static void bc_num_shift(BcNum *restrict n, BcBigDig 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) { + 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(ptr[i] >= 0 && ptr[i] < BC_BASE_POW); } assert(!carry); @@ -669,8 +812,9 @@ static void bc_num_shift(BcNum *restrict n, BcBigDig dig) { * @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) { - +static void +bc_num_shiftLeft(BcNum* restrict n, size_t places) +{ BcBigDig dig; size_t places_rdx; bool shift; @@ -678,13 +822,15 @@ static void bc_num_shiftLeft(BcNum *restrict n, size_t places) { if (!places) return; // Make sure to grow the number if necessary. - if (places > n->scale) { + 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 (BC_NUM_ZERO(n)) + { if (n->scale >= places) n->scale -= places; else n->scale = 0; return; @@ -705,13 +851,13 @@ static void bc_num_shiftLeft(BcNum *restrict n, size_t places) { // 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) { - + 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) { - + 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 @@ -729,19 +875,24 @@ static void bc_num_shiftLeft(BcNum *restrict n, size_t places) { } // If this is non-zero, we need an extra place, so expand, move, and set. - if (places_rdx) { + if (places_rdx) + { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); + // NOLINTNEXTLINE memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); + // NOLINTNEXTLINE memset(n->num, 0, BC_NUM_SIZE(places_rdx)); n->len += places_rdx; } // Set the scale appropriately. - if (places > n->scale) { + if (places > n->scale) + { n->scale = 0; BC_NUM_RDX_SET(n, 0); } - else { + else + { n->scale -= places; BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); } @@ -752,8 +903,9 @@ static void bc_num_shiftLeft(BcNum *restrict n, size_t places) { bc_num_clean(n); } -void bc_num_shiftRight(BcNum *restrict n, size_t places) { - +void +bc_num_shiftRight(BcNum* restrict n, size_t places) +{ BcBigDig dig; size_t places_rdx, scale, scale_mod, int_len, expand; bool shift; @@ -761,7 +913,8 @@ void bc_num_shiftRight(BcNum *restrict n, size_t places) { if (!places) return; // If zero, we can just set the scale and bail. - if (BC_NUM_ZERO(n)) { + if (BC_NUM_ZERO(n)) + { n->scale += places; bc_num_expand(n, BC_NUM_RDX(n->scale)); return; @@ -782,11 +935,13 @@ void bc_num_shiftRight(BcNum *restrict n, size_t places) { 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) { + if (scale_mod + dig > BC_BASE_DIGS) + { expand = places_rdx - 1; places_rdx = 1; } - else { + else + { expand = places_rdx; places_rdx = 0; } @@ -798,6 +953,7 @@ void bc_num_shiftRight(BcNum *restrict n, size_t places) { // Extend, expand, and zero. bc_num_extend(n, places_rdx * BC_BASE_DIGS); bc_num_expand(n, bc_vm_growSize(expand, n->len)); + // NOLINTNEXTLINE memset(n->num + n->len, 0, BC_NUM_SIZE(expand)); // Set the fields. @@ -817,17 +973,6 @@ void bc_num_shiftRight(BcNum *restrict n, size_t places) { 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 @@ -837,19 +982,25 @@ static inline void bc_num_inv(BcNum *a, BcNum *b, size_t scale) { * *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) { - +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) { + if (!rdx) + { + // NOLINTNEXTLINE memcpy(r, n, sizeof(BcNum)); return false; } zero = true; - for (i = 0; zero && i < rdx; ++i) zero = (n->num[i] == 0); + for (i = 0; zero && i < rdx; ++i) + { + zero = (n->num[i] == 0); + } if (BC_ERR(!zero)) return true; @@ -868,10 +1019,17 @@ static bool bc_num_nonInt(const BcNum *restrict n, BcNum *restrict r) { * @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) +static BcBigDig +bc_num_intop(const BcNum* a, const BcNum* b, BcNum* restrict c) { BcNum temp; +#if BC_GCC + temp.len = 0; + temp.rdx = 0; + temp.num = NULL; +#endif // BC_GCC + if (BC_ERR(bc_num_nonInt(b, &temp))) bc_err(BC_ERR_MATH_NON_INTEGER); bc_num_copy(c, a); @@ -890,19 +1048,24 @@ static BcBigDig bc_num_intop(const BcNum *a, const BcNum *b, BcNum *restrict c) * @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; +static void +bc_num_as(BcNum* a, BcNum* b, BcNum* restrict c, size_t sub) +{ + BcDig* ptr_c; + BcDig* ptr_l; + BcDig* 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)) { + if (BC_NUM_ZERO(b)) + { bc_num_copy(c, a); return; } - if (BC_NUM_ZERO(a)) { + if (BC_NUM_ZERO(a)) + { bc_num_copy(c, b); c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(b) != sub); return; @@ -930,17 +1093,18 @@ static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { max_len = max_int + max_rdx; - if (do_sub) { - + 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 do_rev_sub = (bc_num_compare(a->num, b->num + diff, a->len) <= 0); } - else { - + else + { // The result array of the addition might come out one element // longer than the bigger of the operand arrays. max_len += 1; @@ -950,13 +1114,15 @@ static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { assert(max_len <= c->cap); // Cache values for simple code later. - if (do_rev_sub) { + if (do_rev_sub) + { ptr_l = b->num; ptr_r = a->num; len_l = b->len; len_r = a->len; } - else { + else + { ptr_l = a->num; ptr_r = b->num; len_l = a->len; @@ -968,34 +1134,38 @@ static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { // This is true if the numbers have a different number of limbs after the // decimal point. - if (diff) { - + 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) { - + 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). + // NOLINTNEXTLINE memcpy(ptr_c, ptr_l, BC_NUM_SIZE(diff)); ptr_l += diff; len_l -= diff; } - else { - + else + { // The right operand has BcDig values that need to be copied // or subtracted from zero (in case of a subtraction). - if (do_sub) { - + 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 { - + else + { // !do_sub && brdx > ardx + // NOLINTNEXTLINE memcpy(ptr_c, ptr_r, BC_NUM_SIZE(diff)); } @@ -1018,23 +1188,33 @@ static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { // 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) { - + 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); + for (; i < len_l; ++i) + { + ptr_c[i] = bc_num_subDigits(ptr_l[i], 0, &carry); + } } - else { - + 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); + 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); @@ -1060,10 +1240,13 @@ static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { * @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) { - +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; + BcDig* ptr_a = a->num; + BcDig* ptr_b = b->num; + BcDig* ptr_c; BcBigDig sum = 0, carry = 0; assert(sizeof(sum) >= sizeof(BcDig) * 2); @@ -1075,14 +1258,15 @@ static void bc_num_m_simp(const BcNum *a, const BcNum *b, BcNum *restrict c) { // If we don't memset, then we might have uninitialized data use later. ptr_c = c->num; + // NOLINTNEXTLINE 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) { - + for (i = 0; i < clen; ++i) + { ssize_t sidx = (ssize_t) (i - blen + 1); size_t j, k; @@ -1092,18 +1276,20 @@ static void bc_num_m_simp(const BcNum *a, const BcNum *b, BcNum *restrict c) { // On every iteration of this loop, a multiplication happens, then the // sum is automatically calculated. - for (; j < alen && k < blen; ++j, --k) { - + 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) { + 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) { + if (sum >= BC_BASE_POW) + { carry += sum / BC_BASE_POW; sum %= BC_BASE_POW; } @@ -1131,8 +1317,9 @@ static void bc_num_m_simp(const BcNum *a, const BcNum *b, BcNum *restrict c) { * @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) +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)); @@ -1142,26 +1329,33 @@ static void bc_num_shiftAddSub(BcNum *restrict n, const BcNum *restrict a, /** * Implements the Karatsuba algorithm. */ -static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { - +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; + BcDig* digs; + BcDig* dig_ptr; BcNumShiftAddOp op; bool aone = BC_NUM_ONE(a); +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(BC_NUM_ZERO(c)); if (BC_NUM_ZERO(a) || BC_NUM_ZERO(b)) return; - if (aone || BC_NUM_ONE(b)) { + 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) { + if (a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN) + { bc_num_m_simp(a, b, c); return; } @@ -1203,13 +1397,14 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { max = bc_vm_growSize(max, max) + 1; bc_num_init(&temp, max); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // First, set up c. bc_num_expand(c, max); c->len = max; + // NOLINTNEXTLINE memset(c->num, 0, BC_NUM_SIZE(c->len)); // Split the parameters. @@ -1225,8 +1420,8 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { // the ollocations and splits are done, the algorithm is pretty // straightforward. - if (BC_NUM_NONZERO(&h1) && BC_NUM_NONZERO(&h2)) { - + if (BC_NUM_NONZERO(&h1) && BC_NUM_NONZERO(&h2)) + { assert(BC_NUM_RDX_VALID_NP(h1)); assert(BC_NUM_RDX_VALID_NP(h2)); @@ -1237,8 +1432,8 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { bc_num_shiftAddSub(c, &z2, max2, bc_num_addArrays); } - if (BC_NUM_NONZERO(&l1) && BC_NUM_NONZERO(&l2)) { - + if (BC_NUM_NONZERO(&l1) && BC_NUM_NONZERO(&l2)) + { assert(BC_NUM_RDX_VALID_NP(l1)); assert(BC_NUM_RDX_VALID_NP(l2)); @@ -1249,8 +1444,8 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { bc_num_shiftAddSub(c, &z0, 0, bc_num_addArrays); } - if (BC_NUM_NONZERO(&m1) && BC_NUM_NONZERO(&m2)) { - + if (BC_NUM_NONZERO(&m1) && BC_NUM_NONZERO(&m2)) + { assert(BC_NUM_RDX_VALID_NP(m1)); assert(BC_NUM_RDX_VALID_NP(m1)); @@ -1258,7 +1453,8 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { bc_num_clean(&z1); op = (BC_NUM_NEG_NP(m1) != BC_NUM_NEG_NP(m2)) ? - bc_num_subArrays : bc_num_addArrays; + bc_num_subArrays : + bc_num_addArrays; bc_num_shiftAddSub(c, &z1, max2, op); } @@ -1269,7 +1465,7 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { bc_num_free(&z2); bc_num_free(&z1); bc_num_free(&z0); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1281,10 +1477,21 @@ static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) { * @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) { - +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; + size_t ascale, bscale, ardx, brdx, zero, len, rscale; + // These are meant to quiet warnings on GCC about longjmp() clobbering. + // The problem is real here. + size_t scale1, scale2, realscale; + // These are meant to quiet the GCC longjmp() clobbering, even though it + // does not apply here. + volatile size_t azero; + volatile size_t bzero; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); @@ -1295,24 +1502,26 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { bscale = b->scale; // This sets the final scale according to the bc spec. - scale = BC_MAX(scale, ascale); - scale = BC_MAX(scale, bscale); + scale1 = BC_MAX(scale, ascale); + scale2 = BC_MAX(scale1, bscale); rscale = ascale + bscale; - scale = BC_MIN(rscale, scale); + realscale = BC_MIN(rscale, scale2); // 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; + if ((a->len == 1 || b->len == 1) && !a->rdx && !b->rdx) + { + BcNum* operand; BcBigDig dig; // Set the correct operands. - if (a->len == 1) { + if (a->len == 1) + { dig = (BcBigDig) a->num[0]; operand = b; } - else { + else + { dig = (BcBigDig) b->num[0]; operand = a; } @@ -1321,7 +1530,9 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { // 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; } @@ -1336,7 +1547,7 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { 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_SETJMP_LOCKED(vm, init_err); BC_SIG_UNLOCK; @@ -1364,13 +1575,13 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { // jump. BC_SIG_LOCK; - BC_UNSETJMP; + BC_UNSETJMP(vm); // We want to ignore zero limbs. azero = bc_num_shiftZero(&cpa); bzero = bc_num_shiftZero(&cpb); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -1391,15 +1602,17 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { 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)); + bc_num_retireMul(c, realscale, 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); +init_err: + BC_SIG_MAYLOCK; + bc_num_free(&cpb); bc_num_free(&cpa); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1408,11 +1621,17 @@ static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { * @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) { +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; + + for (i = len - 1; i < len; --i) + { + if (a[i] != 0) return true; + } + + return false; } /** @@ -1424,12 +1643,14 @@ static bool bc_num_nonZeroDig(BcDig *restrict a, size_t len) { * @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) { - +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) { + else if (b->len <= len) + { if (a[len]) cmp = 1; else cmp = bc_num_compare(a, b->num, len); } @@ -1446,8 +1667,8 @@ static ssize_t bc_num_divCmp(const BcDig *a, const BcNum *b, size_t len) { * @param b The second operand. * @param divisor The divisor estimate. */ -static void bc_num_divExtend(BcNum *restrict a, BcNum *restrict b, - BcBigDig divisor) +static void +bc_num_divExtend(BcNum* restrict a, BcNum* restrict b, BcBigDig divisor) { size_t pow; @@ -1467,13 +1688,28 @@ static void bc_num_divExtend(BcNum *restrict a, BcNum *restrict b, * @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) +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; + size_t i, rdx; + // This is volatile and len 2 and reallen exist to quiet the GCC warning + // about clobbering on longjmp(). This one is possible, I think. + volatile size_t len; + size_t len2, reallen; + // This is volatile and realend exists to quiet the GCC warning about + // clobbering on longjmp(). This one is possible, I think. + volatile size_t end; + size_t realend; BcNum cpb; - bool nonzero = false; + // This is volatile and realnonzero exists to quiet the GCC warning about + // clobbering on longjmp(). This one is possible, I think. + volatile bool nonzero; + bool realnonzero; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(b->len < a->len); @@ -1485,6 +1721,7 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, // 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); + // NOLINTNEXTLINE memset(c->num, 0, c->cap * sizeof(BcDig)); // Setup. @@ -1498,8 +1735,8 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, // 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)) { - + 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 @@ -1509,36 +1746,47 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, nonzero = (divisor > 1 << ((10 * BC_BASE_DIGS) / 6 + 1)); // If the divisor is *not* greater than half the limb... - if (!nonzero) { - + 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); + len2 = BC_MAX(a->len, b->len); + bc_num_expand(a, len2 + 1); // Make a have a zero most significant limb to match the len. - if (len + 1 > a->len) a->len = len + 1; + if (len2 + 1 > a->len) a->len = len2 + 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]; + reallen = b->len; + realend = a->len - reallen; + divisor = (BcBigDig) b->num[reallen - 1]; - nonzero = bc_num_nonZeroDig(b->num, len - 1); + realnonzero = bc_num_nonZeroDig(b->num, reallen - 1); } + else + { + realend = end; + realnonzero = nonzero; + } + } + else + { + realend = end; + realnonzero = false; } // If b has other nonzero limbs, we want the divisor to be one higher, so // that it is an upper bound. - divisor += nonzero; + divisor += realnonzero; // Make sure c can fit the new length. bc_num_expand(c, a->len); + // NOLINTNEXTLINE memset(c->num, 0, BC_NUM_SIZE(c->cap)); assert(c->scale >= scale); @@ -1548,15 +1796,15 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, bc_num_init(&cpb, len + 1); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // This is the actual division loop. - for (i = end - 1; i < end && i >= rdx && BC_NUM_NONZERO(a); --i) { - + for (i = realend - 1; i < realend && i >= rdx && BC_NUM_NONZERO(a); --i) + { ssize_t cmp; - BcDig *n; + BcDig* n; BcBigDig result; n = a->num + i; @@ -1568,8 +1816,8 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, // 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) { - + while (cmp >= 0) + { BcBigDig n1, dividend, quotient; // These should be named obviously enough. Just imagine that it's a @@ -1581,12 +1829,13 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, // 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) { + if (quotient <= 1) + { quotient = 1; bc_num_subArrays(n, b->num, len); } - else { - + else + { assert(quotient <= BC_BASE_POW); // We need to multiply and subtract for a quotient above 1. @@ -1602,7 +1851,7 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, // 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); + if (realnonzero) cmp = bc_num_divCmp(n, b, len); else cmp = -1; } @@ -1615,7 +1864,7 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, err: BC_SIG_MAYLOCK; bc_num_free(&cpb); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1625,26 +1874,33 @@ static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, * @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) { - +static void +bc_num_d(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) +{ size_t len, cpardx; BcNum cpa, cpb; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY if (BC_NUM_ZERO(b)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO); - if (BC_NUM_ZERO(a)) { + if (BC_NUM_ZERO(a)) + { bc_num_setToZero(c, scale); return; } - if (BC_NUM_ONE(b)) { + 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) { + 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)); @@ -1662,7 +1918,7 @@ static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { bc_num_copy(&cpa, a); bc_num_createCopy(&cpb, b); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -1670,7 +1926,8 @@ static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { // Like the above comment, we want the copy of the first parameter to be // larger than the second parameter. - if (len > cpa.len) { + if (len > cpa.len) + { bc_num_expand(&cpa, bc_vm_growSize(len, 2)); bc_num_extend(&cpa, (len - cpa.len) * BC_BASE_DIGS); } @@ -1685,7 +1942,8 @@ static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { cpa.scale = cpardx * BC_BASE_DIGS; // Once again, just setting things up, this time to match scale. - if (scale > cpa.scale) { + if (scale > cpa.scale) + { bc_num_extend(&cpa, scale); cpardx = BC_NUM_RDX_VAL_NP(cpa); cpa.scale = cpardx * BC_BASE_DIGS; @@ -1702,6 +1960,9 @@ static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { // 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. + // + // But in short, this setup makes it so bc_num_d_long() can pretend the + // numbers are integers. 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; @@ -1715,7 +1976,7 @@ static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BC_SIG_MAYLOCK; bc_num_free(&cpb); bc_num_free(&cpa); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1730,15 +1991,23 @@ static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t 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) +static void +bc_num_r(BcNum* a, BcNum* b, BcNum* restrict c, BcNum* restrict d, size_t scale, + size_t ts) { BcNum temp; + // realscale is meant to quiet a warning on GCC about longjmp() clobbering. + // This one is real. + size_t realscale; bool neg; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY if (BC_NUM_ZERO(b)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO); - if (BC_NUM_ZERO(a)) { + if (BC_NUM_ZERO(a)) + { bc_num_setToZero(c, ts); bc_num_setToZero(d, ts); return; @@ -1748,7 +2017,7 @@ static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c, bc_num_init(&temp, d->cap); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -1756,14 +2025,15 @@ static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c, bc_num_d(a, b, c, scale); // We want an extra digit so we can safely truncate. - if (scale) scale = ts + 1; + if (scale) realscale = ts + 1; + else realscale = scale; 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); + bc_num_m(c, b, &temp, realscale); + bc_num_sub(a, &temp, d, realscale); // Extend if necessary. if (ts > d->scale && BC_NUM_NONZERO(d)) bc_num_extend(d, ts - d->scale); @@ -1775,7 +2045,7 @@ static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c, err: BC_SIG_MAYLOCK; bc_num_free(&temp); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1786,10 +2056,14 @@ static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c, * @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) { - +static void +bc_num_rem(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) +{ BcNum c1; size_t ts; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY ts = bc_vm_growSize(scale, b->scale); ts = BC_MAX(ts, a->scale); @@ -1799,7 +2073,7 @@ static void bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { // Need a temp for the quotient. bc_num_init(&c1, bc_num_mulReq(a, b, ts)); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -1808,7 +2082,7 @@ static void bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { err: BC_SIG_MAYLOCK; bc_num_free(&c1); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1818,27 +2092,45 @@ static void bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { * @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) { - +static void +bc_num_p(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) +{ BcNum copy, btemp; BcBigDig exp; - size_t powrdx, resrdx; + // realscale is meant to quiet a warning on GCC about longjmp() clobbering. + // This one is real. + size_t powrdx, resrdx, realscale; bool neg; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY + + // This is here to silence a warning from GCC. +#if BC_GCC + btemp.len = 0; + btemp.rdx = 0; + btemp.num = NULL; +#endif // BC_GCC if (BC_ERR(bc_num_nonInt(b, &btemp))) bc_err(BC_ERR_MATH_NON_INTEGER); - if (BC_NUM_ZERO(&btemp)) { + assert(btemp.len == 0 || btemp.num != NULL); + + if (BC_NUM_ZERO(&btemp)) + { bc_num_one(c); return; } - if (BC_NUM_ZERO(a)) { + 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_ONE(&btemp)) + { if (!BC_NUM_NEG_NP(btemp)) bc_num_copy(c, a); else bc_num_inv(a, c, scale); return; @@ -1853,21 +2145,24 @@ static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { bc_num_createCopy(©, a); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, 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) { + if (!neg) + { size_t max = BC_MAX(scale, a->scale), scalepow; scalepow = bc_num_mulOverflow(a->scale, exp); - scale = BC_MIN(scalepow, max); + realscale = BC_MIN(scalepow, max); } + else realscale = scale; // 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) { + for (powrdx = a->scale; !(exp & 1); exp >>= 1) + { powrdx <<= 1; assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(©, ©, ©, powrdx); @@ -1880,15 +2175,16 @@ static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { // Now finish the exponentiation by squaring, this time saving the squares // as necessary. - while (exp >>= 1) { - + 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) { + if (exp & 1) + { resrdx += powrdx; assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VALID_NP(copy)); @@ -1897,17 +2193,17 @@ static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { } // Invert if necessary. - if (neg) bc_num_inv(c, c, scale); + if (neg) bc_num_inv(c, c, realscale); // Truncate if necessary. - if (c->scale > scale) bc_num_truncate(c, c->scale - scale); + if (c->scale > realscale) bc_num_truncate(c, c->scale - realscale); bc_num_clean(c); err: BC_SIG_MAYLOCK; bc_num_free(©); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } #if BC_ENABLE_EXTRA_MATH @@ -1918,8 +2214,9 @@ static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { * @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) { - +static void +bc_num_place(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) +{ BcBigDig val; BC_UNUSED(scale); @@ -1934,8 +2231,9 @@ static void bc_num_place(BcNum *a, BcNum *b, BcNum *restrict c, size_t 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) { - +static void +bc_num_left(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) +{ BcBigDig val; BC_UNUSED(scale); @@ -1948,8 +2246,9 @@ static void bc_num_left(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { /** * 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) { - +static void +bc_num_right(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) +{ BcBigDig val; BC_UNUSED(scale); @@ -1980,11 +2279,16 @@ static void bc_num_right(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { * @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) +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; + BcNum* ptr_a; + BcNum* ptr_b; + BcNum num2; +#if BC_ENABLE_LIBRARY + BcVm* vm = NULL; +#endif // BC_ENABLE_LIBRARY assert(a != NULL && b != NULL && c != NULL && op != NULL); @@ -1993,44 +2297,29 @@ static void bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale, 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; - } + ptr_a = c == a ? &num2 : a; + ptr_b = c == b ? &num2 : b; // Actually reallocate. If we don't reallocate, we want to expand at the // very least. - if (init) { + if (c == a || c == b) + { +#if BC_ENABLE_LIBRARY + vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY + + // NOLINTNEXTLINE + memcpy(&num2, c, sizeof(BcNum)); 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_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; } - else { + else + { BC_SIG_UNLOCK; bc_num_expand(c, req); } @@ -2049,15 +2338,14 @@ static void bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale, err: // Cleanup only needed if we initialized c to a new number. - if (init) { + if (c == a || c == b) + { BC_SIG_MAYLOCK; bc_num_free(&num2); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } } -#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 @@ -2067,8 +2355,9 @@ static void bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale, * @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 +bc_num_strValid(const char* restrict val) +{ bool radix = false; size_t i, len = strlen(val); @@ -2080,13 +2369,13 @@ bool bc_num_strValid(const char *restrict val) { if (!len) return true; // Loop through the characters. - for (i = 0; i < len; ++i) { - + for (i = 0; i < len; ++i) + { BcDig c = val[i]; // If we have found a radix point... - if (c == '.') { - + if (c == '.') + { // We don't allow two radices. if (radix) return false; @@ -2100,7 +2389,6 @@ bool bc_num_strValid(const char *restrict val) { return true; } -#endif // !defined(NDEBUG) || BC_ENABLE_LIBRARY /** * Parses one character and returns the digit that corresponds to that @@ -2109,18 +2397,26 @@ bool bc_num_strValid(const char *restrict val) { * @param base The base. * @return The character as a digit. */ -static BcBigDig bc_num_parseChar(char c, size_t base) { - +static BcBigDig +bc_num_parseChar(char c, size_t base) +{ assert(isupper(c) || isdigit(c)); // If a letter... - if (isupper(c)) { + if (isupper(c)) + { +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY // 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; + if (BC_DIGIT_CLAMP) + { + c = ((size_t) c) >= base ? (char) base - 1 : c; + } } // Straight convert the digit to a number. else c -= '0'; @@ -2134,14 +2430,21 @@ static BcBigDig bc_num_parseChar(char c, size_t base) { * @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) { - +static void +bc_num_parseDecimal(BcNum* restrict n, const char* restrict val) +{ size_t len, i, temp, mod; - const char *ptr; + const char* ptr; bool zero = true, rdx; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY // Eat leading zeroes. - for (i = 0; val[i] == '0'; ++i); + for (i = 0; val[i] == '0'; ++i) + { + continue; + } val += i; assert(!val[0] || isalnum(val[0]) || val[0] == '.'); @@ -2161,13 +2464,16 @@ static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) { // 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); + for (i = 0; i < len && (zero = (val[i] == '0' || val[i] == '.')); ++i) + { + continue; + } // 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))); + 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)); @@ -2180,17 +2486,20 @@ static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) { 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)); + // Expand and zero. The plus extra is in case the lack of clamping causes + // the number to overflow the original bounds. + bc_num_expand(n, n->len + !BC_DIGIT_CLAMP); + // NOLINTNEXTLINE + memset(n->num, 0, BC_NUM_SIZE(n->len + !BC_DIGIT_CLAMP)); - if (zero) { + 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 { - + else + { // There is actually stuff to parse if we make it here. Yay... BcBigDig exp, pow; @@ -2202,22 +2511,45 @@ static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) { // Parse loop. We parse backwards because numbers are stored little // endian. - for (i = len - 1; i < len; --i, ++exp) { - + for (i = len - 1; i < len; --i, ++exp) + { char c = val[i]; // Skip the decimal point. if (c == '.') exp -= 1; - else { - + 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; + BcBigDig dig; + + if (isupper(c)) + { + // Clamp for the base. + if (!BC_DIGIT_CLAMP) c = BC_NUM_NUM_LETTER(c); + else c = 9; + } + else c -= '0'; + + // Add the digit to the limb. This takes care of overflow from + // lack of clamping. + dig = ((BcBigDig) n->num[idx]) + ((BcBigDig) c) * pow; + if (dig >= BC_BASE_POW) + { + // We cannot go over BC_BASE_POW with clamping. + assert(!BC_DIGIT_CLAMP); + + n->num[idx + 1] = (BcDig) (dig / BC_BASE_POW); + n->num[idx] = (BcDig) (dig % BC_BASE_POW); + assert(n->num[idx] >= 0 && n->num[idx] < BC_BASE_POW); + assert(n->num[idx + 1] >= 0 && + n->num[idx + 1] < BC_BASE_POW); + } + else + { + n->num[idx] = (BcDig) dig; + assert(n->num[idx] >= 0 && n->num[idx] < BC_BASE_POW); + } // Adjust the power and exponent. if ((exp + 1) % BC_BASE_DIGS == 0) pow = 1; @@ -2225,6 +2557,9 @@ static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) { } } } + + // Make sure to add one to the length if needed from lack of clamping. + n->len += (!BC_DIGIT_CLAMP && n->num[n->len] != 0); } /** @@ -2233,17 +2568,28 @@ static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) { * @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) +static void +bc_num_parseBase(BcNum* restrict n, const char* restrict val, BcBigDig base) { - BcNum temp, mult1, mult2, result1, result2, *m1, *m2, *ptr; + BcNum temp, mult1, mult2, result1, result2; + BcNum* m1; + BcNum* m2; + BcNum* ptr; char c = 0; bool zero = true; BcBigDig v; - size_t i, digs, len = strlen(val); + size_t digs, len = strlen(val); + // This is volatile to quiet a warning on GCC about longjmp() clobbering. + volatile size_t i; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY // 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'); + for (i = 0; zero && i < len; ++i) + { + zero = (val[i] == '.' || val[i] == '0'); + } if (zero) return; BC_SIG_LOCK; @@ -2251,7 +2597,7 @@ static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, bc_num_init(&temp, BC_NUM_BIGDIG_LOG10); bc_num_init(&mult1, BC_NUM_BIGDIG_LOG10); - BC_SETJMP_LOCKED(int_err); + BC_SETJMP_LOCKED(vm, int_err); BC_SIG_UNLOCK; @@ -2260,8 +2606,8 @@ static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, // 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) { - + for (i = 0; i < len && (c = val[i]) && c != '.'; ++i) + { // Convert the character to a digit. v = bc_num_parseChar(c, base); @@ -2283,14 +2629,14 @@ static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, BC_SIG_LOCK; // Unset the jump to reset in for these new initializations. - BC_UNSETJMP; + BC_UNSETJMP(vm); 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_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -2299,8 +2645,8 @@ static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, m2 = &mult2; // Parse the fractional part. This is the hard part. - for (i += 1, digs = 0; i < len && (c = val[i]); ++i, ++digs) { - + for (i += 1, digs = 0; i < len && (c = val[i]); ++i, ++digs) + { size_t rdx; // Convert the character to a digit. @@ -2343,7 +2689,8 @@ static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, bc_num_add(n, &result2, n, digs); // Basic cleanup. - if (BC_NUM_NONZERO(n)) { + if (BC_NUM_NONZERO(n)) + { if (n->scale < digs) bc_num_extend(n, digs - n->scale); } else bc_num_zero(n); @@ -2357,16 +2704,19 @@ static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, BC_SIG_MAYLOCK; bc_num_free(&mult1); bc_num_free(&temp); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** * 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) { +static inline void +bc_num_printNewline(void) +{ #if !BC_ENABLE_LIBRARY - if (vm.nchars >= vm.line_len - 1 && vm.line_len) { + if (vm->nchars >= vm->line_len - 1 && vm->line_len) + { bc_vm_putchar('\\', bc_flush_none); bc_vm_putchar('\n', bc_flush_err); } @@ -2378,7 +2728,9 @@ static inline void bc_num_printNewline(void) { * @param c The character to print. * @param bslash Whether to print a backslash+newline. */ -static void bc_num_putchar(int c, bool bslash) { +static void +bc_num_putchar(int c, bool bslash) +{ if (c != '\n' && bslash) bc_num_printNewline(); bc_vm_putchar(c, bc_flush_save); } @@ -2396,7 +2748,9 @@ static void bc_num_putchar(int c, bool bslash) { * @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) { +static void +bc_num_printChar(size_t n, size_t len, bool rdx, bool bslash) +{ BC_UNUSED(rdx); BC_UNUSED(len); BC_UNUSED(bslash); @@ -2416,19 +2770,23 @@ static void bc_num_printChar(size_t n, size_t len, bool rdx, bool bslash) { * @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) { - +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); + for (exp = 0, pow = 1; exp < len - 1; ++exp, pow *= BC_BASE) + { + continue; + } // Print each character individually. - for (exp = 0; exp < len; pow /= BC_BASE, ++exp) { - + for (exp = 0; exp < len; pow /= BC_BASE, ++exp) + { // The individual subdigit. size_t dig = n / pow; @@ -2451,8 +2809,9 @@ static void bc_num_printDigits(size_t n, size_t len, bool rdx, bool bslash) { * @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) { - +static void +bc_num_printHex(size_t n, size_t len, bool rdx, bool bslash) +{ BC_UNUSED(len); BC_UNUSED(bslash); @@ -2469,15 +2828,16 @@ static void bc_num_printHex(size_t n, size_t len, bool rdx, bool bslash) { * @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) { - +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 loop. - for (i = n->len - 1; i < n->len; --i) { - + for (i = n->len - 1; i < n->len; --i) + { BcDig n9 = n->num[i]; size_t temp; bool irdx = (i == rdx - 1); @@ -2487,25 +2847,27 @@ static void bc_num_printDecimal(const BcNum *restrict n, bool newline) { temp = n->scale % BC_BASE_DIGS; temp = i || !temp ? 0 : BC_BASE_DIGS - temp; + // NOLINTNEXTLINE memset(buffer, 0, BC_BASE_DIGS * sizeof(size_t)); // Fill the buffer with individual digits. - for (j = 0; n9 && j < BC_BASE_DIGS; ++j) { + 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) { - + 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) { - + 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 @@ -2527,40 +2889,34 @@ static void bc_num_printDecimal(const BcNum *restrict n, bool newline) { * @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) +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]; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY BC_SIG_LOCK; bc_num_createCopy(&temp, n); - BC_SETJMP_LOCKED(exit); + BC_SETJMP_LOCKED(vm, 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; - } + if (neg) + { + // Figure out the negative power of 10. + places = bc_num_negPow10(n); - // Calculate the combination of zero limbs and zero digits in the last - // limb. - places += (nrdx - (idx + 1)) * BC_BASE_DIGS; + // Figure out how many digits mod 3 there are (important for + // engineering mode). mod = places % 3; // Calculate places if we are in engineering mode. @@ -2569,8 +2925,8 @@ static void bc_num_printExponent(const BcNum *restrict n, // Shift the temp to the right place. bc_num_shiftLeft(&temp, places); } - else { - + else + { // This is the number of digits that we are supposed to put behind the // decimal point. places = bc_num_intDigits(n) - 1; @@ -2591,7 +2947,8 @@ static void bc_num_printExponent(const BcNum *restrict n, bc_num_putchar('e', !newline); // Need to explicitly print a zero exponent. - if (!places) { + if (!places) + { bc_num_printHex(0, 1, false, !newline); goto exit; } @@ -2609,26 +2966,26 @@ static void bc_num_printExponent(const BcNum *restrict n, exit: BC_SIG_MAYLOCK; bc_num_free(&temp); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } #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. + * Takes a number with limbs with base BC_BASE_POW and converts the limb at the + * given index 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 + * least significant limb. */ -static void bc_num_printFixup(BcNum *restrict n, BcBigDig rem, - BcBigDig pow, size_t idx) +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; + 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(). @@ -2636,8 +2993,8 @@ static void bc_num_printFixup(BcNum *restrict n, BcBigDig rem, // 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) { - + 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. @@ -2651,11 +3008,11 @@ static void bc_num_printFixup(BcNum *restrict n, BcBigDig rem, acc += (BcBigDig) a[i]; // If the accumulator is greater than the base... - if (acc >= BC_BASE_POW) { - + if (acc >= BC_BASE_POW) + { // Do we need to grow? - if (i == len - 1) { - + if (i == len - 1) + { // Grow. len = bc_vm_growSize(len, 1); bc_num_expand(n, bc_vm_growSize(len, idx)); @@ -2683,34 +3040,38 @@ static void bc_num_printFixup(BcNum *restrict n, BcBigDig rem, } /** - * 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 + * Prepares a number for printing in a base that does not have BC_BASE_POW as a + * power. 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) { - +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); + 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) { - + for (i = 0; i < n->len; ++i) + { assert(pow == ((BcBigDig) ((BcDig) pow))); // If the limb needs fixing... - if (n->num[i] >= (BcDig) pow) { - + if (n->num[i] >= (BcDig) pow) + { // Do we need to grow? - if (i + 1 == n->len) { - + if (i + 1 == n->len) + { // Grow the number. n->len = bc_vm_growSize(n->len, 1); bc_num_expand(n, n->len); @@ -2728,20 +3089,29 @@ static void bc_num_printPrepare(BcNum *restrict n, BcBigDig rem, BcBigDig pow) { } } -static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, - BcNumDigitOp print, bool newline) +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; + BcNum intp, fracp1, fracp2, digit, flen1, flen2; + BcNum* n1; + BcNum* n2; + BcNum* temp; + BcBigDig dig = 0, acc, exp; + BcBigDig* ptr; size_t i, j, nrdx, idigits; bool radix; BcDig digit_digs[BC_NUM_BIGDIG_LOG10 + 1]; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(base > 1); // Easy case. Even with scale, we just print this. - if (BC_NUM_ZERO(n)) { + if (BC_NUM_ZERO(n)) + { print(0, len, false, !newline); return; } @@ -2795,7 +3165,7 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, // intp will be the "integer part" of the number, so copy it. bc_num_createCopy(&intp, n); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -2810,36 +3180,40 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, // 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; + 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; + 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; + vm->last_rem = BC_BASE_POW - vm->last_pow; + vm->last_base = base; } - exp = vm.last_exp; + exp = vm->last_exp; - // If vm.last_rem is 0, then the base we are printing in is a divisor of + // 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); + 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) { - + for (i = 0; i < intp.len; ++i) + { // Get the limb. acc = (BcBigDig) intp.num[i]; @@ -2847,11 +3221,13 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, 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) { + if (j != exp - 1) + { dig = acc % base; acc /= base; } - else { + else + { dig = acc; acc = 0; } @@ -2866,19 +3242,37 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, } // Go through the stack backwards and print each digit. - for (i = 0; i < stack.len; ++i) { - + 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)); + // needs explaining. I don't want to print a backslash+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. + // + // First, it needs to check if newlines are completely disabled. If they + // are not disabled, it needs to check the next part. + // + // If the number has a scale, then because we are printing just the + // integer part, there will be at least two more characters (a radix + // point plus at least one digit). So if there is a scale, a backslash + // is necessary. + // + // Finally, the last condition checks to see if we are at the end of the + // stack. If we are *not* (i.e., the index is not one less than the + // stack length), then a backslash is necessary because there is at + // least one more character for at least one more digit). Otherwise, if + // the index is equal to one less than the stack length, we want to + // disable backslash printing. + // + // The function that prints bases 17 and above will take care of not + // printing a backslash in the right case. + print(*ptr, len, false, + !newline || (n->scale != 0 || i < stack.len - 1)); } // We are done if there is no fractional part. @@ -2887,14 +3281,14 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, BC_SIG_LOCK; // Reset the jump because some locals are changing. - BC_UNSETJMP; + BC_UNSETJMP(vm); 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_SETJMP_LOCKED(vm, frac_err); BC_SIG_UNLOCK; @@ -2910,8 +3304,8 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, 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) { - + 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); @@ -2956,7 +3350,7 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, bc_num_free(&fracp1); bc_num_free(&intp); bc_vec_free(&stack); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -2966,8 +3360,9 @@ static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, * @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) { - +static void +bc_num_printBase(BcNum* restrict n, BcBigDig base, bool newline) +{ size_t width; BcNumDigitOp print; bool neg = BC_NUM_NEG(n); @@ -2978,11 +3373,13 @@ static void bc_num_printBase(BcNum *restrict n, BcBigDig base, bool newline) { // 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) { + if (base <= BC_NUM_MAX_POSIX_IBASE) + { width = 1; print = bc_num_printHex; } - else { + else + { assert(base <= BC_BASE_POW); width = bc_num_log10(base - 1); print = bc_num_printDigits; @@ -2997,22 +3394,27 @@ static void bc_num_printBase(BcNum *restrict n, BcBigDig base, bool newline) { #if !BC_ENABLE_LIBRARY -void bc_num_stream(BcNum *restrict n) { +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) { +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; +void +bc_num_init(BcNum* restrict n, size_t req) +{ + BcDig* num; BC_SIG_ASSERT_LOCKED; @@ -3023,20 +3425,27 @@ void bc_num_init(BcNum *restrict n, size_t req) { 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)); + if (req != BC_NUM_DEF_SIZE) num = bc_vm_malloc(BC_NUM_SIZE(req)); + else + { + num = bc_vm_getTemp() == NULL ? bc_vm_malloc(BC_NUM_SIZE(req)) : + bc_vm_takeTemp(); + } bc_num_setup(n, num, req); } -void bc_num_clear(BcNum *restrict n) { +void +bc_num_clear(BcNum* restrict n) +{ n->num = NULL; n->cap = 0; } -void bc_num_free(void *num) { - - BcNum *n = (BcNum*) num; +void +bc_num_free(void* num) +{ + BcNum* n = (BcNum*) num; BC_SIG_ASSERT_LOCKED; @@ -3046,8 +3455,9 @@ void bc_num_free(void *num) { else free(n->num); } -void bc_num_copy(BcNum *d, const BcNum *s) { - +void +bc_num_copy(BcNum* d, const BcNum* s) +{ assert(d != NULL && s != NULL); if (d == s) return; @@ -3059,35 +3469,43 @@ void bc_num_copy(BcNum *d, const BcNum *s) { // properly preserved. d->rdx = s->rdx; d->scale = s->scale; + // NOLINTNEXTLINE memcpy(d->num, s->num, BC_NUM_SIZE(d->len)); } -void bc_num_createCopy(BcNum *d, const BcNum *s) { +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) { +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) { +size_t +bc_num_scale(const BcNum* restrict n) +{ return n->scale; } -size_t bc_num_len(const BcNum *restrict n) { - +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) { - + 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. @@ -3113,15 +3531,23 @@ size_t bc_num_len(const BcNum *restrict n) { return len; } -void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base) { +void +bc_num_parse(BcNum* restrict n, const char* restrict val, BcBigDig base) +{ +#if BC_DEBUG +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY +#endif // BC_DEBUG assert(n != NULL && val != NULL && base); - assert(base >= BC_NUM_MIN_BASE && base <= vm.maxes[BC_PROG_GLOBALS_IBASE]); + 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]) { + if (!val[1]) + { BcBigDig dig = bc_num_parseChar(val[0], BC_NUM_MAX_LBASE); bc_num_bigdig2num(n, dig); } @@ -3131,22 +3557,30 @@ void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base) { assert(BC_NUM_RDX_VALID(n)); } -void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline) { - +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)) { + if (BC_NUM_NONZERO(n)) + { +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY // 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) + // Print the leading zero if necessary. We don't print when using + // scientific or engineering modes. + if (BC_Z && BC_NUM_RDX_VAL(n) == n->len && base != 0 && base != 1) + { bc_num_printHex(0, 1, false, !newline); + } } // Short-circuit 0. @@ -3154,18 +3588,27 @@ void bc_num_print(BcNum *restrict n, BcBigDig base, bool 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) { +BcBigDig +bc_num_bigdig2(const BcNum* restrict n) +{ +#if BC_DEBUG +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY +#endif // BC_DEBUG // 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 + // 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. @@ -3174,26 +3617,28 @@ BcBigDig bc_num_bigdig2(const BcNum *restrict n) { assert(n != NULL); assert(!BC_NUM_NEG(n)); - assert(bc_num_cmp(n, &vm.max) < 0); + 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) { - + switch (n->len - nrdx) + { case 3: { r = (BcBigDig) n->num[nrdx + 2]; + + // Fallthrough. + BC_FALLTHROUGH } - // Fallthrough. - BC_FALLTHROUGH case 2: { r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx + 1]; + + // Fallthrough. + BC_FALLTHROUGH } - // Fallthrough. - BC_FALLTHROUGH case 1: { @@ -3204,7 +3649,12 @@ BcBigDig bc_num_bigdig2(const BcNum *restrict n) { return r; } -BcBigDig bc_num_bigdig(const BcNum *restrict n) { +BcBigDig +bc_num_bigdig(const BcNum* restrict n) +{ +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(n != NULL); @@ -3214,14 +3664,15 @@ BcBigDig bc_num_bigdig(const BcNum *restrict n) { // 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); + 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; +void +bc_num_bigdig2num(BcNum* restrict n, BcBigDig val) +{ + BcDig* ptr; size_t i; assert(n != NULL); @@ -3238,18 +3689,24 @@ void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val) { // 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) { - +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); +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY // This function holds the secret of how I interpret a seed number for the // PRNG. Well, it's actually in the development manual @@ -3263,43 +3720,45 @@ void bc_num_rng(const BcNum *restrict n, BcRNG *rng) { bc_num_init(&frac, nrdx); bc_num_init(&intn, bc_num_int(n)); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; - assert(BC_NUM_RDX_VALID_NP(vm.max)); + assert(BC_NUM_RDX_VALID_NP(vm->max)); + // NOLINTNEXTLINE 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)); + 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_mul(&frac, &vm->max2, &temp, 0); bc_num_truncate(&temp, temp.scale); bc_num_copy(&frac, &temp); // Get the integer. + // NOLINTNEXTLINE 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)); + assert(BC_NUM_NONZERO(&vm->max)); // If there *was* a fractional part... - if (BC_NUM_NONZERO(&frac)) { - + if (BC_NUM_NONZERO(&frac)) + { // This divmod splits frac into the two state parts. - bc_num_divmod(&frac, &vm.max, &temp, &temp2, 0); + 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, + // 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); @@ -3308,22 +3767,23 @@ void bc_num_rng(const BcNum *restrict n, BcRNG *rng) { else state1 = state2 = 0; // If there *was* an integer part... - if (BC_NUM_NONZERO(&intn)) { - + if (BC_NUM_NONZERO(&intn)) + { // This divmod splits intn into the two inc parts. - bc_num_divmod(&intn, &vm.max, &temp, &temp2, 0); + bc_num_divmod(&intn, &vm->max, &temp, &temp2, 0); - // Because temp2 is the mod of vm.max, from above, it is guaranteed + // 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) { + if (bc_num_cmp(&temp, &vm->max) >= 0) + { bc_num_copy(&temp2, &temp); - bc_num_mod(&temp2, &vm.max, &temp, 0); + bc_num_mod(&temp2, &vm->max, &temp, 0); } - // The if statement above ensures that temp is less than vm.max, which + // 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); } @@ -3337,21 +3797,25 @@ void bc_num_rng(const BcNum *restrict n, BcRNG *rng) { bc_num_free(&frac); bc_num_free(&temp2); bc_num_free(&temp); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } -void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { - +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]; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY BC_SIG_LOCK; bc_num_init(&temp3, 2 * BC_RAND_NUM_SIZE); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -3360,12 +3824,12 @@ void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { 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)); + // 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)); + assert(BC_NUM_NONZERO(&vm->max2)); bc_rand_getRands(rng, &s1, &s2, &i1, &i2); @@ -3375,14 +3839,14 @@ void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { 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); + 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); + 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. @@ -3391,7 +3855,7 @@ void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { 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); + bc_num_mul(&conv, &vm->max, &temp1, 0); // Add in the first piece of increment. bc_num_bigdig2num(&conv, (BcBigDig) i1); @@ -3405,13 +3869,14 @@ void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { err: BC_SIG_MAYLOCK; bc_num_free(&temp3); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } -void bc_num_irand(BcNum *restrict a, BcNum *restrict b, BcRNG *restrict rng) { - +void +bc_num_irand(BcNum* restrict a, BcNum* restrict b, BcRNG* restrict rng) +{ BcNum atemp; - size_t i, len; + size_t i; assert(a != b); @@ -3420,25 +3885,87 @@ void bc_num_irand(BcNum *restrict a, BcNum *restrict b, BcRNG *restrict rng) { // If either of these are true, then the numbers are integers. if (BC_NUM_ZERO(a) || BC_NUM_ONE(a)) return; +#if BC_GCC + // This is here in GCC to quiet the "maybe-uninitialized" warning. + atemp.num = NULL; + atemp.len = 0; +#endif // BC_GCC + if (BC_ERR(bc_num_nonInt(a, &atemp))) bc_err(BC_ERR_MATH_NON_INTEGER); + assert(atemp.num != NULL); assert(atemp.len); - len = atemp.len - 1; + if (atemp.len > 2) + { + size_t len; - // 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); + len = atemp.len - 2; + + // Just generate a random number for each limb. + for (i = 0; i < len; i += 2) + { + BcRand dig; - // 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; + dig = bc_rand_bounded(rng, BC_BASE_RAND_POW); + + b->num[i] = (BcDig) (dig % BC_BASE_POW); + b->num[i + 1] = (BcDig) (dig / BC_BASE_POW); + } + } + else + { + // We need this set. + i = 0; + } + + // This will be true if there's one full limb after the two limb groups. + if (i == atemp.len - 2) + { + // Increment this for easy use. + i += 1; + + // If the last digit is not one, we need to set a bound for it + // explicitly. Since there's still an empty limb, we need to fill that. + if (atemp.num[i] != 1) + { + BcRand dig; + BcRand bound; + + // Set the bound to the bound of the last limb times the amount + // needed to fill the second-to-last limb as well. + bound = ((BcRand) atemp.num[i]) * BC_BASE_POW; + + dig = bc_rand_bounded(rng, bound); + + // Fill the last two. + b->num[i - 1] = (BcDig) (dig % BC_BASE_POW); + b->num[i] = (BcDig) (dig / BC_BASE_POW); + + // Ensure that the length will be correct. If the last limb is zero, + // then the length needs to be one less than the bound. + b->len = atemp.len - (b->num[i] == 0); + } + // Here the last limb *is* one, which means the last limb does *not* + // need to be filled. Also, the length needs to be one less because the + // last limb is 0. + else + { + b->num[i - 1] = (BcDig) bc_rand_bounded(rng, BC_BASE_POW); + b->len = atemp.len - 1; + } + } + // Here, there is only one limb to fill. + else + { + // See above for how this works. + if (atemp.num[i] != 1) + { + b->num[i] = (BcDig) bc_rand_bounded(rng, (BcRand) atemp.num[i]); + b->len = atemp.len - (b->num[i] == 0); + } + else b->len = atemp.len - 1; } - // We want 1 less len in the case where we skip the last limb. - else b->len = len; bc_num_clean(b); @@ -3446,8 +3973,9 @@ void bc_num_irand(BcNum *restrict a, BcNum *restrict b, BcRNG *restrict rng) { } #endif // BC_ENABLE_EXTRA_MATH -size_t bc_num_addReq(const BcNum *a, const BcNum *b, size_t scale) { - +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 @@ -3469,8 +3997,9 @@ size_t bc_num_addReq(const BcNum *a, const BcNum *b, size_t scale) { 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 +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. @@ -3485,8 +4014,9 @@ size_t bc_num_mulReq(const BcNum *a, const BcNum *b, size_t scale) { return rdx; } -size_t bc_num_divReq(const BcNum *a, const BcNum *b, size_t scale) { - +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. @@ -3501,79 +4031,110 @@ size_t bc_num_divReq(const BcNum *a, const BcNum *b, size_t scale) { return rdx; } -size_t bc_num_powReq(const BcNum *a, const BcNum *b, size_t scale) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +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) { +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; +void +bc_num_sqrt(BcNum* restrict a, BcNum* restrict b, size_t scale) +{ + BcNum num1, num2, half, f, fprime; + BcNum* x0; + BcNum* x1; + BcNum* temp; + // realscale is meant to quiet a warning on GCC about longjmp() clobbering. + // This one is real. + size_t pow, len, rdx, req, resscale, realscale; BcDig half_digs[1]; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(a != NULL && b != NULL && a != b); @@ -3581,21 +4142,23 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { // 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; + if (a->scale > scale) realscale = a->scale; + else realscale = scale; // Set parameters for the result. len = bc_vm_growSize(bc_num_intDigits(a), 1); - rdx = BC_NUM_RDX(scale); + rdx = BC_NUM_RDX(realscale); // Square root needs half of the length of the parameter. req = bc_vm_growSize(BC_MAX(rdx, BC_NUM_RDX_VAL(a)), len >> 1); + req = bc_vm_growSize(req, 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_num_init(b, req); BC_SIG_UNLOCK; @@ -3603,20 +4166,22 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { assert(a->num != NULL && b->num != NULL); // Easy case. - if (BC_NUM_ZERO(a)) { - bc_num_setToZero(b, scale); + if (BC_NUM_ZERO(a)) + { + bc_num_setToZero(b, realscale); return; } // Another easy case. - if (BC_NUM_ONE(a)) { + if (BC_NUM_ONE(a)) + { bc_num_one(b); - bc_num_extend(b, scale); + bc_num_extend(b, realscale); return; } // Set the parameters again. - rdx = BC_NUM_RDX(scale); + rdx = BC_NUM_RDX(realscale); rdx = BC_MAX(rdx, BC_NUM_RDX_VAL(a)); len = bc_vm_growSize(a->len, rdx); @@ -3626,18 +4191,17 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { 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 + // There is a division by two in the formula. We set up a number that's 1/2 // so that we can use multiplication instead of heavy division. - bc_num_one(&half); + bc_num_setToZero(&half, 1); 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_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -3652,10 +4216,11 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { 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) { - + // a is less than 1, then 0 is a good estimate. Otherwise, we want something + // in the same ballpark. That ballpark is half of pow because the result + // will have half the digits. + 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; @@ -3667,12 +4232,12 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { // I can set the rdx here directly because neg should be false. x0->scale = x0->rdx = 0; - resscale = (scale + BC_BASE_DIGS) + 2; + resscale = (realscale + 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)) { - + while (bc_num_cmp(x1, x0)) + { assert(BC_NUM_NONZERO(x0)); // This loop directly corresponds to the iteration in Newton's method. @@ -3694,7 +4259,7 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { // Copy to the result and truncate. bc_num_copy(b, x0); - if (b->scale > scale) bc_num_truncate(b, b->scale - scale); + if (b->scale > realscale) bc_num_truncate(b, b->scale - realscale); assert(!BC_NUM_NEG(b) || BC_NUM_NONZERO(b)); assert(BC_NUM_RDX_VALID(b)); @@ -3707,14 +4272,20 @@ void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { bc_num_free(&f); bc_num_free(&num2); bc_num_free(&num1); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } -void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) { - +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; + // This is volatile to quiet a warning on GCC about clobbering with + // longjmp(). + volatile bool init = false; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY // 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. @@ -3727,8 +4298,9 @@ void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) { assert(c != d && a != d && b != d && b != c); // Initialize or expand as necessary. - if (c == a) { - + if (c == a) + { + // NOLINTNEXTLINE memcpy(&num2, c, sizeof(BcNum)); ptr_a = &num2; @@ -3738,18 +4310,19 @@ void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) { init = true; - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; } - else { + 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) + if (BC_NUM_NONZERO(a) && !BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b) && + b->len == 1 && !scale) { BcBigDig rem; @@ -3774,30 +4347,34 @@ void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) { err: // Only cleanup if we initialized. - if (init) { + if (init) + { BC_SIG_MAYLOCK; bc_num_free(&num2); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } } -void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) { - +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]; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY 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 +#if BC_DEBUG || BC_GCC // This is entirely for quieting a useless scan-build error. btemp.len = 0; ctemp.len = 0; -#endif // NDEBUG +#endif // BC_DEBUG || BC_GCC // 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) || @@ -3815,7 +4392,7 @@ void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) { bc_num_init(&temp, btemp.len + 1); bc_num_createCopy(&exp, &btemp); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; @@ -3828,13 +4405,13 @@ void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) { // 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)) { - + 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)) { - + if (BC_NUM_ONE(&temp) && !BC_NUM_NEG_NP(temp)) + { assert(BC_NUM_RDX_VALID(d)); assert(BC_NUM_RDX_VALID_NP(base)); @@ -3857,75 +4434,87 @@ void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) { bc_num_free(&exp); bc_num_free(&temp); bc_num_free(&base); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); 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, ": "); +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; + 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) { - +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_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; + 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); +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) { - +void +bc_num_dump(const char* varname, const BcNum* n) +{ ulong i, scale = n->scale; - bc_file_printf(&vm.ferr, "\n%s = %s", varname, + 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) { - + 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, ". "); + { + 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 { - + { + 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) { + if (mod != 0) + { div = n->num[i] / ((BcDig) bc_num_pow10[(ulong) d]); - bc_file_printf(&vm.ferr, "%lu", (unsigned long) div); + 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, " ' %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_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); + bc_file_flush(&vm->ferr, bc_flush_err); } #endif // BC_DEBUG_CODE diff --git a/contrib/bc/src/opt.c b/contrib/bc/src/opt.c index ddc78362e7b..a1c8e813b1e 100644 --- a/contrib/bc/src/opt.c +++ b/contrib/bc/src/opt.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -53,7 +53,9 @@ * @param i The index to test. * @return True if @a i is the last index, false otherwise. */ -static inline bool bc_opt_longoptsEnd(const BcOptLong *longopts, size_t i) { +static inline bool +bc_opt_longoptsEnd(const BcOptLong* longopts, size_t i) +{ return !longopts[i].name && !longopts[i].val; } @@ -63,17 +65,21 @@ static inline bool bc_opt_longoptsEnd(const BcOptLong *longopts, size_t i) { * @param c The character to match against. * @return The name of the long option that matches @a c, or "NULL". */ -static const char* bc_opt_longopt(const BcOptLong *longopts, int c) { - +static const char* +bc_opt_longopt(const BcOptLong* longopts, int c) +{ size_t i; - for (i = 0; !bc_opt_longoptsEnd(longopts, i); ++i) { + for (i = 0; !bc_opt_longoptsEnd(longopts, i); ++i) + { if (longopts[i].val == c) return longopts[i].name; } BC_UNREACHABLE +#if !BC_CLANG return "NULL"; +#endif // !BC_CLANG } /** @@ -85,12 +91,13 @@ static const char* bc_opt_longopt(const BcOptLong *longopts, int c) { * @param use_short True if the short option should be used for error printing, * false otherwise. */ -static void bc_opt_error(BcErr err, int c, const char *str, bool use_short) { - - if (err == BC_ERR_FATAL_OPTION) { - - if (use_short) { - +static void +bc_opt_error(BcErr err, int c, const char* str, bool use_short) +{ + if (err == BC_ERR_FATAL_OPTION) + { + if (use_short) + { char short_str[2]; short_str[0] = (char) c; @@ -109,13 +116,17 @@ static void bc_opt_error(BcErr err, int c, const char *str, bool use_short) { * @param c The character to match against. * @return The type of the long option as an integer, or -1 if none. */ -static int bc_opt_type(const BcOptLong *longopts, char c) { - +static int +bc_opt_type(const BcOptLong* longopts, char c) +{ size_t i; if (c == ':') return -1; - for (i = 0; !bc_opt_longoptsEnd(longopts, i) && longopts[i].val != c; ++i); + for (i = 0; !bc_opt_longoptsEnd(longopts, i) && longopts[i].val != c; ++i) + { + continue; + } if (bc_opt_longoptsEnd(longopts, i)) return -1; @@ -128,11 +139,12 @@ static int bc_opt_type(const BcOptLong *longopts, char c) { * @param longopts The long options array. * @return The character for the short option, or -1 if none left. */ -static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { - +static int +bc_opt_parseShort(BcOpt* o, const BcOptLong* longopts) +{ int type; - char *next; - char *option = o->argv[o->optind]; + const char* next; + const char* option = o->argv[o->optind]; int ret = -1; // Make sure to clear these. @@ -147,8 +159,8 @@ static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { type = bc_opt_type(longopts, option[0]); next = o->argv[o->optind + 1]; - switch (type) { - + switch (type) + { case -1: case BC_OPT_BC_ONLY: case BC_OPT_DC_ONLY: @@ -157,23 +169,24 @@ static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { if (type == -1 || (type == BC_OPT_BC_ONLY && BC_IS_DC) || (type == BC_OPT_DC_ONLY && BC_IS_BC)) { - char str[2] = {0, 0}; + char str[2] = { 0, 0 }; str[0] = option[0]; o->optind += 1; bc_opt_error(BC_ERR_FATAL_OPTION, option[0], str, true); } + + // Fallthrough. + BC_FALLTHROUGH } - // Fallthrough. - BC_FALLTHROUGH case BC_OPT_NONE: { // If there is something else, update the suboption. if (option[1]) o->subopt += 1; - else { - + else + { // Go to the next argument. o->subopt = 0; o->optind += 1; @@ -186,12 +199,17 @@ static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { case BC_OPT_REQUIRED_BC_ONLY: { +#if DC_ENABLED if (BC_IS_DC) + { bc_opt_error(BC_ERR_FATAL_OPTION, option[0], bc_opt_longopt(longopts, option[0]), true); + } +#endif // DC_ENABLED + + // Fallthrough + BC_FALLTHROUGH } - // Fallthrough - BC_FALLTHROUGH case BC_OPT_REQUIRED: { @@ -201,16 +219,18 @@ static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { // Use the next characters, if they exist. if (option[1]) o->optarg = option + 1; - else if (next != NULL) { - + else if (next != NULL) + { // USe the next. o->optarg = next; o->optind += 1; } // No argument, barf. - else bc_opt_error(BC_ERR_FATAL_OPTION_NO_ARG, option[0], - bc_opt_longopt(longopts, option[0]), true); - + else + { + bc_opt_error(BC_ERR_FATAL_OPTION_NO_ARG, option[0], + bc_opt_longopt(longopts, option[0]), true); + } ret = (int) option[0]; @@ -228,15 +248,18 @@ static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { * @param option The command-line argument. * @return True if @a option matches @a name, false otherwise. */ -static bool bc_opt_longoptsMatch(const char *name, const char *option) { - - const char *a = option, *n = name; +static bool +bc_opt_longoptsMatch(const char* name, const char* option) +{ + const char* a = option; + const char* n = name; // Can never match a NULL name. if (name == NULL) return false; - // Loop through - for (; *a && *n && *a != '='; ++a, ++n) { + // Loop through. + for (; *a && *n && *a != '='; ++a, ++n) + { if (*a != *n) return false; } @@ -250,35 +273,40 @@ static bool bc_opt_longoptsMatch(const char *name, const char *option) { * @param option The option to find the argument of. * @return A pointer to the argument of the option, or NULL if none. */ -static char* bc_opt_longoptsArg(char *option) { - +static const char* +bc_opt_longoptsArg(const char* option) +{ // Find the end or equals sign. - for (; *option && *option != '='; ++option); + for (; *option && *option != '='; ++option) + { + continue; + } if (*option == '=') return option + 1; else return NULL; } -int bc_opt_parse(BcOpt *o, const BcOptLong *longopts) { - +int +bc_opt_parse(BcOpt* o, const BcOptLong* longopts) +{ size_t i; - char *option; + const char* option; bool empty; // This just eats empty options. - do { - + do + { option = o->argv[o->optind]; if (option == NULL) return -1; empty = !strcmp(option, ""); o->optind += empty; - - } while (empty); + } + while (empty); // If the option is just a "--". - if (BC_OPT_ISDASHDASH(option)) { - + if (BC_OPT_ISDASHDASH(option)) + { // Consume "--". o->optind += 1; return -1; @@ -297,14 +325,14 @@ int bc_opt_parse(BcOpt *o, const BcOptLong *longopts) { o->optind += 1; // Loop through the valid long options. - for (i = 0; !bc_opt_longoptsEnd(longopts, i); i++) { - - const char *name = longopts[i].name; + for (i = 0; !bc_opt_longoptsEnd(longopts, i); i++) + { + const char* name = longopts[i].name; // If we have a match... - if (bc_opt_longoptsMatch(name, option)) { - - char *arg; + if (bc_opt_longoptsMatch(name, option)) + { + const char* arg; // Get the option char and the argument. o->optopt = longopts[i].val; @@ -335,8 +363,11 @@ int bc_opt_parse(BcOpt *o, const BcOptLong *longopts) { // All's good if it exists; otherwise, barf. if (o->optarg != NULL) o->optind += 1; - else bc_opt_error(BC_ERR_FATAL_OPTION_NO_ARG, - o->optopt, name, false); + else + { + bc_opt_error(BC_ERR_FATAL_OPTION_NO_ARG, o->optopt, name, + false); + } } return o->optopt; @@ -348,10 +379,14 @@ int bc_opt_parse(BcOpt *o, const BcOptLong *longopts) { BC_UNREACHABLE +#if !BC_CLANG return -1; +#endif // !BC_CLANG } -void bc_opt_init(BcOpt *o, char *argv[]) { +void +bc_opt_init(BcOpt* o, const char* argv[]) +{ o->argv = argv; o->optind = 1; o->subopt = 0; diff --git a/contrib/bc/src/parse.c b/contrib/bc/src/parse.c index ea4c25e8ba1..0107d4cdef0 100644 --- a/contrib/bc/src/parse.c +++ b/contrib/bc/src/parse.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -44,12 +44,16 @@ #include #include -void bc_parse_updateFunc(BcParse *p, size_t fidx) { +void +bc_parse_updateFunc(BcParse* p, size_t fidx) +{ p->fidx = fidx; p->func = bc_vec_item(&p->prog->fns, fidx); } -inline void bc_parse_pushName(const BcParse *p, char *name, bool var) { +inline void +bc_parse_pushName(const BcParse* p, char* name, bool var) +{ bc_parse_pushIndex(p, bc_program_search(p->prog, name, var)); } @@ -60,79 +64,95 @@ inline void bc_parse_pushName(const BcParse *p, char *name, bool var) { * @param inst The instruction to push. * @param idx The index to push. */ -static void bc_parse_update(BcParse *p, uchar inst, size_t idx) { - bc_parse_updateFunc(p, p->fidx); +static inline void +bc_parse_pushInstIdx(BcParse* p, uchar inst, size_t idx) +{ bc_parse_push(p, inst); bc_parse_pushIndex(p, idx); } -void bc_parse_addString(BcParse *p) { - +void +bc_parse_addString(BcParse* p) +{ size_t idx; - BC_SIG_LOCK; - - idx = bc_program_addString(p->prog, p->l.str.v, p->fidx); + idx = bc_program_addString(p->prog, p->l.str.v); // Push the string info. - bc_parse_update(p, BC_INST_STR, p->fidx); - bc_parse_pushIndex(p, idx); - - BC_SIG_UNLOCK; + bc_parse_pushInstIdx(p, BC_INST_STR, idx); } -static void bc_parse_addNum(BcParse *p, const char *string) { - - BcVec *consts = &p->func->consts; +static void +bc_parse_addNum(BcParse* p, const char* string) +{ + BcProgram* prog = p->prog; size_t idx; - BcConst *c; - BcVec *slabs; + + // XXX: This function has an implicit assumption: that string is a valid C + // string with a nul terminator. This is because of the unchecked array + // accesses below. I can't check this with an assert() because that could + // lead to out-of-bounds access. + // + // XXX: In fact, just for safety's sake, assume that this function needs a + // non-empty string with a nul terminator, just in case bc_parse_zero or + // bc_parse_one change in the future, which I doubt. + + BC_SIG_ASSERT_LOCKED; // Special case 0. - if (bc_parse_zero[0] == string[0] && bc_parse_zero[1] == string[1]) { + if (bc_parse_zero[0] == string[0] && bc_parse_zero[1] == string[1]) + { bc_parse_push(p, BC_INST_ZERO); return; } // Special case 1. - if (bc_parse_one[0] == string[0] && bc_parse_one[1] == string[1]) { + if (bc_parse_one[0] == string[0] && bc_parse_one[1] == string[1]) + { bc_parse_push(p, BC_INST_ONE); return; } - // Get the index. - idx = consts->len; - - BC_SIG_LOCK; - - // Get the right slab. - slabs = p->fidx == BC_PROG_MAIN || p->fidx == BC_PROG_READ ? - &vm.main_const_slab : &vm.other_slabs; + if (bc_map_insert(&prog->const_map, string, prog->consts.len, &idx)) + { + BcConst* c; + BcId* id = bc_vec_item(&prog->const_map, idx); - // Push an empty constant. - c = bc_vec_pushEmpty(consts); + // Get the index. + idx = id->idx; - // Set the fields. - c->val = bc_slabvec_strdup(slabs, string); - c->base = BC_NUM_BIGDIG_MAX; + // Push an empty constant. + c = bc_vec_pushEmpty(&prog->consts); - // We need this to be able to tell that the number has not been allocated. - bc_num_clear(&c->num); + // Set the fields. We reuse the string in the ID (allocated by + // bc_map_insert()), because why not? + c->val = id->name; + c->base = BC_NUM_BIGDIG_MAX; - bc_parse_update(p, BC_INST_NUM, idx); + // We need this to be able to tell that the number has not been + // allocated. + bc_num_clear(&c->num); + } + else + { + BcId* id = bc_vec_item(&prog->const_map, idx); + idx = id->idx; + } - BC_SIG_UNLOCK; + bc_parse_pushInstIdx(p, BC_INST_NUM, idx); } -void bc_parse_number(BcParse *p) { - +void +bc_parse_number(BcParse* p) +{ #if BC_ENABLE_EXTRA_MATH - char *exp = strchr(p->l.str.v, 'e'); + char* exp = strchr(p->l.str.v, 'e'); size_t idx = SIZE_MAX; // Do we have a number in scientific notation? If so, add a nul byte where // the e is. - if (exp != NULL) { + if (exp != NULL) + { idx = ((size_t) (exp - p->l.str.v)); *exp = 0; } @@ -142,8 +162,8 @@ void bc_parse_number(BcParse *p) { #if BC_ENABLE_EXTRA_MATH // If we have a number in scientific notation... - if (exp != NULL) { - + if (exp != NULL) + { bool neg; // Figure out if the exponent is negative. @@ -156,19 +176,26 @@ void bc_parse_number(BcParse *p) { #endif // BC_ENABLE_EXTRA_MATH } -void bc_parse_text(BcParse *p, const char *text, bool is_stdin) { +void +bc_parse_text(BcParse* p, const char* text, BcMode mode) +{ + BC_SIG_LOCK; // Make sure the pointer isn't invalidated. p->func = bc_vec_item(&p->prog->fns, p->fidx); - bc_lex_text(&p->l, text, is_stdin); -} + bc_lex_text(&p->l, text, mode); -void bc_parse_reset(BcParse *p) { + BC_SIG_UNLOCK; +} +void +bc_parse_reset(BcParse* p) +{ BC_SIG_ASSERT_LOCKED; // Reset the function if it isn't main and switch to main. - if (p->fidx != BC_PROG_MAIN) { + if (p->fidx != BC_PROG_MAIN) + { bc_func_reset(p->func); bc_parse_updateFunc(p, BC_PROG_MAIN); } @@ -178,8 +205,8 @@ void bc_parse_reset(BcParse *p) { p->l.t = BC_LEX_EOF; #if BC_ENABLED - if (BC_IS_BC) { - + if (BC_IS_BC) + { // Get rid of the bc parser state. p->auto_part = false; bc_vec_npop(&p->flags, p->flags.len - 1); @@ -193,18 +220,20 @@ void bc_parse_reset(BcParse *p) { bc_program_reset(p->prog); // Jump if there is an error. - if (BC_ERR(vm.status)) BC_JMP; + if (BC_ERR(vm->status)) BC_JMP; } -#ifndef NDEBUG -void bc_parse_free(BcParse *p) { - +#if BC_DEBUG +void +bc_parse_free(BcParse* p) +{ BC_SIG_ASSERT_LOCKED; assert(p != NULL); #if BC_ENABLED - if (BC_IS_BC) { + if (BC_IS_BC) + { bc_vec_free(&p->flags); bc_vec_free(&p->exits); bc_vec_free(&p->conds); @@ -215,10 +244,11 @@ void bc_parse_free(BcParse *p) { bc_lex_free(&p->l); } -#endif // NDEBUG - -void bc_parse_init(BcParse *p, BcProgram *prog, size_t func) { +#endif // BC_DEBUG +void +bc_parse_init(BcParse* p, BcProgram* prog, size_t func) +{ #if BC_ENABLED uint16_t flag = 0; #endif // BC_ENABLED @@ -228,8 +258,8 @@ void bc_parse_init(BcParse *p, BcProgram *prog, size_t func) { assert(p != NULL && prog != NULL); #if BC_ENABLED - if (BC_IS_BC) { - + if (BC_IS_BC) + { // We always want at least one flag set on the flags stack. bc_vec_init(&p->flags, sizeof(uint16_t), BC_DTOR_NONE); bc_vec_push(&p->flags, &flag); diff --git a/contrib/bc/src/program.c b/contrib/bc/src/program.c index 1ff9c24f323..469835d321b 100644 --- a/contrib/bc/src/program.c +++ b/contrib/bc/src/program.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -48,24 +48,14 @@ #include #include -/** - * Quickly sets the const and strs vector pointers in the program. This is a - * convenience function. - * @param p The program. - * @param f The new function. - */ -static inline void bc_program_setVecs(BcProgram *p, BcFunc *f) { - p->consts = &f->consts; - p->strs = &f->strs; -} - /** * Does a type check for something that expects a number. * @param r The result that will be checked. * @param n The result's number. */ -static inline void bc_program_type_num(BcResult *r, BcNum *n) { - +static inline void +bc_program_type_num(BcResult* r, BcNum* n) +{ #if BC_ENABLED // This should have already been taken care of. @@ -83,7 +73,9 @@ static inline void bc_program_type_num(BcResult *r, BcNum *n) { * @param r The result to check. * @param t The type that the result should be. */ -static void bc_program_type_match(BcResult *r, BcType t) { +static void +bc_program_type_match(BcResult* r, BcType t) +{ if (BC_ERR((r->t != BC_RESULT_ARRAY) != (!t))) bc_err(BC_ERR_EXEC_TYPE); } #endif // BC_ENABLED @@ -97,12 +89,14 @@ static void bc_program_type_match(BcResult *r, BcType t) { * updated. * @return The index at @a bgn in the bytecode vector. */ -static size_t bc_program_index(const char *restrict code, size_t *restrict bgn) +static size_t +bc_program_index(const char* restrict code, size_t* restrict bgn) { uchar amt = (uchar) code[(*bgn)++], i = 0; size_t res = 0; - for (; i < amt; ++i, ++(*bgn)) { + for (; i < amt; ++i, ++(*bgn)) + { size_t temp = ((size_t) ((int) (uchar) code[*bgn]) & UCHAR_MAX); res |= (temp << (i * CHAR_BIT)); } @@ -116,9 +110,10 @@ static size_t bc_program_index(const char *restrict code, size_t *restrict bgn) * @param n The number tied to the result. * @return The string corresponding to the result and number. */ -static char* bc_program_string(BcProgram *p, const BcNum *n) { - BcFunc *f = bc_vec_item(&p->fns, n->rdx); - return *((char**) bc_vec_item(&f->strs, n->scale)); +static inline char* +bc_program_string(BcProgram* p, const BcNum* n) +{ + return *((char**) bc_vec_item(&p->strs, n->scale)); } #if BC_ENABLED @@ -129,12 +124,15 @@ static char* bc_program_string(BcProgram *p, const BcNum *n) { * their respective stacks. * @param p The program. */ -static void bc_program_prepGlobals(BcProgram *p) { - +static void +bc_program_prepGlobals(BcProgram* p) +{ size_t i; for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) + { bc_vec_push(p->globals_v + i, p->globals + i); + } #if BC_ENABLE_EXTRA_MATH bc_rand_push(&p->rng); @@ -148,12 +146,16 @@ static void bc_program_prepGlobals(BcProgram *p) { * @param reset True if all but one item on each stack should be popped, false * otherwise. */ -static void bc_program_popGlobals(BcProgram *p, bool reset) { - +static void +bc_program_popGlobals(BcProgram* p, bool reset) +{ size_t i; - for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { - BcVec *v = p->globals_v + i; + BC_SIG_ASSERT_LOCKED; + + for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) + { + BcVec* v = p->globals_v + i; bc_vec_npop(v, reset ? v->len - 1 : 1); p->globals[i] = BC_PROG_GLOBAL(v); } @@ -169,9 +171,10 @@ static void bc_program_popGlobals(BcProgram *p, bool reset) { * @param vec The reference vector. * @return A pointer to the desired array. */ -static BcVec* bc_program_dereference(const BcProgram *p, BcVec *vec) { - - BcVec *v; +static BcVec* +bc_program_dereference(const BcProgram* p, BcVec* vec) +{ + BcVec* v; size_t vidx, nidx, i = 0; // We want to be sure we have a reference vector. @@ -189,6 +192,7 @@ static BcVec* bc_program_dereference(const BcProgram *p, BcVec *vec) { return v; } + #endif // BC_ENABLED /** @@ -198,7 +202,8 @@ static BcVec* bc_program_dereference(const BcProgram *p, BcVec *vec) { * @param dig The BcBigDig to push onto the results stack. * @param type The type that the pushed result should be. */ -static void bc_program_pushBigdig(BcProgram *p, BcBigDig dig, BcResultType type) +static void +bc_program_pushBigdig(BcProgram* p, BcBigDig dig, BcResultType type) { BcResult res; @@ -212,49 +217,60 @@ static void bc_program_pushBigdig(BcProgram *p, BcBigDig dig, BcResultType type) BC_SIG_UNLOCK; } -size_t bc_program_addString(BcProgram *p, const char *str, size_t fidx) { - - BcFunc *f; - char **str_ptr; - BcVec *slabs; +size_t +bc_program_addString(BcProgram* p, const char* str) +{ + size_t idx; BC_SIG_ASSERT_LOCKED; - // Push an empty string on the proper vector. - f = bc_vec_item(&p->fns, fidx); - str_ptr = bc_vec_pushEmpty(&f->strs); + if (bc_map_insert(&p->str_map, str, p->strs.len, &idx)) + { + char** str_ptr; + BcId* id = bc_vec_item(&p->str_map, idx); - // Figure out which slab vector to use. - slabs = fidx == BC_PROG_MAIN || fidx == BC_PROG_READ ? - &vm.main_slabs : &vm.other_slabs; + // Get the index. + idx = id->idx; - *str_ptr = bc_slabvec_strdup(slabs, str); + // Push an empty string on the proper vector. + str_ptr = bc_vec_pushEmpty(&p->strs); - return f->strs.len - 1; -} + // We reuse the string in the ID (allocated by bc_map_insert()), because + // why not? + *str_ptr = id->name; + } + else + { + BcId* id = bc_vec_item(&p->str_map, idx); + idx = id->idx; + } -size_t bc_program_search(BcProgram *p, const char *id, bool var) { + return idx; +} - BcVec *v, *map; +size_t +bc_program_search(BcProgram* p, const char* name, bool var) +{ + BcVec* v; + BcVec* map; size_t i; + BC_SIG_ASSERT_LOCKED; + // Grab the right vector and map. v = var ? &p->vars : &p->arrs; map = var ? &p->var_map : &p->arr_map; - BC_SIG_LOCK; - // We do an insert because the variable might not exist yet. This is because // the parser calls this function. If the insert succeeds, we create a stack // for the variable/array. But regardless, bc_map_insert() gives us the // index of the item in i. - if (bc_map_insert(map, id, v->len, &i)) { - BcVec *temp = bc_vec_pushEmpty(v); + if (bc_map_insert(map, name, v->len, &i)) + { + BcVec* temp = bc_vec_pushEmpty(v); bc_array_init(temp, var); } - BC_SIG_UNLOCK; - return ((BcId*) bc_vec_item(map, i))->idx; } @@ -266,9 +282,10 @@ size_t bc_program_search(BcProgram *p, const char *id, bool var) { * @param type The type of vector to return. * @return A pointer to the variable or array stack. */ -static inline BcVec* bc_program_vec(const BcProgram *p, size_t idx, BcType type) +static inline BcVec* +bc_program_vec(const BcProgram* p, size_t idx, BcType type) { - const BcVec *v = (type == BC_TYPE_VAR) ? &p->vars : &p->arrs; + const BcVec* v = (type == BC_TYPE_VAR) ? &p->vars : &p->arrs; return bc_vec_item(v, idx); } @@ -283,9 +300,10 @@ static inline BcVec* bc_program_vec(const BcProgram *p, size_t idx, BcType type) * @param r The result whose number will be returned. * @return The BcNum corresponding to the result. */ -static BcNum* bc_program_num(BcProgram *p, BcResult *r) { - - BcNum *n; +static BcNum* +bc_program_num(BcProgram* p, BcResult* r) +{ + BcNum* n; #ifdef _WIN32 // Windows made it an error to not initialize this, so shut it up. @@ -295,8 +313,8 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { n = NULL; #endif // _WIN32 - switch (r->t) { - + switch (r->t) + { case BC_RESULT_STR: case BC_RESULT_TEMP: case BC_RESULT_IBASE: @@ -314,7 +332,7 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { case BC_RESULT_ARRAY: case BC_RESULT_ARRAY_ELEM: { - BcVec *v; + BcVec* v; BcType type = (r->t == BC_RESULT_VAR) ? BC_TYPE_VAR : BC_TYPE_ARRAY; // Get the correct variable or array vector. @@ -324,11 +342,11 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { // it's returning an array element. This is because we have to dig // deeper to get *to* the element. That's what the code inside this // if statement does. - if (r->t == BC_RESULT_ARRAY_ELEM) { - + if (r->t == BC_RESULT_ARRAY_ELEM) + { size_t idx = r->d.loc.idx; - v = bc_vec_top(v); + v = bc_vec_item(v, r->d.loc.stack_idx); #if BC_ENABLED // If this is true, we have a reference vector, so dereference @@ -348,7 +366,8 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { // an element *way* out there, we have to preinitialize all // elements between the current last element and the actual // accessed element. - if (v->len <= idx) { + if (v->len <= idx) + { BC_SIG_LOCK; bc_array_expand(v, bc_vm_growSize(idx, 1)); BC_SIG_UNLOCK; @@ -357,21 +376,34 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { n = bc_vec_item(v, idx); } // This is either a number (for a var) or an array (for an array). - // Because bc_vec_top() returns a void*, we don't need to cast. - else n = bc_vec_top(v); + // Because bc_vec_top() and bc_vec_item() return a void*, we don't + // need to cast. + else + { +#if BC_ENABLED + if (BC_IS_BC) + { + n = bc_vec_item(v, r->d.loc.stack_idx); + } + else +#endif // BC_ENABLED + { + n = bc_vec_top(v); + } + } break; } case BC_RESULT_ZERO: { - n = &vm.zero; + n = &vm->zero; break; } case BC_RESULT_ONE: { - n = &vm.one; + n = &vm->one; break; } @@ -379,18 +411,26 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { // We should never get here; this is taken care of earlier because a // result is expected. case BC_RESULT_VOID: -#ifndef NDEBUG +#if BC_DEBUG { abort(); + // Fallthrough } -#endif // NDEBUG - // Fallthrough +#endif // BC_DEBUG case BC_RESULT_LAST: { n = &p->last; break; } #endif // BC_ENABLED + +#if BC_GCC + // This is here in GCC to quiet the "maybe-uninitialized" warning. + default: + { + abort(); + } +#endif // BC_GCC } return n; @@ -405,8 +445,8 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { * we care about. * @param idx The index of the result from the top of the results stack. */ -static void bc_program_operand(BcProgram *p, BcResult **r, - BcNum **n, size_t idx) +static void +bc_program_operand(BcProgram* p, BcResult** r, BcNum** n, size_t idx) { *r = bc_vec_item_rev(&p->results, idx); @@ -431,8 +471,9 @@ static void bc_program_operand(BcProgram *p, BcResult **r, * @param idx The starting index where the operands are in the results stack, * starting from the top. */ -static void bc_program_binPrep(BcProgram *p, BcResult **l, BcNum **ln, - BcResult **r, BcNum **rn, size_t idx) +static void +bc_program_binPrep(BcProgram* p, BcResult** l, BcNum** ln, BcResult** r, + BcNum** rn, size_t idx) { BcResultType lt; @@ -440,9 +481,12 @@ static void bc_program_binPrep(BcProgram *p, BcResult **l, BcNum **ln, #ifndef BC_PROG_NO_STACK_CHECK // Check the stack for dc. - if (BC_IS_DC) { + if (BC_IS_DC) + { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 2))) + { bc_err(BC_ERR_EXEC_STACK); + } } #endif // BC_PROG_NO_STACK_CHECK @@ -463,7 +507,9 @@ static void bc_program_binPrep(BcProgram *p, BcResult **l, BcNum **ln, // reallocated out from under the BcNums or arrays we had. In other words, // this is to fix pointer invalidation. if (lt == (*r)->t && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) + { *ln = bc_program_num(p, *l); + } if (BC_ERR(lt == BC_RESULT_STR)) bc_err(BC_ERR_EXEC_TYPE); } @@ -484,8 +530,9 @@ static void bc_program_binPrep(BcProgram *p, BcResult **l, BcNum **ln, * @param idx The starting index where the operands are in the results stack, * starting from the top. */ -static void bc_program_binOpPrep(BcProgram *p, BcResult **l, BcNum **ln, - BcResult **r, BcNum **rn, size_t idx) +static void +bc_program_binOpPrep(BcProgram* p, BcResult** l, BcNum** ln, BcResult** r, + BcNum** rn, size_t idx) { bc_program_binPrep(p, l, ln, r, rn, idx); bc_program_type_num(*l, *ln); @@ -504,10 +551,12 @@ static void bc_program_binOpPrep(BcProgram *p, BcResult **l, BcNum **ln, * @param rn An out parameter; this is set to the pointer to the number for the * right operand. */ -static void bc_program_assignPrep(BcProgram *p, BcResult **l, BcNum **ln, - BcResult **r, BcNum **rn) +static void +bc_program_assignPrep(BcProgram* p, BcResult** l, BcNum** ln, BcResult** r, + BcNum** rn) { BcResultType lt, min; + bool good; // This is the min non-allowable result type. dc allows strings. min = BC_RESULT_TEMP - ((unsigned int) (BC_IS_BC)); @@ -522,7 +571,7 @@ static void bc_program_assignPrep(BcProgram *p, BcResult **l, BcNum **ln, // Strings can be assigned to variables. We are already good if we are // assigning a string. - bool good = ((*r)->t == BC_RESULT_STR && lt <= BC_RESULT_ARRAY_ELEM); + good = ((*r)->t == BC_RESULT_STR && lt <= BC_RESULT_ARRAY_ELEM); assert(BC_PROG_STR(*rn) || (*r)->t != BC_RESULT_STR); @@ -540,15 +589,19 @@ static void bc_program_assignPrep(BcProgram *p, BcResult **l, BcNum **ln, * we care about. * @param idx The index of the result from the top of the results stack. */ -static void bc_program_prep(BcProgram *p, BcResult **r, BcNum **n, size_t idx) { - +static void +bc_program_prep(BcProgram* p, BcResult** r, BcNum** n, size_t idx) +{ assert(p != NULL && r != NULL && n != NULL); #ifndef BC_PROG_NO_STACK_CHECK // Check the stack for dc. - if (BC_IS_DC) { + if (BC_IS_DC) + { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) + { bc_err(BC_ERR_EXEC_STACK); + } } #endif // BC_PROG_NO_STACK_CHECK @@ -565,9 +618,10 @@ static void bc_program_prep(BcProgram *p, BcResult **r, BcNum **n, size_t idx) { * @param p The program. * @return A clean result. */ -static BcResult* bc_program_prepResult(BcProgram *p) { - - BcResult *res = bc_vec_pushEmpty(&p->results); +static BcResult* +bc_program_prepResult(BcProgram* p) +{ + BcResult* res = bc_vec_pushEmpty(&p->results); bc_result_clear(res); @@ -583,23 +637,30 @@ static BcResult* bc_program_prepResult(BcProgram *p) { * @param bgn An in/out parameter; marks the start of the index in the * bytecode vector and will be updated to point to after the index. */ -static void bc_program_const(BcProgram *p, const char *code, size_t *bgn) { - +static void +bc_program_const(BcProgram* p, const char* code, size_t* bgn) +{ // I lied. I actually push the result first. I can do this because the // result will be popped on error. I also get the constant itself. - BcResult *r = bc_program_prepResult(p); - BcConst *c = bc_vec_item(p->consts, bc_program_index(code, bgn)); + BcResult* r = bc_program_prepResult(p); + BcConst* c = bc_vec_item(&p->consts, bc_program_index(code, bgn)); BcBigDig base = BC_PROG_IBASE(p); // Only reparse if the base changed. - if (c->base != base) { - + if (c->base != base) + { // Allocate if we haven't yet. - if (c->num.num == NULL) { + if (c->num.num == NULL) + { + // The plus 1 is in case of overflow with lack of clamping. + size_t len = strlen(c->val) + (BC_DIGIT_CLAMP == 0); + BC_SIG_LOCK; - bc_num_init(&c->num, BC_NUM_RDX(strlen(c->val))); + bc_num_init(&c->num, BC_NUM_RDX(len)); BC_SIG_UNLOCK; } + // We need to zero an already existing number. + else bc_num_zero(&c->num); // bc_num_parse() should only do operations that cannot fail. bc_num_parse(&c->num, c->val, base); @@ -619,10 +680,14 @@ static void bc_program_const(BcProgram *p, const char *code, size_t *bgn) { * @param p The program. * @param inst The instruction corresponding to the binary operator to execute. */ -static void bc_program_op(BcProgram *p, uchar inst) { - - BcResult *opd1, *opd2, *res; - BcNum *n1, *n2; +static void +bc_program_op(BcProgram* p, uchar inst) +{ + BcResult* opd1; + BcResult* opd2; + BcResult* res; + BcNum* n1; + BcNum* n2; size_t idx = inst - BC_INST_POWER; res = bc_program_prepResult(p); @@ -651,72 +716,83 @@ static void bc_program_op(BcProgram *p, uchar inst) { * Executes a read() or ? command. * @param p The program. */ -static void bc_program_read(BcProgram *p) { - +static void +bc_program_read(BcProgram* p) +{ BcStatus s; BcInstPtr ip; size_t i; const char* file; - bool is_stdin; - BcFunc *f = bc_vec_item(&p->fns, BC_PROG_READ); + BcMode mode; + BcFunc* f = bc_vec_item(&p->fns, BC_PROG_READ); // If we are already executing a read, that is an error. So look for a read // and barf. - for (i = 0; i < p->stack.len; ++i) { - BcInstPtr *ip_ptr = bc_vec_item(&p->stack, i); + for (i = 0; i < p->stack.len; ++i) + { + BcInstPtr* ip_ptr = bc_vec_item(&p->stack, i); if (ip_ptr->func == BC_PROG_READ) bc_err(BC_ERR_EXEC_REC_READ); } BC_SIG_LOCK; // Save the filename because we are going to overwrite it. - file = vm.file; - is_stdin = vm.is_stdin; + file = vm->file; + mode = vm->mode; // It is a parse error if there needs to be more than one line, so we unset // this to tell the lexer to not request more. We set it back later. - vm.is_stdin = false; - - if (!BC_PARSE_IS_INITED(&vm.read_prs, p)) { + vm->mode = BC_MODE_FILE; + if (!BC_PARSE_IS_INITED(&vm->read_prs, p)) + { // We need to parse, but we don't want to use the existing parser // because it has state it needs to keep. (It could have a partial parse // state.) So we create a new parser. This parser is in the BcVm struct // so that it is not local, which means that a longjmp() could change // it. - bc_parse_init(&vm.read_prs, p, BC_PROG_READ); + bc_parse_init(&vm->read_prs, p, BC_PROG_READ); // We need a separate input buffer; that's why it is also in the BcVm // struct. - bc_vec_init(&vm.read_buf, sizeof(char), BC_DTOR_NONE); + bc_vec_init(&vm->read_buf, sizeof(char), BC_DTOR_NONE); + } + else + { + // This needs to be updated because the parser could have been used + // somewhere else. + bc_parse_updateFunc(&vm->read_prs, BC_PROG_READ); + + // The read buffer also needs to be emptied or else it will still + // contain previous read expressions. + bc_vec_empty(&vm->read_buf); } - // This needs to be updated because the parser could have been used - // somewhere else - else bc_parse_updateFunc(&vm.read_prs, BC_PROG_READ); - BC_SETJMP_LOCKED(exec_err); + BC_SETJMP_LOCKED(vm, exec_err); BC_SIG_UNLOCK; // Set up the lexer and the read function. - bc_lex_file(&vm.read_prs.l, bc_program_stdin_name); + bc_lex_file(&vm->read_prs.l, bc_program_stdin_name); bc_vec_popAll(&f->code); // Read a line. - if (!BC_R) s = bc_read_line(&vm.read_buf, ""); - else s = bc_read_line(&vm.read_buf, BC_IS_BC ? "read> " : "?> "); + if (!BC_R) s = bc_read_line(&vm->read_buf, ""); + else s = bc_read_line(&vm->read_buf, BC_VM_READ_PROMPT); // We should *not* have run into EOF. if (s == BC_STATUS_EOF) bc_err(BC_ERR_EXEC_READ_EXPR); - // Parse *one* expression. - bc_parse_text(&vm.read_prs, vm.read_buf.v, false); - vm.expr(&vm.read_prs, BC_PARSE_NOREAD | BC_PARSE_NEEDVAL); + // Parse *one* expression, so mode should not be stdin. + bc_parse_text(&vm->read_prs, vm->read_buf.v, BC_MODE_FILE); + BC_SIG_LOCK; + vm->expr(&vm->read_prs, BC_PARSE_NOREAD | BC_PARSE_NEEDVAL); + BC_SIG_UNLOCK; // We *must* have a valid expression. A semicolon cannot end an expression, // although EOF can. - if (BC_ERR(vm.read_prs.l.t != BC_LEX_NLINE && - vm.read_prs.l.t != BC_LEX_EOF)) + if (BC_ERR(vm->read_prs.l.t != BC_LEX_NLINE && + vm->read_prs.l.t != BC_LEX_EOF)) { bc_err(BC_ERR_EXEC_READ_EXPR); } @@ -735,12 +811,16 @@ static void bc_program_read(BcProgram *p) { f = bc_vec_item(&p->fns, BC_PROG_READ); // We want a return instruction to simplify things. - bc_vec_pushByte(&f->code, vm.read_ret); + bc_vec_pushByte(&f->code, vm->read_ret); + + // This lock is here to make sure dc's tail calls are the same length. + BC_SIG_LOCK; bc_vec_push(&p->stack, &ip); #if DC_ENABLED // We need a new tail call entry for dc. - if (BC_IS_DC) { + if (BC_IS_DC) + { size_t temp = 0; bc_vec_push(&p->tail_calls, &temp); } @@ -748,9 +828,9 @@ static void bc_program_read(BcProgram *p) { exec_err: BC_SIG_MAYLOCK; - vm.is_stdin = is_stdin; - vm.file = file; - BC_LONGJMP_CONT; + vm->mode = (uchar) mode; + vm->file = file; + BC_LONGJMP_CONT(vm); } #if BC_ENABLE_EXTRA_MATH @@ -759,20 +839,21 @@ static void bc_program_read(BcProgram *p) { * Execute a rand(). * @param p The program. */ -static void bc_program_rand(BcProgram *p) { - +static void +bc_program_rand(BcProgram* p) +{ BcRand rand = bc_rand_int(&p->rng); bc_program_pushBigdig(p, (BcBigDig) rand, BC_RESULT_TEMP); -#ifndef NDEBUG +#if BC_DEBUG // This is just to ensure that the generated number is correct. I also use // braces because I declare every local at the top of the scope. { - BcResult *r = bc_vec_top(&p->results); + BcResult* r = bc_vec_top(&p->results); assert(BC_NUM_RDX_VALID_NP(r->d.n)); } -#endif // NDEBUG +#endif // BC_DEBUG } #endif // BC_ENABLE_EXTRA_MATH @@ -780,12 +861,16 @@ static void bc_program_rand(BcProgram *p) { * Prints a series of characters, without escapes. * @param str The string (series of characters). */ -static void bc_program_printChars(const char *str) { +static void +bc_program_printChars(const char* str) +{ + const char* nl; + size_t len = vm->nchars + strlen(str); + sig_atomic_t lock; - const char *nl; - size_t len = vm.nchars + strlen(str); + BC_SIG_TRYLOCK(lock); - bc_file_puts(&vm.fout, bc_flush_save, str); + bc_file_puts(&vm->fout, bc_flush_save, str); // We need to update the number of characters, so we find the last newline // and set the characters accordingly. @@ -793,49 +878,59 @@ static void bc_program_printChars(const char *str) { if (nl != NULL) len = strlen(nl + 1); - vm.nchars = len > UINT16_MAX ? UINT16_MAX : (uint16_t) len; + vm->nchars = len > UINT16_MAX ? UINT16_MAX : (uint16_t) len; + + BC_SIG_TRYUNLOCK(lock); } /** * Prints a string with escapes. * @param str The string. */ -static void bc_program_printString(const char *restrict str) { - +static void +bc_program_printString(const char* restrict str) +{ size_t i, len = strlen(str); #if DC_ENABLED // This is to ensure a nul byte is printed for dc's stream operation. - if (!len && BC_IS_DC) { + if (!len && BC_IS_DC) + { bc_vm_putchar('\0', bc_flush_save); return; } #endif // DC_ENABLED // Loop over the characters, processing escapes and printing the rest. - for (i = 0; i < len; ++i) { - + for (i = 0; i < len; ++i) + { int c = str[i]; // If we have an escape... - if (c == '\\' && i != len - 1) { - - const char *ptr; + if (c == '\\' && i != len - 1) + { + const char* ptr; // Get the escape character and its companion. c = str[++i]; ptr = strchr(bc_program_esc_chars, c); // If we have a companion character... - if (ptr != NULL) { - + if (ptr != NULL) + { // We need to specially handle a newline. - if (c == 'n') vm.nchars = UINT16_MAX; + if (c == 'n') + { + BC_SIG_LOCK; + vm->nchars = UINT16_MAX; + BC_SIG_UNLOCK; + } // Grab the actual character. c = bc_program_esc_seqs[(size_t) (ptr - bc_program_esc_chars)]; } - else { + else + { // Just print the backslash if there is no companion character. // The following character will be printed later after the outer // if statement. @@ -853,19 +948,23 @@ static void bc_program_printString(const char *restrict str) { * @param inst The instruction for the type of print we are doing. * @param idx The index of the result that we are printing. */ -static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { - - BcResult *r; - char *str; - BcNum *n; +static void +bc_program_print(BcProgram* p, uchar inst, size_t idx) +{ + BcResult* r; + char* str; + BcNum* n; bool pop = (inst != BC_INST_PRINT); assert(p != NULL); #ifndef BC_PROG_NO_STACK_CHECK - if (BC_IS_DC) { + if (BC_IS_DC) + { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) + { bc_err(BC_ERR_EXEC_STACK); + } } #endif // BC_PROG_NO_STACK_CHECK @@ -878,7 +977,8 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { // true because that means that we are executing a print statement, but // attempting to do a print on a lone void value is allowed because that's // exactly how we want void values used. - if (r->t == BC_RESULT_VOID) { + if (r->t == BC_RESULT_VOID) + { if (BC_ERR(pop)) bc_err(BC_ERR_EXEC_VOID_VAL); bc_vec_pop(&p->results); return; @@ -888,8 +988,8 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { n = bc_program_num(p, r); // If we have a number... - if (BC_PROG_NUM(r, n)) { - + if (BC_PROG_NUM(r, n)) + { #if BC_ENABLED assert(inst != BC_INST_PRINT_STR); #endif // BC_ENABLED @@ -902,10 +1002,10 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { if (BC_IS_BC) bc_num_copy(&p->last, n); #endif // BC_ENABLED } - else { - + else + { // We want to flush any stuff in the stdout buffer first. - bc_file_flush(&vm.fout, bc_flush_save); + bc_file_flush(&vm->fout, bc_flush_save); str = bc_program_string(p, n); #if BC_ENABLED @@ -916,26 +1016,31 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { bc_program_printString(str); // Need to print a newline only in this case. - if (inst == BC_INST_PRINT) - bc_vm_putchar('\n', bc_flush_err); + if (inst == BC_INST_PRINT) bc_vm_putchar('\n', bc_flush_err); } } - // bc always pops. - if (BC_IS_BC || pop) bc_vec_pop(&p->results); + // bc always pops. This macro makes sure that happens. + if (BC_PROGRAM_POP(pop)) bc_vec_pop(&p->results); } -void bc_program_negate(BcResult *r, BcNum *n) { +void +bc_program_negate(BcResult* r, BcNum* n) +{ bc_num_copy(&r->d.n, n); if (BC_NUM_NONZERO(&r->d.n)) BC_NUM_NEG_TGL_NP(r->d.n); } -void bc_program_not(BcResult *r, BcNum *n) { +void +bc_program_not(BcResult* r, BcNum* n) +{ if (!bc_num_cmpZero(n)) bc_num_one(&r->d.n); } #if BC_ENABLE_EXTRA_MATH -void bc_program_trunc(BcResult *r, BcNum *n) { +void +bc_program_trunc(BcResult* r, BcNum* n) +{ bc_num_copy(&r->d.n, n); bc_num_truncate(&r->d.n, n->scale); } @@ -946,10 +1051,12 @@ void bc_program_trunc(BcResult *r, BcNum *n) { * @param p The program. * @param inst The unary operation. */ -static void bc_program_unary(BcProgram *p, uchar inst) { - - BcResult *res, *ptr; - BcNum *num; +static void +bc_program_unary(BcProgram* p, uchar inst) +{ + BcResult* res; + BcResult* ptr; + BcNum* num; res = bc_program_prepResult(p); @@ -971,10 +1078,14 @@ static void bc_program_unary(BcProgram *p, uchar inst) { * @param p The program. * @param inst The operator. */ -static void bc_program_logical(BcProgram *p, uchar inst) { - - BcResult *opd1, *opd2, *res; - BcNum *n1, *n2; +static void +bc_program_logical(BcProgram* p, uchar inst) +{ + BcResult* opd1; + BcResult* opd2; + BcResult* res; + BcNum* n1; + BcNum* n2; bool cond = 0; ssize_t cmp; @@ -987,16 +1098,20 @@ static void bc_program_logical(BcProgram *p, uchar inst) { // Boolean and and or are not short circuiting. This is why; they can be // implemented much easier this way. if (inst == BC_INST_BOOL_AND) + { cond = (bc_num_cmpZero(n1) && bc_num_cmpZero(n2)); + } else if (inst == BC_INST_BOOL_OR) + { cond = (bc_num_cmpZero(n1) || bc_num_cmpZero(n2)); - else { - + } + else + { // We have a relational operator, so do a comparison. cmp = bc_num_cmp(n1, n2); - switch (inst) { - + switch (inst) + { case BC_INST_REL_EQ: { cond = (cmp == 0); @@ -1032,13 +1147,13 @@ static void bc_program_logical(BcProgram *p, uchar inst) { cond = (cmp > 0); break; } -#ifndef NDEBUG +#if BC_DEBUG default: { // There is a bug if we get here. abort(); } -#endif // NDEBUG +#endif // BC_DEBUG } } @@ -1062,9 +1177,10 @@ static void bc_program_logical(BcProgram *p, uchar inst) { * string from the results stack and push it onto the variable * stack. */ -static void bc_program_assignStr(BcProgram *p, BcNum *num, BcVec *v, bool push) +static void +bc_program_assignStr(BcProgram* p, BcNum* num, BcVec* v, bool push) { - BcNum *n; + BcNum* n; assert(BC_PROG_STACK(&p->results, 1 + !push)); assert(num != NULL && num->num == NULL && num->cap == 0); @@ -1078,32 +1194,29 @@ static void bc_program_assignStr(BcProgram *p, BcNum *num, BcVec *v, bool push) n = bc_vec_pushEmpty(v); // We can just copy because the num should not have allocated anything. + // NOLINTNEXTLINE memcpy(n, num, sizeof(BcNum)); } /** * Copies a value to a variable. This is used for storing in dc as well as to * set function parameters to arguments in bc. - * @param p The program. - * @param idx The index of the variable or array to copy to. - * @param t The type to copy to. This could be a variable or an array. - * @param last Whether to grab the last item on the variable stack or not (for - * bc function parameters). This is important because if a new - * value has been pushed to the variable already, we need to grab - * the value pushed before. This happens when you have a parameter - * named something like "x", and a variable "x" is passed to - * another parameter. + * @param p The program. + * @param idx The index of the variable or array to copy to. + * @param t The type to copy to. This could be a variable or an array. */ -static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) +static void +bc_program_copyToVar(BcProgram* p, size_t idx, BcType t) { BcResult *ptr = NULL, r; - BcVec *vec; - BcNum *n = NULL; + BcVec* vec; + BcNum* n = NULL; bool var = (t == BC_TYPE_VAR); #if DC_ENABLED // Check the stack for dc. - if (BC_IS_DC) { + if (BC_IS_DC) + { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); } #endif @@ -1118,11 +1231,6 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) { // Type match the result. bc_program_type_match(ptr, t); - - // Get the variable or array, taking care to get the real item. We take - // care of last with arrays later. - if (!last && var) - n = bc_vec_item_rev(bc_program_vec(p, ptr->d.loc.loc, t), 1); } #endif // BC_ENABLED @@ -1130,8 +1238,8 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) // We can shortcut in dc if it's assigning a string by using // bc_program_assignStr(). - if (ptr->t == BC_RESULT_STR) { - + if (ptr->t == BC_RESULT_STR) + { assert(BC_PROG_STR(n)); if (BC_ERR(!var)) bc_err(BC_ERR_EXEC_TYPE); @@ -1144,33 +1252,28 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) BC_SIG_LOCK; // Just create and copy for a normal variable. - if (var) { - if (BC_PROG_STR(n)) memcpy(&r.d.n, n, sizeof(BcNum)); + if (var) + { + if (BC_PROG_STR(n)) + { + // NOLINTNEXTLINE + memcpy(&r.d.n, n, sizeof(BcNum)); + } else bc_num_createCopy(&r.d.n, n); } - else { - + else + { // If we get here, we are handling an array. This is one place we need // to cast the number from bc_program_num() to a vector. - BcVec *v = (BcVec*) n, *rv = &r.d.v; + BcVec* v = (BcVec*) n; + BcVec* rv = &r.d.v; #if BC_ENABLED - if (BC_IS_BC) { - - BcVec *parent; + if (BC_IS_BC) + { bool ref, ref_size; - // We need to figure out if the parameter is a reference or not and - // construct the reference vector, if necessary. So this gets the - // parent stack for the array. - parent = bc_program_vec(p, ptr->d.loc.loc, t); - assert(parent != NULL); - - // This takes care of last for arrays. Mostly. - if (!last) v = bc_vec_item_rev(parent, !last); - assert(v != NULL); - // True if we are using a reference. ref = (v->size == sizeof(BcNum) && t == BC_TYPE_REF); @@ -1182,16 +1285,14 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) ref_size = (v->size == sizeof(uchar)); // If we *should* have a reference. - if (ref || (ref_size && t == BC_TYPE_REF)) { - + if (ref || (ref_size && t == BC_TYPE_REF)) + { // Create a new reference vector. bc_vec_init(rv, sizeof(uchar), BC_DTOR_NONE); // If this is true, then we need to construct a reference. - if (ref) { - - assert(parent->len >= (size_t) (!last + 1)); - + if (ref) + { // Make sure the pointer was not invalidated. vec = bc_program_vec(p, idx, t); @@ -1199,7 +1300,7 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) // care of last; it ensures the reference goes to the right // place. bc_vec_pushIndex(rv, ptr->d.loc.loc); - bc_vec_pushIndex(rv, parent->len - !last - 1); + bc_vec_pushIndex(rv, ptr->d.loc.stack_idx); } // If we get here, we are copying a ref to a ref. Just push a // copy of all of the bytes. @@ -1218,7 +1319,9 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) // If we get here, we have a reference, but we need an array, so // dereference the array. else if (ref_size && t != BC_TYPE_REF) + { v = bc_program_dereference(p, v); + } } #endif // BC_ENABLED @@ -1235,16 +1338,97 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) BC_SIG_UNLOCK; } +void +bc_program_assignBuiltin(BcProgram* p, bool scale, bool obase, BcBigDig val) +{ + BcBigDig* ptr_t; + BcBigDig max, min; +#if BC_ENABLED + BcVec* v; + BcBigDig* ptr; +#endif // BC_ENABLED + + assert(!scale || !obase); + + // Scale needs handling separate from ibase and obase. + if (scale) + { + // Set the min and max. + min = 0; + max = vm->maxes[BC_PROG_GLOBALS_SCALE]; + +#if BC_ENABLED + // Get a pointer to the stack. + v = p->globals_v + BC_PROG_GLOBALS_SCALE; +#endif // BC_ENABLED + + // Get a pointer to the current value. + ptr_t = p->globals + BC_PROG_GLOBALS_SCALE; + } + else + { + // Set the min and max. + min = BC_NUM_MIN_BASE; + if (BC_ENABLE_EXTRA_MATH && obase && (BC_IS_DC || !BC_IS_POSIX)) + { + min = 0; + } + max = vm->maxes[obase + BC_PROG_GLOBALS_IBASE]; + +#if BC_ENABLED + // Get a pointer to the stack. + v = p->globals_v + BC_PROG_GLOBALS_IBASE + obase; +#endif // BC_ENABLED + + // Get a pointer to the current value. + ptr_t = p->globals + BC_PROG_GLOBALS_IBASE + obase; + } + + // Check for error. + if (BC_ERR(val > max || val < min)) + { + BcErr e; + + // This grabs the right error. + if (scale) e = BC_ERR_EXEC_SCALE; + else if (obase) e = BC_ERR_EXEC_OBASE; + else e = BC_ERR_EXEC_IBASE; + + bc_verr(e, min, max); + } + +#if BC_ENABLED + // Set the top of the stack. + ptr = bc_vec_top(v); + *ptr = val; +#endif // BC_ENABLED + + // Set the actual global variable. + *ptr_t = val; +} + +#if BC_ENABLE_EXTRA_MATH +void +bc_program_assignSeed(BcProgram* p, BcNum* val) +{ + bc_num_rng(val, &p->rng); +} +#endif // BC_ENABLE_EXTRA_MATH + /** * Executes an assignment operator. * @param p The program. * @param inst The assignment operator to execute. */ -static void bc_program_assign(BcProgram *p, uchar inst) { - +static void +bc_program_assign(BcProgram* p, uchar inst) +{ // The local use_val is true when the assigned value needs to be copied. - BcResult *left, *right, res; - BcNum *l, *r; + BcResult* left; + BcResult* right; + BcResult res; + BcNum* l; + BcNum* r; bool ob, sc, use_val = BC_INST_USE_VAL(inst); bc_program_assignPrep(p, &left, &l, &right, &r); @@ -1253,23 +1437,26 @@ static void bc_program_assign(BcProgram *p, uchar inst) { assert(left->t != BC_RESULT_STR); // If we are assigning a string... - if (right->t == BC_RESULT_STR) { - + if (right->t == BC_RESULT_STR) + { assert(BC_PROG_STR(r)); #if BC_ENABLED if (inst != BC_INST_ASSIGN && inst != BC_INST_ASSIGN_NO_VAL) + { bc_err(BC_ERR_EXEC_TYPE); + } #endif // BC_ENABLED // If we are assigning to an array element... - if (left->t == BC_RESULT_ARRAY_ELEM) { - + if (left->t == BC_RESULT_ARRAY_ELEM) + { BC_SIG_LOCK; // We need to free the number and clear it. bc_num_free(l); + // NOLINTNEXTLINE memcpy(l, r, sizeof(BcNum)); // Now we can pop the results. @@ -1277,11 +1464,11 @@ static void bc_program_assign(BcProgram *p, uchar inst) { BC_SIG_UNLOCK; } - else { - + else + { // If we get here, we are assigning to a variable, which we can use // bc_program_assignStr() for. - BcVec *v = bc_program_vec(p, left->d.loc.loc, BC_TYPE_VAR); + BcVec* v = bc_program_vec(p, left->d.loc.loc, BC_TYPE_VAR); bc_program_assignStr(p, r, v, false); } @@ -1289,8 +1476,10 @@ static void bc_program_assign(BcProgram *p, uchar inst) { // If this is true, the value is going to be used again, so we want to // push a temporary with the string. - if (inst == BC_INST_ASSIGN) { + if (inst == BC_INST_ASSIGN) + { res.t = BC_RESULT_STR; + // NOLINTNEXTLINE memcpy(&res.d.n, r, sizeof(BcNum)); bc_vec_push(&p->results, &res); } @@ -1302,8 +1491,8 @@ static void bc_program_assign(BcProgram *p, uchar inst) { } // If we have a normal assignment operator, not a math one... - if (BC_INST_IS_ASSIGN(inst)) { - + if (BC_INST_IS_ASSIGN(inst)) + { // Assigning to a variable that has a string here is fine because there // is no math done on it. @@ -1313,11 +1502,12 @@ static void bc_program_assign(BcProgram *p, uchar inst) { // type of right to BC_RESULT_ZERO in order to prevent it from being // freed. We also don't have to worry about BC_RESULT_STR because it's // take care of above. - if (right->t == BC_RESULT_TEMP || right->t >= BC_RESULT_IBASE) { - + if (right->t == BC_RESULT_TEMP || right->t >= BC_RESULT_IBASE) + { BC_SIG_LOCK; bc_num_free(l); + // NOLINTNEXTLINE memcpy(l, r, sizeof(BcNum)); right->t = BC_RESULT_ZERO; @@ -1327,8 +1517,8 @@ static void bc_program_assign(BcProgram *p, uchar inst) { else bc_num_copy(l, r); } #if BC_ENABLED - else { - + else + { // If we get here, we are doing a math assignment (+=, -=, etc.). So // we need to prepare for a binary operator. BcBigDig scale = BC_PROG_SCALE(p); @@ -1341,7 +1531,9 @@ static void bc_program_assign(BcProgram *p, uchar inst) { // Get the right type of assignment operator, whether val is used or // NO_VAL for performance. if (!use_val) + { inst -= (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER); + } assert(BC_NUM_RDX_VALID(l)); assert(BC_NUM_RDX_VALID(r)); @@ -1357,62 +1549,24 @@ static void bc_program_assign(BcProgram *p, uchar inst) { // The globals need special handling, especially the non-seed ones. The // first part of the if statement handles them. - if (ob || sc || left->t == BC_RESULT_IBASE) { - - BcVec *v; - BcBigDig *ptr, *ptr_t, val, max, min; - + if (ob || sc || left->t == BC_RESULT_IBASE) + { // Get the actual value. - val = bc_num_bigdig(l); + BcBigDig val = bc_num_bigdig(l); - // Scale needs handling separate from ibase and obase. - if (sc) { - - // Set the min and max. - min = 0; - max = vm.maxes[BC_PROG_GLOBALS_SCALE]; - - // Get a pointer to the stack and to the current value. - v = p->globals_v + BC_PROG_GLOBALS_SCALE; - ptr_t = p->globals + BC_PROG_GLOBALS_SCALE; - } - else { - - // Set the min and max. - min = BC_NUM_MIN_BASE; - if (BC_ENABLE_EXTRA_MATH && ob && (BC_IS_DC || !BC_IS_POSIX)) - min = 0; - max = vm.maxes[ob + BC_PROG_GLOBALS_IBASE]; - - // Get a pointer to the stack and to the current value. - v = p->globals_v + BC_PROG_GLOBALS_IBASE + ob; - ptr_t = p->globals + BC_PROG_GLOBALS_IBASE + ob; - } - - // Check for error. - if (BC_ERR(val > max || val < min)) { - - // This grabs the right error. - BcErr e = left->t - BC_RESULT_IBASE + BC_ERR_EXEC_IBASE; - - bc_verr(e, min, max); - } - - // Set the top of the stack and the actual global value. - ptr = bc_vec_top(v); - *ptr = val; - *ptr_t = val; + bc_program_assignBuiltin(p, sc, ob, val); } #if BC_ENABLE_EXTRA_MATH // To assign to steed, let bc_num_rng() do its magic. - else if (left->t == BC_RESULT_SEED) bc_num_rng(l, &p->rng); + else if (left->t == BC_RESULT_SEED) bc_program_assignSeed(p, l); #endif // BC_ENABLE_EXTRA_MATH BC_SIG_LOCK; // If we needed to use the value, then we need to copy it. Otherwise, we can // pop indiscriminately. Oh, and the copy should be a BC_RESULT_TEMP. - if (use_val) { + if (use_val) + { bc_num_createCopy(&res.d.n, l); res.t = BC_RESULT_TEMP; bc_vec_npop(&p->results, 2); @@ -1434,36 +1588,42 @@ static void bc_program_assign(BcProgram *p, uchar inst) { * @param copy True if the variable's value should be copied to the results * stack. This is only used in dc. */ -static void bc_program_pushVar(BcProgram *p, const char *restrict code, - size_t *restrict bgn, bool pop, bool copy) +static void +bc_program_pushVar(BcProgram* p, const char* restrict code, + size_t* restrict bgn, bool pop, bool copy) { BcResult r; size_t idx = bc_program_index(code, bgn); + BcVec* v; // Set the result appropriately. r.t = BC_RESULT_VAR; r.d.loc.loc = idx; + // Get the stack for the variable. This is used in both bc and dc. + v = bc_program_vec(p, idx, BC_TYPE_VAR); + r.d.loc.stack_idx = v->len - 1; + #if DC_ENABLED // If this condition is true, then we have the hard case, where we have to // adjust dc registers. - if (BC_IS_DC && (pop || copy)) { - - // Get the stack for the variable and the number at the top. - BcVec *v = bc_program_vec(p, idx, BC_TYPE_VAR); - BcNum *num = bc_vec_top(v); + if (BC_IS_DC && (pop || copy)) + { + // Get the number at the top at the top of the stack. + BcNum* num = bc_vec_top(v); // Ensure there are enough elements on the stack. - if (BC_ERR(!BC_PROG_STACK(v, 2 - copy))) { - const char *name = bc_map_name(&p->var_map, idx); + if (BC_ERR(!BC_PROG_STACK(v, 2 - copy))) + { + const char* name = bc_map_name(&p->var_map, idx); bc_verr(BC_ERR_EXEC_STACK_REGISTER, name); } assert(BC_PROG_STACK(v, 2 - copy)); // If the top of the stack is actually a number... - if (!BC_PROG_STR(num)) { - + if (!BC_PROG_STR(num)) + { BC_SIG_LOCK; // Create a copy to go onto the results stack as appropriate. @@ -1479,9 +1639,11 @@ static void bc_program_pushVar(BcProgram *p, const char *restrict code, return; } - else { + else + { // Set the string result. We can just memcpy because all of the // fields in the num should be cleared. + // NOLINTNEXTLINE memcpy(&r.d.n, num, sizeof(BcNum)); r.t = BC_RESULT_STR; } @@ -1502,18 +1664,28 @@ static void bc_program_pushVar(BcProgram *p, const char *restrict code, * vector, and will be updated to point after the index on return. * @param inst The instruction; whether to push an array or an array element. */ -static void bc_program_pushArray(BcProgram *p, const char *restrict code, - size_t *restrict bgn, uchar inst) +static void +bc_program_pushArray(BcProgram* p, const char* restrict code, + size_t* restrict bgn, uchar inst) { - BcResult r, *operand; - BcNum *num; + BcResult r; + BcResult* operand; + BcNum* num; BcBigDig temp; + BcVec* v; // Get the index of the array. r.d.loc.loc = bc_program_index(code, bgn); + // We need the array to get its length. + v = bc_program_vec(p, r.d.loc.loc, BC_TYPE_ARRAY); + assert(v != NULL); + + r.d.loc.stack_idx = v->len - 1; + // Doing an array is easy; just set the result type and finish. - if (inst == BC_INST_ARRAY) { + if (inst == BC_INST_ARRAY) + { r.t = BC_RESULT_ARRAY; bc_vec_push(&p->results, &r); return; @@ -1545,10 +1717,11 @@ static void bc_program_pushArray(BcProgram *p, const char *restrict code, * @param p The program. * @param inst The instruction; whether to do an increment or decrement. */ -static void bc_program_incdec(BcProgram *p, uchar inst) { - +static void +bc_program_incdec(BcProgram* p, uchar inst) +{ BcResult *ptr, res, copy; - BcNum *num; + BcNum* num; uchar inst2; bc_program_prep(p, &ptr, &num, 0); @@ -1559,7 +1732,7 @@ static void bc_program_incdec(BcProgram *p, uchar inst) { copy.t = BC_RESULT_TEMP; bc_num_createCopy(©.d.n, num); - BC_SETJMP_LOCKED(exit); + BC_SETJMP_LOCKED(vm, exit); BC_SIG_UNLOCK; @@ -1574,7 +1747,7 @@ static void bc_program_incdec(BcProgram *p, uchar inst) { bc_vec_push(&p->results, ©); - BC_UNSETJMP; + BC_UNSETJMP(vm); BC_SIG_UNLOCK; @@ -1584,7 +1757,7 @@ static void bc_program_incdec(BcProgram *p, uchar inst) { exit: BC_SIG_MAYLOCK; bc_num_free(©.d.n); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** @@ -1596,15 +1769,15 @@ static void bc_program_incdec(BcProgram *p, uchar inst) { * vector, and will be updated to point after the indices on * return. */ -static void bc_program_call(BcProgram *p, const char *restrict code, - size_t *restrict bgn) +static void +bc_program_call(BcProgram* p, const char* restrict code, size_t* restrict bgn) { BcInstPtr ip; size_t i, nargs; - BcFunc *f; - BcVec *v; - BcAuto *a; - BcResult *arg; + BcFunc* f; + BcVec* v; + BcAuto* a; + BcResult* arg; // Pull the number of arguments out of the bytecode vector. nargs = bc_program_index(code, bgn); @@ -1617,7 +1790,9 @@ static void bc_program_call(BcProgram *p, const char *restrict code, // Error checking. if (BC_ERR(!f->code.len)) bc_verr(BC_ERR_EXEC_UNDEF_FUNC, f->name); if (BC_ERR(nargs != f->nparams)) + { bc_verr(BC_ERR_EXEC_PARAMS, f->nparams, nargs); + } // Set the length of the results stack. We discount the argument, of course. ip.len = p->results.len - nargs; @@ -1628,56 +1803,36 @@ static void bc_program_call(BcProgram *p, const char *restrict code, if (BC_G) bc_program_prepGlobals(p); // Push the arguments onto the stacks of their respective parameters. - for (i = 0; i < nargs; ++i) { - - size_t j; - bool last = true; - + for (i = 0; i < nargs; ++i) + { arg = bc_vec_top(&p->results); if (BC_ERR(arg->t == BC_RESULT_VOID)) bc_err(BC_ERR_EXEC_VOID_VAL); // Get the corresponding parameter. a = bc_vec_item(&f->autos, nargs - 1 - i); - // If I have already pushed to a var, I need to make sure I - // get the previous version, not the already pushed one. This condition - // must be true for that to even be possible. - if (arg->t == BC_RESULT_VAR || arg->t == BC_RESULT_ARRAY) { - - // Loop through all of the previous parameters. - for (j = 0; j < i && last; ++j) { - - BcAuto *aptr = bc_vec_item(&f->autos, nargs - 1 - j); - - // This condition is true if there is a previous parameter with - // the same name *and* type because variables and arrays do not - // interfere with each other. - last = (arg->d.loc.loc != aptr->idx || - (!aptr->type) != (arg->t == BC_RESULT_VAR)); - } - } - // Actually push the value onto the parameter's stack. - bc_program_copyToVar(p, a->idx, a->type, last); + bc_program_copyToVar(p, a->idx, a->type); } BC_SIG_LOCK; // Push zeroes onto the stacks of the auto variables. - for (; i < f->autos.len; ++i) { - + for (; i < f->autos.len; ++i) + { // Get the auto and its stack. a = bc_vec_item(&f->autos, i); v = bc_program_vec(p, a->idx, a->type); // If a variable, just push a 0; otherwise, push an array. - if (a->type == BC_TYPE_VAR) { - BcNum *n = bc_vec_pushEmpty(v); + if (a->type == BC_TYPE_VAR) + { + BcNum* n = bc_vec_pushEmpty(v); bc_num_init(n, BC_NUM_DEF_SIZE); } - else { - - BcVec *v2; + else + { + BcVec* v2; assert(a->type == BC_TYPE_ARRAY); @@ -1698,11 +1853,12 @@ static void bc_program_call(BcProgram *p, const char *restrict code, * @param inst The return instruction. bc can return void, and we need to know * if it is. */ -static void bc_program_return(BcProgram *p, uchar inst) { - - BcResult *res; - BcFunc *f; - BcInstPtr *ip; +static void +bc_program_return(BcProgram* p, uchar inst) +{ + BcResult* res; + BcFunc* f; + BcInstPtr* ip; size_t i, nresults; // Get the instruction pointer. @@ -1725,25 +1881,26 @@ static void bc_program_return(BcProgram *p, uchar inst) { res = bc_program_prepResult(p); // If we are returning normally... - if (inst == BC_INST_RET) { - - BcNum *num; - BcResult *operand; + if (inst == BC_INST_RET) + { + BcNum* num; + BcResult* operand; // Prepare and copy the return value. bc_program_operand(p, &operand, &num, 1); - if (BC_PROG_STR(num)) { - + if (BC_PROG_STR(num)) + { // We need to set this because otherwise, it will be a // BC_RESULT_TEMP, and BC_RESULT_TEMP needs an actual number to make // it easier to do type checking. res->t = BC_RESULT_STR; + // NOLINTNEXTLINE memcpy(&res->d.n, num, sizeof(BcNum)); } - else { - + else + { BC_SIG_LOCK; bc_num_createCopy(&res->d.n, num); @@ -1751,8 +1908,8 @@ static void bc_program_return(BcProgram *p, uchar inst) { } // Void is easy; set the result. else if (inst == BC_INST_RET_VOID) res->t = BC_RESULT_VOID; - else { - + else + { BC_SIG_LOCK; // If we get here, the instruction is for returning a zero, so do that. @@ -1762,14 +1919,16 @@ static void bc_program_return(BcProgram *p, uchar inst) { BC_SIG_MAYUNLOCK; // We need to pop items off of the stacks of arguments and autos as well. - for (i = 0; i < f->autos.len; ++i) { - - BcAuto *a = bc_vec_item(&f->autos, i); - BcVec *v = bc_program_vec(p, a->idx, a->type); + for (i = 0; i < f->autos.len; ++i) + { + BcAuto* a = bc_vec_item(&f->autos, i); + BcVec* v = bc_program_vec(p, a->idx, a->type); bc_vec_pop(v); } + BC_SIG_LOCK; + // When we retire, pop all of the unused results. bc_program_retire(p, 1, nresults); @@ -1778,6 +1937,8 @@ static void bc_program_return(BcProgram *p, uchar inst) { // Pop the stack. This is what causes the function to actually "return." bc_vec_pop(&p->stack); + + BC_SIG_UNLOCK; } #endif // BC_ENABLED @@ -1786,23 +1947,27 @@ static void bc_program_return(BcProgram *p, uchar inst) { * @param p The program. * @param inst The builtin to execute. */ -static void bc_program_builtin(BcProgram *p, uchar inst) { - - BcResult *opd, *res; - BcNum *num; +static void +bc_program_builtin(BcProgram* p, uchar inst) +{ + BcResult* opd; + BcResult* res; + BcNum* num; bool len = (inst == BC_INST_LENGTH); // Ensure we have a valid builtin. #if BC_ENABLE_EXTRA_MATH assert(inst >= BC_INST_LENGTH && inst <= BC_INST_IRAND); #else // BC_ENABLE_EXTRA_MATH - assert(inst >= BC_INST_LENGTH && inst <= BC_INST_ABS); + assert(inst >= BC_INST_LENGTH && inst <= BC_INST_IS_STRING); #endif // BC_ENABLE_EXTRA_MATH #ifndef BC_PROG_NO_STACK_CHECK // Check stack for dc. if (BC_IS_DC && BC_ERR(!BC_PROG_STACK(&p->results, 1))) + { bc_err(BC_ERR_EXEC_STACK); + } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, 1)); @@ -1815,15 +1980,18 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { // We need to ensure that strings and arrays aren't passed to most builtins. // The scale function can take strings in dc. - if (!len && (inst != BC_INST_SCALE_FUNC || BC_IS_BC)) + if (!len && (inst != BC_INST_SCALE_FUNC || BC_IS_BC) && + inst != BC_INST_IS_NUMBER && inst != BC_INST_IS_STRING) + { bc_program_type_num(opd, num); + } // Square root is easy. if (inst == BC_INST_SQRT) bc_num_sqrt(num, &res->d.n, BC_PROG_SCALE(p)); // Absolute value is easy. - else if (inst == BC_INST_ABS) { - + else if (inst == BC_INST_ABS) + { BC_SIG_LOCK; bc_num_createCopy(&res->d.n, num); @@ -1832,10 +2000,34 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { BC_NUM_NEG_CLR_NP(res->d.n); } + + // Testing for number or string is easy. + else if (inst == BC_INST_IS_NUMBER || inst == BC_INST_IS_STRING) + { + bool cond; + bool is_str; + + BC_SIG_LOCK; + + bc_num_init(&res->d.n, BC_NUM_DEF_SIZE); + + BC_SIG_UNLOCK; + + // Test if the number is a string. + is_str = BC_PROG_STR(num); + + // This confusing condition simply means that the instruction must be + // true if is_str is, or it must be false if is_str is. Otherwise, the + // returned value is false (0). + cond = ((inst == BC_INST_IS_STRING) == is_str); + if (cond) bc_num_one(&res->d.n); + } + #if BC_ENABLE_EXTRA_MATH - // irand() is easy. - else if (inst == BC_INST_IRAND) { + // irand() is easy. + else if (inst == BC_INST_IRAND) + { BC_SIG_LOCK; bc_num_init(&res->d.n, num->len - BC_NUM_RDX_VAL(num)); @@ -1844,39 +2036,45 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { bc_num_irand(num, &res->d.n, &p->rng); } + #endif // BC_ENABLE_EXTRA_MATH // Everything else is...not easy. - else { - + else + { BcBigDig val = 0; // Well, scale() is easy, but length() is not. - if (len) { - + if (len) + { // If we are bc and we have an array... - if (opd->t == BC_RESULT_ARRAY) { - + if (opd->t == BC_RESULT_ARRAY) + { // Yes, this is one place where we need to cast the number from // bc_program_num() to a vector. - BcVec *v = (BcVec*) num; + BcVec* v = (BcVec*) num; + + // XXX: If this is changed, you should also change the similar + // code in bc_program_asciify(). #if BC_ENABLED // Dereference the array, if necessary. if (BC_IS_BC && v->size == sizeof(uchar)) + { v = bc_program_dereference(p, v); + } #endif // BC_ENABLED assert(v->size == sizeof(BcNum)); val = (BcBigDig) v->len; } - else { - + else + { // If the item is a string... - if (!BC_PROG_NUM(opd, num)) { - - char *str; + if (!BC_PROG_NUM(opd, num)) + { + char* str; // Get the string, then get the length. str = bc_program_string(p, num); @@ -1892,7 +2090,9 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { // Like I said; scale() is actually easy. It just also needs the integer // conversion that length() does. else if (BC_IS_BC || BC_PROG_NUM(opd, num)) + { val = (BcBigDig) bc_num_scale(num); + } BC_SIG_LOCK; @@ -1909,10 +2109,15 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { * Executes a divmod. * @param p The program. */ -static void bc_program_divmod(BcProgram *p) { - - BcResult *opd1, *opd2, *res, *res2; - BcNum *n1, *n2; +static void +bc_program_divmod(BcProgram* p) +{ + BcResult* opd1; + BcResult* opd2; + BcResult* res; + BcResult* res2; + BcNum* n1; + BcNum* n2; size_t req; // We grow first to avoid pointer invalidation. @@ -1946,16 +2151,24 @@ static void bc_program_divmod(BcProgram *p) { * Executes modular exponentiation. * @param p The program. */ -static void bc_program_modexp(BcProgram *p) { - - BcResult *r1, *r2, *r3, *res; - BcNum *n1, *n2, *n3; +static void +bc_program_modexp(BcProgram* p) +{ + BcResult* r1; + BcResult* r2; + BcResult* r3; + BcResult* res; + BcNum* n1; + BcNum* n2; + BcNum* n3; #if DC_ENABLED // Check the stack. if (BC_IS_DC && BC_ERR(!BC_PROG_STACK(&p->results, 3))) + { bc_err(BC_ERR_EXEC_STACK); + } #endif // DC_ENABLED @@ -1973,7 +2186,9 @@ static void bc_program_modexp(BcProgram *p) { // Make sure that the values have their pointers updated, if necessary. // Only array elements are possible because this is dc. if (r1->t == BC_RESULT_ARRAY_ELEM && (r1->t == r2->t || r1->t == r3->t)) + { n1 = bc_program_num(p, r1); + } BC_SIG_LOCK; @@ -1991,58 +2206,40 @@ static void bc_program_modexp(BcProgram *p) { * @param p The program. * @param n The number to asciify. */ -static uchar bc_program_asciifyNum(BcProgram *p, BcNum *n) { - - BcNum num; - BcBigDig val; - -#ifndef NDEBUG - // This is entirely to satisfy a useless scan-build error. - val = 0; -#endif // NDEBUG - - bc_num_clear(&num); - - BC_SETJMP(num_err); - - BC_SIG_LOCK; - - bc_num_createCopy(&num, n); - - BC_SIG_UNLOCK; +static uchar +bc_program_asciifyNum(BcProgram* p, BcNum* n) +{ + bc_num_copy(&p->asciify, n); // We want to clear the scale and sign for easy mod later. - bc_num_truncate(&num, num.scale); - BC_NUM_NEG_CLR_NP(num); + bc_num_truncate(&p->asciify, p->asciify.scale); + BC_NUM_NEG_CLR(&p->asciify); // This is guaranteed to not have a divide by 0 // because strmb is equal to 256. - bc_num_mod(&num, &p->strmb, &num, 0); + bc_num_mod(&p->asciify, &p->strmb, &p->asciify, 0); // This is also guaranteed to not error because num is in the range // [0, UCHAR_MAX], which is definitely in range for a BcBigDig. And // it is not negative. - val = bc_num_bigdig2(&num); - -num_err: - BC_SIG_MAYLOCK; - bc_num_free(&num); - BC_LONGJMP_CONT; - return (uchar) val; + return (uchar) bc_num_bigdig2(&p->asciify); } /** - * Executes the "asciify" command in dc. - * @param p The program. - * @param fidx The index of the current function. + * Executes the "asciify" command in bc and dc. + * @param p The program. */ -static void bc_program_asciify(BcProgram *p, size_t fidx) { - +static void +bc_program_asciify(BcProgram* p) +{ BcResult *r, res; - BcNum *n; - char str[2], *str2; + BcNum* n; uchar c; size_t idx; +#if BC_ENABLED + // This is in the outer scope because it has to be freed after a jump. + char* temp_str; +#endif // BC_ENABLED // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); @@ -2053,44 +2250,109 @@ static void bc_program_asciify(BcProgram *p, size_t fidx) { bc_program_operand(p, &r, &n, 0); assert(n != NULL); + assert(BC_IS_BC || r->t != BC_RESULT_ARRAY); - // Asciify. - if (BC_PROG_NUM(r, n)) c = bc_program_asciifyNum(p, n); - else { +#if BC_ENABLED + // Handle arrays in bc specially. + if (r->t == BC_RESULT_ARRAY) + { + // Yes, this is one place where we need to cast the number from + // bc_program_num() to a vector. + BcVec* v = (BcVec*) n; + size_t i; - // Get the string itself, then the first character. - str2 = bc_program_string(p, n); - c = (uchar) str2[0]; + // XXX: If this is changed, you should also change the similar code in + // bc_program_builtin(). + + // Dereference the array, if necessary. + if (v->size == sizeof(uchar)) + { + v = bc_program_dereference(p, v); + } + + assert(v->size == sizeof(BcNum)); + + // Allocate the string and set the jump for it. + BC_SIG_LOCK; + temp_str = bc_vm_malloc(v->len + 1); + BC_SETJMP_LOCKED(vm, exit); + BC_SIG_UNLOCK; + + // Convert the array. + for (i = 0; i < v->len; ++i) + { + BcNum* num = (BcNum*) bc_vec_item(v, i); + + if (BC_PROG_STR(num)) + { + temp_str[i] = (bc_program_string(p, num))[0]; + } + else + { + temp_str[i] = (char) bc_program_asciifyNum(p, num); + } + } + + temp_str[v->len] = '\0'; + + // Store the string in the slab and map, and free the temp string. + BC_SIG_LOCK; + idx = bc_program_addString(p, temp_str); + free(temp_str); + BC_UNSETJMP(vm); + BC_SIG_UNLOCK; } + else +#endif // BC_ENABLED + { + char str[2]; + char* str2; - // Fill the resulting string. - str[0] = (char) c; - str[1] = '\0'; + // Asciify. + if (BC_PROG_NUM(r, n)) c = bc_program_asciifyNum(p, n); + else + { + // Get the string itself, then the first character. + str2 = bc_program_string(p, n); + c = (uchar) str2[0]; + } - // Add the string to the data structures. - BC_SIG_LOCK; - idx = bc_program_addString(p, str, fidx); - BC_SIG_UNLOCK; + // Fill the resulting string. + str[0] = (char) c; + str[1] = '\0'; + + // Add the string to the data structures. + BC_SIG_LOCK; + idx = bc_program_addString(p, str); + BC_SIG_UNLOCK; + } // Set the result res.t = BC_RESULT_STR; bc_num_clear(&res.d.n); - res.d.n.rdx = fidx; res.d.n.scale = idx; // Pop and push. bc_vec_pop(&p->results); bc_vec_push(&p->results, &res); + + return; + +#if BC_ENABLED +exit: + free(temp_str); +#endif // BC_ENABLED } /** * Streams a number or a string to stdout. * @param p The program. */ -static void bc_program_printStream(BcProgram *p) { - - BcResult *r; - BcNum *n; +static void +bc_program_printStream(BcProgram* p) +{ + BcResult* r; + BcNum* n; // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); @@ -2119,11 +2381,12 @@ static void bc_program_printStream(BcProgram *p) { * @param bgn An in/out parameter; the start of the index in the bytecode * vector, and will be updated to point after the index on return. */ -static void bc_program_regStackLen(BcProgram *p, const char *restrict code, - size_t *restrict bgn) +static void +bc_program_regStackLen(BcProgram* p, const char* restrict code, + size_t* restrict bgn) { size_t idx = bc_program_index(code, bgn); - BcVec *v = bc_program_vec(p, idx, BC_TYPE_VAR); + BcVec* v = bc_program_vec(p, idx, BC_TYPE_VAR); bc_program_pushBigdig(p, (BcBigDig) v->len, BC_RESULT_TEMP); } @@ -2132,7 +2395,9 @@ static void bc_program_regStackLen(BcProgram *p, const char *restrict code, * Pushes the length of the results stack onto the results stack. * @param p The program. */ -static void bc_program_stackLen(BcProgram *p) { +static void +bc_program_stackLen(BcProgram* p) +{ bc_program_pushBigdig(p, (BcBigDig) p->results.len, BC_RESULT_TEMP); } @@ -2143,10 +2408,11 @@ static void bc_program_stackLen(BcProgram *p) { * 2, and one to pop the amount equal to the number at the top of * the results stack. */ -static void bc_program_nquit(BcProgram *p, uchar inst) { - - BcResult *opnd; - BcNum *num; +static void +bc_program_nquit(BcProgram* p, uchar inst) +{ + BcResult* opnd; + BcNum* num; BcBigDig val; size_t i; @@ -2155,8 +2421,8 @@ static void bc_program_nquit(BcProgram *p, uchar inst) { // Get the number of executions to pop. if (inst == BC_INST_QUIT) val = 2; - else { - + else + { bc_program_prep(p, &opnd, &num, 0); val = bc_num_bigdig(num); @@ -2164,8 +2430,8 @@ static void bc_program_nquit(BcProgram *p, uchar inst) { } // Loop over the tail call stack and adjust the quit value appropriately. - for (i = 0; val && i < p->tail_calls.len; ++i) { - + for (i = 0; val && i < p->tail_calls.len; ++i) + { // Get the number of tail calls for this one. size_t calls = *((size_t*) bc_vec_item_rev(&p->tail_calls, i)) + 1; @@ -2175,17 +2441,21 @@ static void bc_program_nquit(BcProgram *p, uchar inst) { } // If we don't have enough executions, just quit. - if (i == p->stack.len) { - vm.status = BC_STATUS_QUIT; + if (i == p->stack.len) + { + vm->status = BC_STATUS_QUIT; BC_JMP; } - else { + else + { // We can always pop the last item we reached on the tail call stack // because these are for tail calls. That means that any executions that // we would not have quit in that position on the stack would have quit // anyway. + BC_SIG_LOCK; bc_vec_npop(&p->stack, i); bc_vec_npop(&p->tail_calls, i); + BC_SIG_UNLOCK; } } @@ -2193,14 +2463,17 @@ static void bc_program_nquit(BcProgram *p, uchar inst) { * Pushes the depth of the execution stack onto the stack. * @param p The program. */ -static void bc_program_execStackLen(BcProgram *p) { - +static void +bc_program_execStackLen(BcProgram* p) +{ size_t i, amt, len = p->tail_calls.len; amt = len; for (i = 0; i < len; ++i) + { amt += *((size_t*) bc_vec_item(&p->tail_calls, i)); + } bc_program_pushBigdig(p, (BcBigDig) amt, BC_RESULT_TEMP); } @@ -2214,15 +2487,16 @@ static void bc_program_execStackLen(BcProgram *p) { * @param cond True if the execution is conditional, false otherwise. * @param len The number of bytes in the bytecode vector. */ -static void bc_program_execStr(BcProgram *p, const char *restrict code, - size_t *restrict bgn, bool cond, size_t len) +static void +bc_program_execStr(BcProgram* p, const char* restrict code, + size_t* restrict bgn, bool cond, size_t len) { - BcResult *r; - char *str; - BcFunc *f; + BcResult* r; + char* str; + BcFunc* f; BcInstPtr ip; size_t fidx; - BcNum *n; + BcNum* n; assert(p->stack.len == p->tail_calls.len); @@ -2235,10 +2509,14 @@ static void bc_program_execStr(BcProgram *p, const char *restrict code, bc_program_operand(p, &r, &n, 0); // If execution is conditional... - if (cond) { - + if (cond) + { bool exec; - size_t idx, then_idx, else_idx; + size_t then_idx; + // These are volatile to quiet warnings on GCC about clobbering with + // longjmp(). + volatile size_t else_idx; + volatile size_t idx; // Get the index of the "then" var and "else" var. then_idx = bc_program_index(code, bgn); @@ -2250,23 +2528,25 @@ static void bc_program_execStr(BcProgram *p, const char *restrict code, idx = exec ? then_idx : else_idx; BC_SIG_LOCK; - BC_SETJMP_LOCKED(exit); + BC_SETJMP_LOCKED(vm, exit); // If we are supposed to execute, execute. If else_idx == SIZE_MAX, that // means there was no else clause, so if execute is false and else does // not exist, we don't execute. The goto skips all of the setup for the // execution. if (exec || (else_idx != SIZE_MAX)) + { n = bc_vec_top(bc_program_vec(p, idx, BC_TYPE_VAR)); + } else goto exit; if (BC_ERR(!BC_PROG_STR(n))) bc_err(BC_ERR_EXEC_TYPE); - BC_UNSETJMP; + BC_UNSETJMP(vm); BC_SIG_UNLOCK; } - else { - + else + { // In non-conditional situations, only the top of stack can be executed, // and in those cases, variables are not allowed to be "on the stack"; // they are only put on the stack to be assigned to. @@ -2287,39 +2567,39 @@ static void bc_program_execStr(BcProgram *p, const char *restrict code, f = bc_vec_item(&p->fns, fidx); // If the function has not been parsed yet... - if (!f->code.len) { - + if (!f->code.len) + { BC_SIG_LOCK; - if (!BC_PARSE_IS_INITED(&vm.read_prs, p)) { - - bc_parse_init(&vm.read_prs, p, fidx); + if (!BC_PARSE_IS_INITED(&vm->read_prs, p)) + { + bc_parse_init(&vm->read_prs, p, fidx); // Initialize this too because bc_vm_shutdown() expects them to be // initialized togther. - bc_vec_init(&vm.read_buf, sizeof(char), BC_DTOR_NONE); + bc_vec_init(&vm->read_buf, sizeof(char), BC_DTOR_NONE); } // This needs to be updated because the parser could have been used // somewhere else - else bc_parse_updateFunc(&vm.read_prs, fidx); + else bc_parse_updateFunc(&vm->read_prs, fidx); - bc_lex_file(&vm.read_prs.l, vm.file); + bc_lex_file(&vm->read_prs.l, vm->file); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; - // Parse. - bc_parse_text(&vm.read_prs, str, false); - vm.expr(&vm.read_prs, BC_PARSE_NOCALL); + // Parse. Only one expression is needed, so stdin isn't used. + bc_parse_text(&vm->read_prs, str, BC_MODE_FILE); BC_SIG_LOCK; + vm->expr(&vm->read_prs, BC_PARSE_NOCALL); - BC_UNSETJMP; + BC_UNSETJMP(vm); // We can just assert this here because // dc should parse everything until EOF. - assert(vm.read_prs.l.t == BC_LEX_EOF); + assert(vm->read_prs.l.t == BC_LEX_EOF); BC_SIG_UNLOCK; } @@ -2329,15 +2609,17 @@ static void bc_program_execStr(BcProgram *p, const char *restrict code, ip.len = p->results.len; ip.func = fidx; + BC_SIG_LOCK; + // Pop the operand. bc_vec_pop(&p->results); // Tail call processing. This condition means that there is more on the // execution stack, and we are at the end of the bytecode vector, and the // last instruction is just a BC_INST_POP_EXEC, which would return. - if (p->stack.len > 1 && *bgn == len - 1 && code[*bgn] == BC_INST_POP_EXEC) { - - size_t *call_ptr = bc_vec_top(&p->tail_calls); + if (p->stack.len > 1 && *bgn == len - 1 && code[*bgn] == BC_INST_POP_EXEC) + { + size_t* call_ptr = bc_vec_top(&p->tail_calls); // Add one to the tail call. *call_ptr += 1; @@ -2352,6 +2634,8 @@ static void bc_program_execStr(BcProgram *p, const char *restrict code, // Push the new function onto the execution stack and return. bc_vec_push(&p->stack, &ip); + BC_SIG_UNLOCK; + return; err: @@ -2364,19 +2648,22 @@ static void bc_program_execStr(BcProgram *p, const char *restrict code, exit: bc_vec_pop(&p->results); - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } /** * Prints every item on the results stack, one per line. * @param p The program. */ -static void bc_program_printStack(BcProgram *p) { - +static void +bc_program_printStack(BcProgram* p) +{ size_t idx; for (idx = 0; idx < p->results.len; ++idx) + { bc_program_print(p, BC_INST_PRINT, idx); + } } #endif // DC_ENABLED @@ -2385,8 +2672,9 @@ static void bc_program_printStack(BcProgram *p) { * @param p The program. * @param inst Which global to push, as an instruction. */ -static void bc_program_pushGlobal(BcProgram *p, uchar inst) { - +static void +bc_program_pushGlobal(BcProgram* p, uchar inst) +{ BcResultType t; // Make sure the instruction is valid. @@ -2402,17 +2690,35 @@ static void bc_program_pushGlobal(BcProgram *p, uchar inst) { * @param p The program. * @param inst Which global setting to push, as an instruction. */ -static void bc_program_globalSetting(BcProgram *p, uchar inst) { - +static void +bc_program_globalSetting(BcProgram* p, uchar inst) +{ BcBigDig val; // Make sure the instruction is valid. +#if DC_ENABLED + assert((inst >= BC_INST_LINE_LENGTH && inst <= BC_INST_LEADING_ZERO) || + (BC_IS_DC && inst == BC_INST_EXTENDED_REGISTERS)); +#else // DC_ENABLED assert(inst >= BC_INST_LINE_LENGTH && inst <= BC_INST_LEADING_ZERO); +#endif // DC_ENABLED - if (inst == BC_INST_LINE_LENGTH) val = (BcBigDig) vm.line_len; + if (inst == BC_INST_LINE_LENGTH) + { + val = (BcBigDig) vm->line_len; + } #if BC_ENABLED - else if (inst == BC_INST_GLOBAL_STACKS) val = (BC_G != 0); + else if (inst == BC_INST_GLOBAL_STACKS) + { + val = (BC_G != 0); + } #endif // BC_ENABLED +#if DC_ENABLED + else if (inst == BC_INST_EXTENDED_REGISTERS) + { + val = (DC_X != 0); + } +#endif // DC_ENABLED else val = (BC_Z != 0); // Push the global. @@ -2425,9 +2731,10 @@ static void bc_program_globalSetting(BcProgram *p, uchar inst) { * Pushes the value of seed on the stack. * @param p The program. */ -static void bc_program_pushSeed(BcProgram *p) { - - BcResult *res; +static void +bc_program_pushSeed(BcProgram* p) +{ + BcResult* res; res = bc_program_prepResult(p); res->t = BC_RESULT_SEED; @@ -2450,27 +2757,22 @@ static void bc_program_pushSeed(BcProgram *p) { * @param p The program. * @param id_ptr The ID of the function as inserted into the map. */ -static void bc_program_addFunc(BcProgram *p, BcId *id_ptr) { - - BcInstPtr *ip; - BcFunc *f; +static void +bc_program_addFunc(BcProgram* p, BcId* id_ptr) +{ + BcFunc* f; BC_SIG_ASSERT_LOCKED; // Push and init. f = bc_vec_pushEmpty(&p->fns); bc_func_init(f, id_ptr->name); - - // This is to make sure pointers are updated if the array was moved. - if (p->stack.len) { - ip = bc_vec_top(&p->stack); - bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, ip->func)); - } } -size_t bc_program_insertFunc(BcProgram *p, const char *name) { - - BcId *id_ptr; +size_t +bc_program_insertFunc(BcProgram* p, const char* name) +{ + BcId* id_ptr; bool new; size_t idx; @@ -2484,15 +2786,16 @@ size_t bc_program_insertFunc(BcProgram *p, const char *name) { idx = id_ptr->idx; // If the function is new... - if (new) { - + if (new) + { // Add the function to the fns array. bc_program_addFunc(p, id_ptr); } #if BC_ENABLED // bc has to reset the function because it's about to be redefined. - else if (BC_IS_BC) { - BcFunc *func = bc_vec_item(&p->fns, idx); + else if (BC_IS_BC) + { + BcFunc* func = bc_vec_item(&p->fns, idx); bc_func_reset(func); } #endif // BC_ENABLED @@ -2500,17 +2803,25 @@ size_t bc_program_insertFunc(BcProgram *p, const char *name) { return idx; } -#ifndef NDEBUG -void bc_program_free(BcProgram *p) { - +#if BC_DEBUG || BC_ENABLE_MEMCHECK +void +bc_program_free(BcProgram* p) +{ +#if BC_ENABLED size_t i; +#endif // BC_ENABLED BC_SIG_ASSERT_LOCKED; assert(p != NULL); +#if BC_ENABLED // Free the globals stacks. - for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) bc_vec_free(p->globals_v + i); + for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) + { + bc_vec_free(p->globals_v + i); + } +#endif // BC_ENABLED bc_vec_free(&p->fns); bc_vec_free(&p->fn_map); @@ -2520,6 +2831,12 @@ void bc_program_free(BcProgram *p) { bc_vec_free(&p->arr_map); bc_vec_free(&p->results); bc_vec_free(&p->stack); + bc_vec_free(&p->consts); + bc_vec_free(&p->const_map); + bc_vec_free(&p->strs); + bc_vec_free(&p->str_map); + + bc_num_free(&p->asciify); #if BC_ENABLED if (BC_IS_BC) bc_num_free(&p->last); @@ -2533,10 +2850,11 @@ void bc_program_free(BcProgram *p) { if (BC_IS_DC) bc_vec_free(&p->tail_calls); #endif // DC_ENABLED } -#endif // NDEBUG - -void bc_program_init(BcProgram *p) { +#endif // BC_DEBUG || BC_ENABLE_MEMCHECK +void +bc_program_init(BcProgram* p) +{ BcInstPtr ip; size_t i; @@ -2545,23 +2863,26 @@ void bc_program_init(BcProgram *p) { assert(p != NULL); // We want this clear. + // NOLINTNEXTLINE memset(&ip, 0, sizeof(BcInstPtr)); // Setup the globals stacks and the current values. - for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { - + for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) + { BcBigDig val = i == BC_PROG_GLOBALS_SCALE ? 0 : BC_BASE; +#if BC_ENABLED bc_vec_init(p->globals_v + i, sizeof(BcBigDig), BC_DTOR_NONE); bc_vec_push(p->globals_v + i, &val); +#endif // BC_ENABLED p->globals[i] = val; } #if DC_ENABLED // dc-only setup. - if (BC_IS_DC) { - + if (BC_IS_DC) + { bc_vec_init(&p->tail_calls, sizeof(size_t), BC_DTOR_NONE); // We want an item for the main function on the tail call stack. @@ -2573,6 +2894,8 @@ void bc_program_init(BcProgram *p) { bc_num_setup(&p->strmb, p->strmb_num, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(&p->strmb, BC_NUM_STREAM_BASE); + bc_num_init(&p->asciify, BC_NUM_DEF_SIZE); + #if BC_ENABLE_EXTRA_MATH // We need to initialize srand() just in case /dev/urandom and /dev/random // are not available. @@ -2584,11 +2907,11 @@ void bc_program_init(BcProgram *p) { if (BC_IS_BC) bc_num_init(&p->last, BC_NUM_DEF_SIZE); #endif // BC_ENABLED -#ifndef NDEBUG +#if BC_DEBUG bc_vec_init(&p->fns, sizeof(BcFunc), BC_DTOR_FUNC); -#else // NDEBUG +#else // BC_DEBUG bc_vec_init(&p->fns, sizeof(BcFunc), BC_DTOR_NONE); -#endif // NDEBUG +#endif // BC_DEBUG bc_map_init(&p->fn_map); bc_program_insertFunc(p, bc_func_main); bc_program_insertFunc(p, bc_func_read); @@ -2605,24 +2928,70 @@ void bc_program_init(BcProgram *p) { bc_vec_init(&p->stack, sizeof(BcInstPtr), BC_DTOR_NONE); bc_vec_push(&p->stack, &ip); - // Make sure the pointers are properly set up. - bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN)); - - assert(p->consts != NULL && p->strs != NULL); + bc_vec_init(&p->consts, sizeof(BcConst), BC_DTOR_CONST); + bc_map_init(&p->const_map); + bc_vec_init(&p->strs, sizeof(char*), BC_DTOR_NONE); + bc_map_init(&p->str_map); } -void bc_program_reset(BcProgram *p) { +void +bc_program_printStackTrace(BcProgram* p) +{ + size_t i, max_digits; + + max_digits = bc_vm_numDigits(p->stack.len - 1); + + for (i = 0; i < p->stack.len; ++i) + { + BcInstPtr* ip = bc_vec_item_rev(&p->stack, i); + BcFunc* f = bc_vec_item(&p->fns, ip->func); + size_t j, digits; + + digits = bc_vm_numDigits(i); + + bc_file_puts(&vm->ferr, bc_flush_none, " "); + + for (j = 0; j < max_digits - digits; ++j) + { + bc_file_putchar(&vm->ferr, bc_flush_none, ' '); + } + + bc_file_printf(&vm->ferr, "%zu: %s", i, f->name); + +#if BC_ENABLED + if (BC_IS_BC && ip->func != BC_PROG_MAIN && ip->func != BC_PROG_READ) + { + bc_file_puts(&vm->ferr, bc_flush_none, "()"); + } +#endif // BC_ENABLED + + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + } +} - BcFunc *f; - BcInstPtr *ip; +void +bc_program_reset(BcProgram* p) +{ + BcFunc* f; + BcInstPtr* ip; BC_SIG_ASSERT_LOCKED; - // Pop all but the last execution and all results. + // Pop all but the last execution. bc_vec_npop(&p->stack, p->stack.len - 1); - bc_vec_popAll(&p->results); + +#if DC_ENABLED + // We need to pop tail calls too. + if (BC_IS_DC) bc_vec_npop(&p->tail_calls, p->tail_calls.len - 1); +#endif // DC_ENABLED #if BC_ENABLED + // Clear the stack if we are in bc. We have to do this in bc because bc's + // stack is implicit. + // + // XXX: We don't do this in dc because other dc implementations don't. + if (BC_IS_BC || !BC_I) bc_vec_popAll(&p->results); + // Clear the globals' stacks. if (BC_G) bc_program_popGlobals(p, true); #endif // BC_ENABLED @@ -2633,69 +3002,100 @@ void bc_program_reset(BcProgram *p) { // Reset the instruction pointer. ip = bc_vec_top(&p->stack); - bc_program_setVecs(p, f); + // NOLINTNEXTLINE memset(ip, 0, sizeof(BcInstPtr)); - // Write the ready message for a signal, and clear the signal. - if (vm.sig) { - bc_file_write(&vm.fout, bc_flush_none, bc_program_ready_msg, - bc_program_ready_msg_len); - bc_file_flush(&vm.fout, bc_flush_err); - vm.sig = 0; + if (BC_SIG_INTERRUPT(vm)) + { + // Write the ready message for a signal. + bc_file_printf(&vm->fout, "%s", bc_program_ready_msg); + bc_file_flush(&vm->fout, bc_flush_err); } -} -void bc_program_exec(BcProgram *p) { + // Clear the signal. + vm->sig = 0; +} +void +bc_program_exec(BcProgram* p) +{ size_t idx; - BcResult r, *ptr; - BcInstPtr *ip; - BcFunc *func; - char *code; + BcResult r; + BcResult* ptr; + BcInstPtr* ip; + BcFunc* func; + char* code; bool cond = false; uchar inst; #if BC_ENABLED - BcNum *num; + BcNum* num; #endif // BC_ENABLED #if !BC_HAS_COMPUTED_GOTO -#ifndef NDEBUG +#if BC_DEBUG size_t jmp_bufs_len; -#endif // NDEBUG +#endif // BC_DEBUG #endif // !BC_HAS_COMPUTED_GOTO #if BC_HAS_COMPUTED_GOTO + +#if BC_GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpedantic" +#endif // BC_GCC + +#if BC_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu-label-as-value" +#endif // BC_CLANG + BC_PROG_LBLS; BC_PROG_LBLS_ASSERT; +#if BC_CLANG +#pragma clang diagnostic pop +#endif // BC_CLANG + +#if BC_GCC +#pragma GCC diagnostic pop +#endif // BC_GCC + // BC_INST_INVALID is a marker for the end so that we don't have to have an // execution loop. func = (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN); bc_vec_pushByte(&func->code, BC_INST_INVALID); #endif // BC_HAS_COMPUTED_GOTO + BC_SETJMP(vm, end); + ip = bc_vec_top(&p->stack); func = (BcFunc*) bc_vec_item(&p->fns, ip->func); code = func->code.v; - // Ensure the pointers are correct. - bc_program_setVecs(p, func); - #if !BC_HAS_COMPUTED_GOTO -#ifndef NDEBUG - jmp_bufs_len = vm.jmp_bufs.len; -#endif // NDEBUG +#if BC_DEBUG + jmp_bufs_len = vm->jmp_bufs.len; +#endif // BC_DEBUG // This loop is the heart of the execution engine. It *is* the engine. For // computed goto, it is ignored. while (ip->idx < func->code.len) #endif // !BC_HAS_COMPUTED_GOTO { - BC_SIG_ASSERT_NOT_LOCKED; #if BC_HAS_COMPUTED_GOTO +#if BC_GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpedantic" +#endif // BC_GCC + +#if BC_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu-label-as-value" +#endif // BC_CLANG + BC_PROG_JUMP(inst, code, ip); #else // BC_HAS_COMPUTED_GOTO @@ -2706,19 +3106,20 @@ void bc_program_exec(BcProgram *p) { #endif // BC_HAS_COMPUTED_GOTO #if BC_DEBUG_CODE - bc_file_printf(&vm.ferr, "inst: %s\n", bc_inst_names[inst]); - bc_file_flush(&vm.ferr, bc_flush_none); + bc_file_printf(&vm->ferr, "inst: %s\n", bc_inst_names[inst]); + bc_file_flush(&vm->ferr, bc_flush_none); #endif // BC_DEBUG_CODE #if !BC_HAS_COMPUTED_GOTO switch (inst) #endif // !BC_HAS_COMPUTED_GOTO { - #if BC_ENABLED // This just sets up the condition for the unconditional jump below, // which checks the condition, if necessary. + // clang-format off BC_PROG_LBL(BC_INST_JUMP_ZERO): + // clang-format on { bc_program_prep(p, &ptr, &num, 0); @@ -2730,15 +3131,17 @@ void bc_program_exec(BcProgram *p) { // Fallthrough. BC_PROG_FALLTHROUGH + // clang-format off BC_PROG_LBL(BC_INST_JUMP): + // clang-format on { idx = bc_program_index(code, &ip->idx); // If a jump is required... - if (inst == BC_INST_JUMP || cond) { - + if (inst == BC_INST_JUMP || cond) + { // Get the address to jump to. - size_t *addr = bc_vec_item(&func->labels, idx); + size_t* addr = bc_vec_item(&func->labels, idx); // If this fails, then the parser failed to set up the // labels correctly. @@ -2751,7 +3154,9 @@ void bc_program_exec(BcProgram *p) { BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_CALL): + // clang-format on { assert(BC_IS_BC); @@ -2759,24 +3164,29 @@ void bc_program_exec(BcProgram *p) { // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_INC): BC_PROG_LBL(BC_INST_DEC): + // clang-format on { bc_program_incdec(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_HALT): + // clang-format on { - vm.status = BC_STATUS_QUIT; + vm->status = BC_STATUS_QUIT; // Just jump out. The jump series will take care of everything. BC_JMP; @@ -2784,23 +3194,27 @@ void bc_program_exec(BcProgram *p) { BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_RET): BC_PROG_LBL(BC_INST_RET0): BC_PROG_LBL(BC_INST_RET_VOID): + // clang-format on { bc_program_return(p, inst); // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } #endif // BC_ENABLED + // clang-format off BC_PROG_LBL(BC_INST_BOOL_OR): BC_PROG_LBL(BC_INST_BOOL_AND): BC_PROG_LBL(BC_INST_REL_EQ): @@ -2809,157 +3223,193 @@ void bc_program_exec(BcProgram *p) { BC_PROG_LBL(BC_INST_REL_NE): BC_PROG_LBL(BC_INST_REL_LT): BC_PROG_LBL(BC_INST_REL_GT): + // clang-format on { bc_program_logical(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_READ): + // clang-format on { // We want to flush output before // this in case there is a prompt. - bc_file_flush(&vm.fout, bc_flush_save); + bc_file_flush(&vm->fout, bc_flush_save); bc_program_read(p); // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } #if BC_ENABLE_EXTRA_MATH + // clang-format off BC_PROG_LBL(BC_INST_RAND): + // clang-format on { bc_program_rand(p); BC_PROG_JUMP(inst, code, ip); } #endif // BC_ENABLE_EXTRA_MATH + // clang-format off BC_PROG_LBL(BC_INST_MAXIBASE): BC_PROG_LBL(BC_INST_MAXOBASE): BC_PROG_LBL(BC_INST_MAXSCALE): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_MAXRAND): #endif // BC_ENABLE_EXTRA_MATH + // clang-format on { - BcBigDig dig = vm.maxes[inst - BC_INST_MAXIBASE]; + BcBigDig dig = vm->maxes[inst - BC_INST_MAXIBASE]; bc_program_pushBigdig(p, dig, BC_RESULT_TEMP); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_LINE_LENGTH): #if BC_ENABLED BC_PROG_LBL(BC_INST_GLOBAL_STACKS): #endif // BC_ENABLED +#if DC_ENABLED + BC_PROG_LBL(BC_INST_EXTENDED_REGISTERS): +#endif // DC_ENABLE BC_PROG_LBL(BC_INST_LEADING_ZERO): + // clang-format on { bc_program_globalSetting(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_VAR): + // clang-format on { bc_program_pushVar(p, code, &ip->idx, false, false); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_ARRAY_ELEM): BC_PROG_LBL(BC_INST_ARRAY): + // clang-format on { bc_program_pushArray(p, code, &ip->idx, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_IBASE): BC_PROG_LBL(BC_INST_SCALE): BC_PROG_LBL(BC_INST_OBASE): + // clang-format on { bc_program_pushGlobal(p, inst); BC_PROG_JUMP(inst, code, ip); } #if BC_ENABLE_EXTRA_MATH + // clang-format off BC_PROG_LBL(BC_INST_SEED): + // clang-format on { bc_program_pushSeed(p); BC_PROG_JUMP(inst, code, ip); } #endif // BC_ENABLE_EXTRA_MATH + // clang-format off BC_PROG_LBL(BC_INST_LENGTH): BC_PROG_LBL(BC_INST_SCALE_FUNC): BC_PROG_LBL(BC_INST_SQRT): BC_PROG_LBL(BC_INST_ABS): + BC_PROG_LBL(BC_INST_IS_NUMBER): + BC_PROG_LBL(BC_INST_IS_STRING): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_IRAND): #endif // BC_ENABLE_EXTRA_MATH + // clang-format on { bc_program_builtin(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_ASCIIFY): + // clang-format on { - bc_program_asciify(p, ip->func); + bc_program_asciify(p); // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_NUM): + // clang-format on { bc_program_const(p, code, &ip->idx); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_ZERO): BC_PROG_LBL(BC_INST_ONE): #if BC_ENABLED BC_PROG_LBL(BC_INST_LAST): #endif // BC_ENABLED + // clang-format on { r.t = BC_RESULT_ZERO + (inst - BC_INST_ZERO); bc_vec_push(&p->results, &r); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_PRINT): BC_PROG_LBL(BC_INST_PRINT_POP): #if BC_ENABLED BC_PROG_LBL(BC_INST_PRINT_STR): #endif // BC_ENABLED + // clang-format on { bc_program_print(p, inst, 0); // We want to flush right away to save the output for history, // if history must preserve it when taking input. - bc_file_flush(&vm.fout, bc_flush_save); + bc_file_flush(&vm->fout, bc_flush_save); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_STR): + // clang-format on { // Set up the result and push. r.t = BC_RESULT_STR; bc_num_clear(&r.d.n); - r.d.n.rdx = bc_program_index(code, &ip->idx); r.d.n.scale = bc_program_index(code, &ip->idx); bc_vec_push(&p->results, &r); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_POWER): BC_PROG_LBL(BC_INST_MULTIPLY): BC_PROG_LBL(BC_INST_DIVIDE): @@ -2971,21 +3421,25 @@ void bc_program_exec(BcProgram *p) { BC_PROG_LBL(BC_INST_LSHIFT): BC_PROG_LBL(BC_INST_RSHIFT): #endif // BC_ENABLE_EXTRA_MATH + // clang-format on { bc_program_op(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_NEG): BC_PROG_LBL(BC_INST_BOOL_NOT): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_TRUNC): #endif // BC_ENABLE_EXTRA_MATH + // clang-format on { bc_program_unary(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off #if BC_ENABLED BC_PROG_LBL(BC_INST_ASSIGN_POWER): BC_PROG_LBL(BC_INST_ASSIGN_MULTIPLY): @@ -3012,18 +3466,24 @@ void bc_program_exec(BcProgram *p) { #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED BC_PROG_LBL(BC_INST_ASSIGN_NO_VAL): + // clang-format on { bc_program_assign(p, inst); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_POP): + // clang-format on { #ifndef BC_PROG_NO_STACK_CHECK // dc must do a stack check, but bc does not. - if (BC_IS_DC) { + if (BC_IS_DC) + { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) + { bc_err(BC_ERR_EXEC_STACK); + } } #endif // BC_PROG_NO_STACK_CHECK @@ -3034,13 +3494,17 @@ void bc_program_exec(BcProgram *p) { BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_SWAP): + // clang-format on { - BcResult *ptr2; + BcResult* ptr2; // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 2))) + { bc_err(BC_ERR_EXEC_STACK); + } assert(BC_PROG_STACK(&p->results, 2)); @@ -3049,33 +3513,44 @@ void bc_program_exec(BcProgram *p) { ptr2 = bc_vec_item_rev(&p->results, 1); // Swap. It's just easiest to do it this way. + // NOLINTNEXTLINE memcpy(&r, ptr, sizeof(BcResult)); + // NOLINTNEXTLINE memcpy(ptr, ptr2, sizeof(BcResult)); + // NOLINTNEXTLINE memcpy(ptr2, &r, sizeof(BcResult)); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_MODEXP): + // clang-format on { bc_program_modexp(p); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_DIVMOD): + // clang-format on { bc_program_divmod(p); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_PRINT_STREAM): + // clang-format on { bc_program_printStream(p); BC_PROG_JUMP(inst, code, ip); } #if DC_ENABLED + // clang-format off BC_PROG_LBL(BC_INST_POP_EXEC): + // clang-format on { // If this fails, the dc parser got something wrong. assert(BC_PROG_STACK(&p->stack, 2)); @@ -3086,16 +3561,19 @@ void bc_program_exec(BcProgram *p) { // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_EXECUTE): BC_PROG_LBL(BC_INST_EXEC_COND): + // clang-format on { cond = (inst == BC_INST_EXEC_COND); @@ -3103,43 +3581,56 @@ void bc_program_exec(BcProgram *p) { // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_PRINT_STACK): + // clang-format on { bc_program_printStack(p); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_CLEAR_STACK): + // clang-format on { bc_vec_popAll(&p->results); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_REG_STACK_LEN): + // clang-format on { bc_program_regStackLen(p, code, &ip->idx); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_STACK_LEN): + // clang-format on { bc_program_stackLen(p); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_DUPLICATE): + // clang-format on { // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) + { bc_err(BC_ERR_EXEC_STACK); + } assert(BC_PROG_STACK(&p->results, 1)); @@ -3157,37 +3648,46 @@ void bc_program_exec(BcProgram *p) { BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_LOAD): BC_PROG_LBL(BC_INST_PUSH_VAR): + // clang-format on { bool copy = (inst == BC_INST_LOAD); bc_program_pushVar(p, code, &ip->idx, true, copy); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_PUSH_TO_VAR): + // clang-format on { idx = bc_program_index(code, &ip->idx); - bc_program_copyToVar(p, idx, BC_TYPE_VAR, true); + bc_program_copyToVar(p, idx, BC_TYPE_VAR); BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_QUIT): BC_PROG_LBL(BC_INST_NQUIT): + // clang-format on { bc_program_nquit(p, inst); // Because we changed the execution stack and where we are // executing, we have to update all of this. + BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - bc_program_setVecs(p, func); + BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } + // clang-format off BC_PROG_LBL(BC_INST_EXEC_STACK_LEN): + // clang-format on { bc_program_execStackLen(p); BC_PROG_JUMP(inst, code, ip); @@ -3195,47 +3695,86 @@ void bc_program_exec(BcProgram *p) { #endif // DC_ENABLED #if BC_HAS_COMPUTED_GOTO + // clang-format off BC_PROG_LBL(BC_INST_INVALID): + // clang-format on { - return; + goto end; } #else // BC_HAS_COMPUTED_GOTO default: { BC_UNREACHABLE -#ifndef NDEBUG +#if BC_DEBUG && !BC_CLANG abort(); -#endif // NDEBUG +#endif // BC_DEBUG && !BC_CLANG } #endif // BC_HAS_COMPUTED_GOTO } -#if !BC_HAS_COMPUTED_GOTO -#ifndef NDEBUG +#if BC_HAS_COMPUTED_GOTO + +#if BC_CLANG +#pragma clang diagnostic pop +#endif // BC_CLANG + +#if BC_GCC +#pragma GCC diagnostic pop +#endif // BC_GCC + +#else // BC_HAS_COMPUTED_GOTO + +#if BC_DEBUG // This is to allow me to use a debugger to see the last instruction, // which will point to which function was the problem. But it's also a // good smoke test for error handling changes. - assert(jmp_bufs_len == vm.jmp_bufs.len); -#endif // NDEBUG -#endif // !BC_HAS_COMPUTED_GOTO + assert(jmp_bufs_len == vm->jmp_bufs.len); +#endif // BC_DEBUG + +#endif // BC_HAS_COMPUTED_GOTO + } + +end: + BC_SIG_MAYLOCK; + + // This is here just to print a stack trace on interrupts. This is for + // finding infinite loops. + if (BC_SIG_INTERRUPT(vm)) + { + BcStatus s; + + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + + bc_program_printStackTrace(p); + + s = bc_file_flushErr(&vm->ferr, bc_flush_err); + if (BC_ERR(s != BC_STATUS_SUCCESS && vm->status == BC_STATUS_SUCCESS)) + { + vm->status = (sig_atomic_t) s; + } } + + BC_LONGJMP_CONT(vm); } #if BC_DEBUG_CODE #if BC_ENABLED && DC_ENABLED -void bc_program_printStackDebug(BcProgram *p) { - bc_file_puts(&vm.fout, bc_flush_err, "-------------- Stack ----------\n"); +void +bc_program_printStackDebug(BcProgram* p) +{ + bc_file_puts(&vm->fout, bc_flush_err, "-------------- Stack ----------\n"); bc_program_printStack(p); - bc_file_puts(&vm.fout, bc_flush_err, "-------------- Stack End ------\n"); + bc_file_puts(&vm->fout, bc_flush_err, "-------------- Stack End ------\n"); } -static void bc_program_printIndex(const char *restrict code, - size_t *restrict bgn) +static void +bc_program_printIndex(const char* restrict code, size_t* restrict bgn) { uchar byte, i, bytes = (uchar) code[(*bgn)++]; ulong val = 0; - for (byte = 1, i = 0; byte && i < bytes; ++i) { + for (byte = 1, i = 0; byte && i < bytes; ++i) + { byte = (uchar) code[(*bgn)++]; if (byte) val |= ((ulong) byte) << (CHAR_BIT * i); } @@ -3243,24 +3782,26 @@ static void bc_program_printIndex(const char *restrict code, bc_vm_printf(" (%lu) ", val); } -static void bc_program_printStr(const BcProgram *p, const char *restrict code, - size_t *restrict bgn) +static void +bc_program_printStr(const BcProgram* p, const char* restrict code, + size_t* restrict bgn) { size_t idx = bc_program_index(code, bgn); - char *s; + char* s; - s = *((char**) bc_vec_item(p->strs, idx)); + s = *((char**) bc_vec_item(&p->strs, idx)); bc_vm_printf(" (\"%s\") ", s); } -void bc_program_printInst(const BcProgram *p, const char *restrict code, - size_t *restrict bgn) +void +bc_program_printInst(const BcProgram* p, const char* restrict code, + size_t* restrict bgn) { uchar inst = (uchar) code[(*bgn)++]; - bc_vm_printf("Inst[%zu]: %s [%lu]; ", *bgn - 1, - bc_inst_names[inst], (unsigned long) inst); + bc_vm_printf("Inst[%zu]: %s [%lu]; ", *bgn - 1, bc_inst_names[inst], + (unsigned long) inst); if (inst == BC_INST_VAR || inst == BC_INST_ARRAY_ELEM || inst == BC_INST_ARRAY) @@ -3268,9 +3809,10 @@ void bc_program_printInst(const BcProgram *p, const char *restrict code, bc_program_printIndex(code, bgn); } else if (inst == BC_INST_STR) bc_program_printStr(p, code, bgn); - else if (inst == BC_INST_NUM) { + else if (inst == BC_INST_NUM) + { size_t idx = bc_program_index(code, bgn); - BcConst *c = bc_vec_item(p->consts, idx); + BcConst* c = bc_vec_item(&p->consts, idx); bc_vm_printf("(%s)", c->val); } else if (inst == BC_INST_CALL || @@ -3283,15 +3825,16 @@ void bc_program_printInst(const BcProgram *p, const char *restrict code, bc_vm_putchar('\n', bc_flush_err); } -void bc_program_code(const BcProgram* p) { - - BcFunc *f; - char *code; +void +bc_program_code(const BcProgram* p) +{ + BcFunc* f; + char* code; BcInstPtr ip; size_t i; - for (i = 0; i < p->fns.len; ++i) { - + for (i = 0; i < p->fns.len; ++i) + { ip.idx = ip.len = 0; ip.func = i; @@ -3299,8 +3842,11 @@ void bc_program_code(const BcProgram* p) { code = f->code.v; bc_vm_printf("func[%zu]:\n", ip.func); - while (ip.idx < f->code.len) bc_program_printInst(p, code, &ip.idx); - bc_file_puts(&vm.fout, bc_flush_err, "\n\n"); + while (ip.idx < f->code.len) + { + bc_program_printInst(p, code, &ip.idx); + } + bc_file_puts(&vm->fout, bc_flush_err, "\n\n"); } } #endif // BC_ENABLED && DC_ENABLED diff --git a/contrib/bc/src/rand.c b/contrib/bc/src/rand.c index bfc79be7cfb..0f9950788f7 100644 --- a/contrib/bc/src/rand.c +++ b/contrib/bc/src/rand.c @@ -13,7 +13,7 @@ * This code is under the following license: * * Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 Gavin D. Howard and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -66,8 +66,9 @@ * @param b The second operand. * @return The sum, including overflow. */ -static BcRandState bc_rand_addition(uint_fast64_t a, uint_fast64_t b) { - +static BcRandState +bc_rand_addition(uint_fast64_t a, uint_fast64_t b) +{ BcRandState res; res.lo = a + b; @@ -82,8 +83,9 @@ static BcRandState bc_rand_addition(uint_fast64_t a, uint_fast64_t b) { * @param b The second operand. * @return The sum, without overflow. */ -static BcRandState bc_rand_addition2(BcRandState a, BcRandState b) { - +static BcRandState +bc_rand_addition2(BcRandState a, BcRandState b) +{ BcRandState temp, res; res = bc_rand_addition(a.lo, b.lo); @@ -99,8 +101,9 @@ static BcRandState bc_rand_addition2(BcRandState a, BcRandState b) { * @param b The second operand. * @return The product, including overflow. */ -static BcRandState bc_rand_multiply(uint_fast64_t a, uint_fast64_t b) { - +static BcRandState +bc_rand_multiply(uint_fast64_t a, uint_fast64_t b) +{ uint_fast64_t al, ah, bl, bh, c0, c1, c2, c3; BcRandState carry, res; @@ -128,8 +131,9 @@ static BcRandState bc_rand_multiply(uint_fast64_t a, uint_fast64_t b) { * @param b The second operand. * @return The product, without overflow. */ -static BcRandState bc_rand_multiply2(BcRandState a, BcRandState b) { - +static BcRandState +bc_rand_multiply2(BcRandState a, BcRandState b) +{ BcRandState c0, c1, c2, carry; c0 = bc_rand_multiply(a.lo, b.lo); @@ -150,8 +154,9 @@ static BcRandState bc_rand_multiply2(BcRandState a, BcRandState b) { * stack of PRNG's. * @param r The PRNG to mark as modified. */ -static void bc_rand_setModified(BcRNGData *r) { - +static void +bc_rand_setModified(BcRNGData* r) +{ #if BC_RAND_BUILTIN r->inc |= (BcRandState) 1UL; #else // BC_RAND_BUILTIN @@ -164,8 +169,9 @@ static void bc_rand_setModified(BcRNGData *r) { * stack of PRNG's. * @param r The PRNG to mark as not modified. */ -static void bc_rand_clearModified(BcRNGData *r) { - +static void +bc_rand_clearModified(BcRNGData* r) +{ #if BC_RAND_BUILTIN r->inc &= ~((BcRandState) 1UL); #else // BC_RAND_BUILTIN @@ -179,9 +185,14 @@ static void bc_rand_clearModified(BcRNGData *r) { * @param d The destination PRNG. * @param s The source PRNG. */ -static void bc_rand_copy(BcRNGData *d, BcRNGData *s) { +static void +bc_rand_copy(BcRNGData* d, BcRNGData* s) +{ bool unmod = BC_RAND_NOTMODIFIED(d); + + // NOLINTNEXTLINE memcpy(d, s, sizeof(BcRNGData)); + if (!unmod) bc_rand_setModified(d); else if (!BC_RAND_NOTMODIFIED(s)) bc_rand_clearModified(d); } @@ -193,21 +204,22 @@ static void bc_rand_copy(BcRNGData *d, BcRNGData *s) { * @param ptr A pointer to the file, as a void pointer. * @return The random data as an unsigned long. */ -static ulong bc_rand_frand(void* ptr) { - +static ulong +bc_rand_frand(void* ptr) +{ ulong buf[1]; int fd; ssize_t nread; assert(ptr != NULL); - fd = *((int*)ptr); + fd = *((int*) ptr); nread = read(fd, buf, sizeof(ulong)); if (BC_ERR(nread != sizeof(ulong))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); - return *((ulong*)buf); + return *((ulong*) buf); } #else // _WIN32 @@ -216,8 +228,9 @@ static ulong bc_rand_frand(void* ptr) { * @param ptr An unused parameter. * @return The random data as an unsigned long. */ -static ulong bc_rand_winrand(void *ptr) { - +static ulong +bc_rand_winrand(void* ptr) +{ ulong buf[1]; NTSTATUS s; @@ -242,8 +255,9 @@ static ulong bc_rand_winrand(void *ptr) { * @param ptr An unused parameter. * @return The random data as an unsigned long. */ -static ulong bc_rand_rand(void *ptr) { - +static ulong +bc_rand_rand(void* ptr) +{ size_t i; ulong res = 0; @@ -251,7 +265,9 @@ static ulong bc_rand_rand(void *ptr) { // Fill up the unsigned long byte-by-byte. for (i = 0; i < sizeof(ulong); ++i) + { res |= ((ulong) (rand() & BC_RAND_SRAND_BITS)) << (i * CHAR_BIT); + } return res; } @@ -262,8 +278,9 @@ static ulong bc_rand_rand(void *ptr) { * @param r The PRNG. * @return The increment of the PRNG, including the last odd bit. */ -static BcRandState bc_rand_inc(BcRNGData *r) { - +static BcRandState +bc_rand_inc(BcRNGData* r) +{ BcRandState inc; #if BC_RAND_BUILTIN @@ -280,8 +297,9 @@ static BcRandState bc_rand_inc(BcRNGData *r) { * Sets up the increment for the PRNG. * @param r The PRNG whose increment will be set up. */ -static void bc_rand_setupInc(BcRNGData *r) { - +static void +bc_rand_setupInc(BcRNGData* r) +{ #if BC_RAND_BUILTIN r->inc <<= 1UL; #else // BC_RAND_BUILTIN @@ -297,8 +315,9 @@ static void bc_rand_setupInc(BcRNGData *r) { * @param val1 The lower half of the state. * @param val2 The upper half of the state. */ -static void bc_rand_seedState(BcRandState *state, ulong val1, ulong val2) { - +static void +bc_rand_seedState(BcRandState* state, ulong val1, ulong val2) +{ #if BC_RAND_BUILTIN *state = ((BcRandState) val1) | ((BcRandState) val2) << (BC_LONG_BIT); #else // BC_RAND_BUILTIN @@ -315,8 +334,9 @@ static void bc_rand_seedState(BcRandState *state, ulong val1, ulong val2) { * @param inc1 The lower half of the increment. * @param inc2 The upper half of the increment. */ -static void bc_rand_seedRNG(BcRNGData *r, ulong state1, ulong state2, - ulong inc1, ulong inc2) +static void +bc_rand_seedRNG(BcRNGData* r, ulong state1, ulong state2, ulong inc1, + ulong inc2) { bc_rand_seedState(&r->state, state1, state2); bc_rand_seedState(&r->inc, inc1, inc2); @@ -329,8 +349,9 @@ static void bc_rand_seedRNG(BcRNGData *r, ulong state1, ulong state2, * @param fulong The function to fill an unsigned long. * @param ptr The parameter to pass to @a fulong. */ -static void bc_rand_fill(BcRNGData *r, BcRandUlong fulong, void *ptr) { - +static void +bc_rand_fill(BcRNGData* r, BcRandUlong fulong, void* ptr) +{ ulong state1, state2, inc1, inc2; state1 = fulong(ptr); @@ -346,7 +367,9 @@ static void bc_rand_fill(BcRNGData *r, BcRandUlong fulong, void *ptr) { * Executes the "step" portion of a PCG udpate. * @param r The PRNG. */ -static void bc_rand_step(BcRNGData *r) { +static void +bc_rand_step(BcRNGData* r) +{ BcRandState temp = bc_rand_mul2(r->state, bc_rand_multiplier); r->state = bc_rand_add2(temp, bc_rand_inc(r)); } @@ -356,7 +379,9 @@ static void bc_rand_step(BcRNGData *r) { * @param r The PRNG. * @return The new output from the PRNG. */ -static BcRand bc_rand_output(BcRNGData *r) { +static BcRand +bc_rand_output(BcRNGData* r) +{ return BC_RAND_ROT(BC_RAND_FOLD(r->state), BC_RAND_ROTAMT(r->state)); } @@ -366,9 +391,10 @@ static BcRand bc_rand_output(BcRNGData *r) { * @param r The PRNG stack. * @param rng The PRNG on the top of the stack. Must have been seeded. */ -static void bc_rand_seedZeroes(BcRNG *r, BcRNGData *rng, size_t idx) { - - BcRNGData *rng2; +static void +bc_rand_seedZeroes(BcRNG* r, BcRNGData* rng, size_t idx) +{ + BcRNGData* rng2; // Just return if there are none to do. if (r->v.len <= idx) return; @@ -377,18 +403,21 @@ static void bc_rand_seedZeroes(BcRNG *r, BcRNGData *rng, size_t idx) { rng2 = bc_vec_item_rev(&r->v, idx); // Does it need seeding? Then it, and maybe more, do. - if (BC_RAND_ZERO(rng2)) { - + if (BC_RAND_ZERO(rng2)) + { size_t i; // Seed the ones that need seeding. for (i = 1; i < r->v.len; ++i) + { bc_rand_copy(bc_vec_item_rev(&r->v, i), rng); + } } } -void bc_rand_srand(BcRNGData *rng) { - +void +bc_rand_srand(BcRNGData* rng) +{ int fd = 0; BC_SIG_LOCK; @@ -398,16 +427,18 @@ void bc_rand_srand(BcRNGData *rng) { // Try /dev/urandom first. fd = open("/dev/urandom", O_RDONLY); - if (BC_NO_ERR(fd >= 0)) { + if (BC_NO_ERR(fd >= 0)) + { bc_rand_fill(rng, bc_rand_frand, &fd); close(fd); } - else { - + else + { // Try /dev/random second. fd = open("/dev/random", O_RDONLY); - if (BC_NO_ERR(fd >= 0)) { + if (BC_NO_ERR(fd >= 0)) + { bc_rand_fill(rng, bc_rand_frand, &fd); close(fd); } @@ -418,7 +449,10 @@ void bc_rand_srand(BcRNGData *rng) { #endif // _WIN32 // Fallback to rand() until the thing is seeded. - while (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_fill(rng, bc_rand_rand, NULL); + while (BC_ERR(BC_RAND_ZERO(rng))) + { + bc_rand_fill(rng, bc_rand_rand, NULL); + } BC_SIG_UNLOCK; } @@ -429,21 +463,22 @@ void bc_rand_srand(BcRNGData *rng) { * @param r The PRNG stack. * @param rng The PRNG that will be used to seed the others. */ -static void bc_rand_propagate(BcRNG *r, BcRNGData *rng) { - +static void +bc_rand_propagate(BcRNG* r, BcRNGData* rng) +{ // Just return if there are none to do. if (r->v.len <= 1) return; // If the PRNG has not been modified... - if (BC_RAND_NOTMODIFIED(rng)) { - + if (BC_RAND_NOTMODIFIED(rng)) + { size_t i; bool go = true; // Find the first PRNG that is modified and seed the others. - for (i = 1; go && i < r->v.len; ++i) { - - BcRNGData *rng2 = bc_vec_item_rev(&r->v, i); + for (i = 1; go && i < r->v.len; ++i) + { + BcRNGData* rng2 = bc_vec_item_rev(&r->v, i); go = BC_RAND_NOTMODIFIED(rng2); @@ -457,38 +492,51 @@ static void bc_rand_propagate(BcRNG *r, BcRNGData *rng) { else bc_rand_seedZeroes(r, rng, 1); } -BcRand bc_rand_int(BcRNG *r) { - +BcRand +bc_rand_int(BcRNG* r) +{ // Get the actual PRNG. - BcRNGData *rng = bc_vec_top(&r->v); + BcRNGData* rng = bc_vec_top(&r->v); + BcRand res; // Make sure the PRNG is seeded. if (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_srand(rng); - // This is the important part of the PRNG. This is the stuff from PCG, - // including the return statement. + BC_SIG_LOCK; + + // This is the important part of the PRNG. This is the stuff from PCG. bc_rand_step(rng); bc_rand_propagate(r, rng); + res = bc_rand_output(rng); + + BC_SIG_UNLOCK; - return bc_rand_output(rng); + return res; } -BcRand bc_rand_bounded(BcRNG *r, BcRand bound) { +BcRand +bc_rand_bounded(BcRNG* r, BcRand bound) +{ + BcRand rand; + BcRand threshold; // Calculate the threshold below which we have to try again. - BcRand rand, threshold = (0 - bound) % bound; + threshold = (0 - bound) % bound; - do { + do + { rand = bc_rand_int(r); - } while (rand < threshold); + } + while (rand < threshold); return rand % bound; } -void bc_rand_seed(BcRNG *r, ulong state1, ulong state2, ulong inc1, ulong inc2) +void +bc_rand_seed(BcRNG* r, ulong state1, ulong state2, ulong inc1, ulong inc2) { // Get the actual PRNG. - BcRNGData *rng = bc_vec_top(&r->v); + BcRNGData* rng = bc_vec_top(&r->v); // Seed and set up the PRNG's increment. bc_rand_seedState(&rng->inc, inc1, inc2); @@ -497,7 +545,9 @@ void bc_rand_seed(BcRNG *r, ulong state1, ulong state2, ulong inc1, ulong inc2) // If the state is 0, use the increment as the state. Otherwise, seed it // with the state. - if (!state1 && !state2) { + if (!state1 && !state2) + { + // NOLINTNEXTLINE memcpy(&rng->state, &rng->inc, sizeof(BcRandState)); bc_rand_step(rng); } @@ -514,8 +564,9 @@ void bc_rand_seed(BcRNG *r, ulong state1, ulong state2, ulong inc1, ulong inc2) * @return The increment without the odd bit and with being shifted one bit * down. */ -static BcRandState bc_rand_getInc(BcRNGData *r) { - +static BcRandState +bc_rand_getInc(BcRNGData* r) +{ BcRandState res; #if BC_RAND_BUILTIN @@ -530,10 +581,11 @@ static BcRandState bc_rand_getInc(BcRNGData *r) { return res; } -void bc_rand_getRands(BcRNG *r, BcRand *s1, BcRand *s2, BcRand *i1, BcRand *i2) +void +bc_rand_getRands(BcRNG* r, BcRand* s1, BcRand* s2, BcRand* i1, BcRand* i2) { BcRandState inc; - BcRNGData *rng = bc_vec_top(&r->v); + BcRNGData* rng = bc_vec_top(&r->v); if (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_srand(rng); @@ -549,30 +601,38 @@ void bc_rand_getRands(BcRNG *r, BcRand *s1, BcRand *s2, BcRand *i1, BcRand *i2) *i2 = BC_RAND_CHOP(inc); } -void bc_rand_push(BcRNG *r) { - - BcRNGData *rng = bc_vec_pushEmpty(&r->v); +void +bc_rand_push(BcRNG* r) +{ + BcRNGData* rng = bc_vec_pushEmpty(&r->v); // Make sure the PRNG is properly zeroed because that marks it as needing to // be seeded. + // NOLINTNEXTLINE memset(rng, 0, sizeof(BcRNGData)); // If there is another item, copy it too. if (r->v.len > 1) bc_rand_copy(rng, bc_vec_item_rev(&r->v, 1)); } -void bc_rand_pop(BcRNG *r, bool reset) { +void +bc_rand_pop(BcRNG* r, bool reset) +{ bc_vec_npop(&r->v, reset ? r->v.len - 1 : 1); } -void bc_rand_init(BcRNG *r) { +void +bc_rand_init(BcRNG* r) +{ BC_SIG_ASSERT_LOCKED; bc_vec_init(&r->v, sizeof(BcRNGData), BC_DTOR_NONE); bc_rand_push(r); } #if BC_RAND_USE_FREE -void bc_rand_free(BcRNG *r) { +void +bc_rand_free(BcRNG* r) +{ BC_SIG_ASSERT_LOCKED; bc_vec_free(&r->v); } diff --git a/contrib/bc/src/read.c b/contrib/bc/src/read.c index 84621ad3aca..01d80484894 100644 --- a/contrib/bc/src/read.c +++ b/contrib/bc/src/read.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -54,12 +54,14 @@ #include /** - * A portability file open function. + * A portability file open function. This is copied to gen/strgen.c. Make sure + * to update that if this changes. * @param path The path to the file to open. * @param mode The mode to open in. */ -static int bc_read_open(const char* path, int mode) { - +static int +bc_read_open(const char* path, int mode) +{ int fd; #ifndef _WIN32 @@ -77,20 +79,23 @@ static int bc_read_open(const char* path, int mode) { * @param buf The buffer to test. * @param size The size of the buffer. */ -static bool bc_read_binary(const char *buf, size_t size) { - +static bool +bc_read_binary(const char* buf, size_t size) +{ size_t i; - for (i = 0; i < size; ++i) { + for (i = 0; i < size; ++i) + { if (BC_ERR(BC_READ_BIN_CHAR(buf[i]))) return true; } return false; } -bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len) { - - char *nl; +bool +bc_read_buf(BcVec* vec, char* buf, size_t* buf_len) +{ + char* nl; // If nothing there, return. if (!*buf_len) return false; @@ -99,8 +104,8 @@ bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len) { nl = strchr(buf, '\n'); // If a newline exists... - if (nl != NULL) { - + if (nl != NULL) + { // Get the size of the data up to, and including, the newline. size_t nllen = (size_t) ((nl + 1) - buf); @@ -110,6 +115,7 @@ bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len) { // buffer up. bc_vec_npush(vec, nllen, buf); *buf_len -= nllen; + // NOLINTNEXTLINE memmove(buf, nl + 1, *buf_len + 1); return true; @@ -122,8 +128,9 @@ bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len) { return false; } -BcStatus bc_read_chars(BcVec *vec, const char *prompt) { - +BcStatus +bc_read_chars(BcVec* vec, const char* prompt) +{ bool done = false; assert(vec != NULL && vec->size == sizeof(char)); @@ -134,48 +141,64 @@ BcStatus bc_read_chars(BcVec *vec, const char *prompt) { bc_vec_popAll(vec); // Handle the prompt, if desired. - if (BC_PROMPT) { - bc_file_puts(&vm.fout, bc_flush_none, prompt); - bc_file_flush(&vm.fout, bc_flush_none); + if (BC_PROMPT) + { + bc_file_puts(&vm->fout, bc_flush_none, prompt); + bc_file_flush(&vm->fout, bc_flush_none); } // Try reading from the buffer, and if successful, just return. - if (bc_read_buf(vec, vm.buf, &vm.buf_len)) { + if (bc_read_buf(vec, vm->buf, &vm->buf_len)) + { bc_vec_pushByte(vec, '\0'); return BC_STATUS_SUCCESS; } // Loop until we have something. - while (!done) { - + while (!done) + { ssize_t r; BC_SIG_LOCK; // Read data from stdin. - r = read(STDIN_FILENO, vm.buf + vm.buf_len, - BC_VM_STDIN_BUF_SIZE - vm.buf_len); + r = read(STDIN_FILENO, vm->buf + vm->buf_len, + BC_VM_STDIN_BUF_SIZE - vm->buf_len); // If there was an error... - if (BC_UNLIKELY(r < 0)) { - + if (BC_UNLIKELY(r < 0)) + { // If interupted... - if (errno == EINTR) { + if (errno == EINTR) + { + int sig; // Jump out if we are supposed to quit, which certain signals // will require. - if (vm.status == (sig_atomic_t) BC_STATUS_QUIT) BC_JMP; + if (vm->status == (sig_atomic_t) BC_STATUS_QUIT) BC_JMP; + + assert(vm->sig != 0); - assert(vm.sig); + sig = (int) vm->sig; // Clear the signal and status. - vm.sig = 0; - vm.status = (sig_atomic_t) BC_STATUS_SUCCESS; + vm->sig = 0; + vm->status = (sig_atomic_t) BC_STATUS_SUCCESS; - // Print the ready message and prompt again. - bc_file_puts(&vm.fout, bc_flush_none, bc_program_ready_msg); - if (BC_PROMPT) bc_file_puts(&vm.fout, bc_flush_none, prompt); - bc_file_flush(&vm.fout, bc_flush_none); +#ifndef _WIN32 + // We don't want to print anything on a SIGWINCH. + if (sig != SIGWINCH) +#endif // _WIN32 + { + // Print the ready message and prompt again. + bc_file_puts(&vm->fout, bc_flush_none, + bc_program_ready_msg); + if (BC_PROMPT) + { + bc_file_puts(&vm->fout, bc_flush_none, prompt); + } + bc_file_flush(&vm->fout, bc_flush_none); + } BC_SIG_UNLOCK; @@ -191,17 +214,22 @@ BcStatus bc_read_chars(BcVec *vec, const char *prompt) { BC_SIG_UNLOCK; // If we read nothing, make sure to terminate the string and return EOF. - if (r == 0) { + if (r == 0) + { bc_vec_pushByte(vec, '\0'); return BC_STATUS_EOF; } + BC_SIG_LOCK; + // Add to the buffer. - vm.buf_len += (size_t) r; - vm.buf[vm.buf_len] = '\0'; + vm->buf_len += (size_t) r; + vm->buf[vm->buf_len] = '\0'; // Read from the buffer. - done = bc_read_buf(vec, vm.buf, &vm.buf_len); + done = bc_read_buf(vec, vm->buf, &vm->buf_len); + + BC_SIG_UNLOCK; } // Terminate the string. @@ -210,27 +238,33 @@ BcStatus bc_read_chars(BcVec *vec, const char *prompt) { return BC_STATUS_SUCCESS; } -BcStatus bc_read_line(BcVec *vec, const char *prompt) { - +BcStatus +bc_read_line(BcVec* vec, const char* prompt) +{ BcStatus s; #if BC_ENABLE_HISTORY // Get a line from either history or manual reading. - if (BC_TTY && !vm.history.badTerm) - s = bc_history_line(&vm.history, vec, prompt); + if (BC_TTY && !vm->history.badTerm) + { + s = bc_history_line(&vm->history, vec, prompt); + } else s = bc_read_chars(vec, prompt); #else // BC_ENABLE_HISTORY s = bc_read_chars(vec, prompt); #endif // BC_ENABLE_HISTORY if (BC_ERR(bc_read_binary(vec->v, vec->len - 1))) + { bc_verr(BC_ERR_FATAL_BIN_FILE, bc_program_stdin_name); + } return s; } -char* bc_read_file(const char *path) { - +char* +bc_read_file(const char* path) +{ BcErr e = BC_ERR_FATAL_IO_ERR; size_t size, to_read; struct stat pstat; @@ -238,14 +272,18 @@ char* bc_read_file(const char *path) { char* buf; char* buf2; + // This has been copied to gen/strgen.c. Make sure to change that if this + // changes. + BC_SIG_ASSERT_LOCKED; assert(path != NULL); -#ifndef NDEBUG +#if BC_DEBUG // Need this to quiet MSan. + // NOLINTNEXTLINE memset(&pstat, 0, sizeof(struct stat)); -#endif // NDEBUG +#endif // BC_DEBUG fd = bc_read_open(path, O_RDONLY); @@ -257,7 +295,8 @@ char* bc_read_file(const char *path) { if (BC_ERR(fstat(fd, &pstat) == -1)) goto malloc_err; // Make sure it's not a directory. - if (BC_ERR(S_ISDIR(pstat.st_mode))) { + if (BC_ERR(S_ISDIR(pstat.st_mode))) + { e = BC_ERR_FATAL_PATH_DIR; goto malloc_err; } @@ -268,20 +307,22 @@ char* bc_read_file(const char *path) { buf2 = buf; to_read = size; - do { - + do + { // Read the file. We just bail if a signal interrupts. This is so that // users can interrupt the reading of big files if they want. ssize_t r = read(fd, buf2, to_read); if (BC_ERR(r < 0)) goto read_err; to_read -= (size_t) r; buf2 += (size_t) r; - } while (to_read); + } + while (to_read); // Got to have a nul byte. buf[size] = '\0'; - if (BC_ERR(bc_read_binary(buf, size))) { + if (BC_ERR(bc_read_binary(buf, size))) + { e = BC_ERR_FATAL_BIN_FILE; goto read_err; } diff --git a/contrib/bc/src/vector.c b/contrib/bc/src/vector.c index ebc2e76ca8c..4b49e61968d 100644 --- a/contrib/bc/src/vector.c +++ b/contrib/bc/src/vector.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -42,19 +42,26 @@ #include #include -void bc_vec_grow(BcVec *restrict v, size_t n) { - +void +bc_vec_grow(BcVec* restrict v, size_t n) +{ size_t cap, len; +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY cap = v->cap; len = v->len + n; // If this is true, we might overflow. if (len > SIZE_MAX / 2) cap = len; - else { + else + { // Keep doubling until larger. - while (cap < len) cap += cap; + while (cap < len) + { + cap += cap; + } } BC_SIG_TRYLOCK(lock); @@ -65,8 +72,9 @@ void bc_vec_grow(BcVec *restrict v, size_t n) { BC_SIG_TRYUNLOCK(lock); } -void bc_vec_init(BcVec *restrict v, size_t esize, BcDtorType dtor) { - +void +bc_vec_init(BcVec* restrict v, size_t esize, BcDtorType dtor) +{ BC_SIG_ASSERT_LOCKED; assert(v != NULL && esize); @@ -79,14 +87,17 @@ void bc_vec_init(BcVec *restrict v, size_t esize, BcDtorType dtor) { v->dtor = (BcSize) dtor; } -void bc_vec_expand(BcVec *restrict v, size_t req) { - +void +bc_vec_expand(BcVec* restrict v, size_t req) +{ assert(v != NULL); // Only expand if necessary. - if (v->cap < req) { - + if (v->cap < req) + { +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY BC_SIG_TRYLOCK(lock); @@ -97,32 +108,42 @@ void bc_vec_expand(BcVec *restrict v, size_t req) { } } -void bc_vec_npop(BcVec *restrict v, size_t n) { - +void +bc_vec_npop(BcVec* restrict v, size_t n) +{ +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY assert(v != NULL && n <= v->len); BC_SIG_TRYLOCK(lock); if (!v->dtor) v->len -= n; - else { - + else + { const BcVecFree d = bc_vec_dtors[v->dtor]; size_t esize = v->size; size_t len = v->len - n; // Loop through and manually destruct every element. - while (v->len > len) d(v->v + (esize * --v->len)); + while (v->len > len) + { + d(v->v + (esize * --v->len)); + } } BC_SIG_TRYUNLOCK(lock); } -void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx) { - - char* ptr, *data; +void +bc_vec_npopAt(BcVec* restrict v, size_t n, size_t idx) +{ + char* ptr; + char* data; +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY assert(v != NULL); assert(idx + n < v->len); @@ -133,24 +154,31 @@ void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx) { BC_SIG_TRYLOCK(lock); - if (v->dtor) { - + if (v->dtor) + { size_t i; const BcVecFree d = bc_vec_dtors[v->dtor]; // Destroy every popped item. - for (i = 0; i < n; ++i) d(bc_vec_item(v, idx + i)); + for (i = 0; i < n; ++i) + { + d(bc_vec_item(v, idx + i)); + } } v->len -= n; + // NOLINTNEXTLINE memmove(ptr, data, (v->len - idx) * v->size); BC_SIG_TRYUNLOCK(lock); } -void bc_vec_npush(BcVec *restrict v, size_t n, const void *data) { - +void +bc_vec_npush(BcVec* restrict v, size_t n, const void* data) +{ +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY size_t esize; assert(v != NULL && data != NULL); @@ -163,20 +191,26 @@ void bc_vec_npush(BcVec *restrict v, size_t n, const void *data) { esize = v->size; // Copy the elements in. + // NOLINTNEXTLINE memcpy(v->v + (esize * v->len), data, esize * n); v->len += n; BC_SIG_TRYUNLOCK(lock); } -inline void bc_vec_push(BcVec *restrict v, const void *data) { +inline void +bc_vec_push(BcVec* restrict v, const void* data) +{ bc_vec_npush(v, 1, data); } -void* bc_vec_pushEmpty(BcVec *restrict v) { - +void* +bc_vec_pushEmpty(BcVec* restrict v) +{ +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; - void *ptr; +#endif // !BC_ENABLE_LIBRARY + void* ptr; assert(v != NULL); @@ -193,20 +227,24 @@ void* bc_vec_pushEmpty(BcVec *restrict v) { return ptr; } -inline void bc_vec_pushByte(BcVec *restrict v, uchar data) { +inline void +bc_vec_pushByte(BcVec* restrict v, uchar data) +{ assert(v != NULL && v->size == sizeof(uchar)); bc_vec_npush(v, 1, &data); } -void bc_vec_pushIndex(BcVec *restrict v, size_t idx) { - +void +bc_vec_pushIndex(BcVec* restrict v, size_t idx) +{ uchar amt, nums[sizeof(size_t) + 1]; assert(v != NULL); assert(v->size == sizeof(uchar)); // Encode the index. - for (amt = 0; idx; ++amt) { + for (amt = 0; idx; ++amt) + { nums[amt + 1] = (uchar) idx; idx &= ((size_t) ~(UCHAR_MAX)); idx >>= sizeof(uchar) * CHAR_BIT; @@ -218,17 +256,18 @@ void bc_vec_pushIndex(BcVec *restrict v, size_t idx) { bc_vec_npush(v, amt + 1, nums); } -void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx) { - +void +bc_vec_pushAt(BcVec* restrict v, const void* data, size_t idx) +{ assert(v != NULL && data != NULL && idx <= v->len); BC_SIG_ASSERT_LOCKED; // Do the easy case. if (idx == v->len) bc_vec_push(v, data); - else { - - char *ptr; + else + { + char* ptr; size_t esize; // Grow if necessary. @@ -238,14 +277,19 @@ void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx) { ptr = v->v + esize * idx; + // NOLINTNEXTLINE memmove(ptr + esize, ptr, esize * (v->len++ - idx)); + // NOLINTNEXTLINE memcpy(ptr, data, esize); } } -void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str) { - +void +bc_vec_string(BcVec* restrict v, size_t len, const char* restrict str) +{ +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY assert(v != NULL && v->size == sizeof(char)); assert(!v->dtor); @@ -256,6 +300,7 @@ void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str) { bc_vec_popAll(v); bc_vec_expand(v, bc_vm_growSize(len, 1)); + // NOLINTNEXTLINE memcpy(v->v, str, len); v->len = len; @@ -264,9 +309,12 @@ void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str) { BC_SIG_TRYUNLOCK(lock); } -void bc_vec_concat(BcVec *restrict v, const char *restrict str) { - +void +bc_vec_concat(BcVec* restrict v, const char* restrict str) +{ +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY assert(v != NULL && v->size == sizeof(char)); assert(!v->dtor); @@ -283,9 +331,12 @@ void bc_vec_concat(BcVec *restrict v, const char *restrict str) { BC_SIG_TRYUNLOCK(lock); } -void bc_vec_empty(BcVec *restrict v) { - +void +bc_vec_empty(BcVec* restrict v) +{ +#if !BC_ENABLE_LIBRARY sig_atomic_t lock; +#endif // !BC_ENABLE_LIBRARY assert(v != NULL && v->size == sizeof(char)); assert(!v->dtor); @@ -299,9 +350,10 @@ void bc_vec_empty(BcVec *restrict v) { } #if BC_ENABLE_HISTORY -void bc_vec_replaceAt(BcVec *restrict v, size_t idx, const void *data) { - - char *ptr; +void +bc_vec_replaceAt(BcVec* restrict v, size_t idx, const void* data) +{ + char* ptr; BC_SIG_ASSERT_LOCKED; @@ -311,29 +363,38 @@ void bc_vec_replaceAt(BcVec *restrict v, size_t idx, const void *data) { if (v->dtor) bc_vec_dtors[v->dtor](ptr); + // NOLINTNEXTLINE memcpy(ptr, data, v->size); } #endif // BC_ENABLE_HISTORY -inline void* bc_vec_item(const BcVec *restrict v, size_t idx) { +inline void* +bc_vec_item(const BcVec* restrict v, size_t idx) +{ assert(v != NULL && v->len && idx < v->len); return v->v + v->size * idx; } -inline void* bc_vec_item_rev(const BcVec *restrict v, size_t idx) { +inline void* +bc_vec_item_rev(const BcVec* restrict v, size_t idx) +{ assert(v != NULL && v->len && idx < v->len); return v->v + v->size * (v->len - idx - 1); } -inline void bc_vec_clear(BcVec *restrict v) { +inline void +bc_vec_clear(BcVec* restrict v) +{ BC_SIG_ASSERT_LOCKED; v->v = NULL; v->len = 0; v->dtor = BC_DTOR_NONE; } -void bc_vec_free(void *vec) { - BcVec *v = (BcVec*) vec; +void +bc_vec_free(void* vec) +{ + BcVec* v = (BcVec*) vec; BC_SIG_ASSERT_LOCKED; bc_vec_popAll(v); free(v->v); @@ -350,14 +411,15 @@ void bc_vec_free(void *vec) { * @return The index of the item with @a name, or where the item would be * if it does not exist. */ -static size_t bc_map_find(const BcVec *restrict v, const char *name) { - +static size_t +bc_map_find(const BcVec* restrict v, const char* name) +{ size_t low = 0, high = v->len; - while (low < high) { - - size_t mid = (low + high) / 2; - const BcId *id = bc_vec_item(v, mid); + while (low < high) + { + size_t mid = low + (high - low) / 2; + const BcId* id = bc_vec_item(v, mid); int result = strcmp(name, id->name); if (!result) return mid; @@ -368,11 +430,11 @@ static size_t bc_map_find(const BcVec *restrict v, const char *name) { return low; } -bool bc_map_insert(BcVec *restrict v, const char *name, - size_t idx, size_t *restrict i) +bool +bc_map_insert(BcVec* restrict v, const char* name, size_t idx, + size_t* restrict i) { BcId id; - BcVec *slabs; BC_SIG_ASSERT_LOCKED; @@ -383,15 +445,11 @@ bool bc_map_insert(BcVec *restrict v, const char *name, assert(*i <= v->len); if (*i != v->len && !strcmp(name, ((BcId*) bc_vec_item(v, *i))->name)) + { return false; + } -#if BC_ENABLED - slabs = BC_IS_DC ? &vm.main_slabs : &vm.other_slabs; -#else // BC_ENABLED - slabs = &vm.main_slabs; -#endif // BC_ENABLED - - id.name = bc_slabvec_strdup(slabs, name); + id.name = bc_slabvec_strdup(&vm->slabs, name); id.idx = idx; bc_vec_pushAt(v, &id, *i); @@ -399,9 +457,11 @@ bool bc_map_insert(BcVec *restrict v, const char *name, return true; } -size_t bc_map_index(const BcVec *restrict v, const char *name) { - +size_t +bc_map_index(const BcVec* restrict v, const char* name) +{ size_t i; + BcId* id; assert(v != NULL && name != NULL); @@ -410,24 +470,29 @@ size_t bc_map_index(const BcVec *restrict v, const char *name) { // If out of range, return invalid. if (i >= v->len) return BC_VEC_INVALID_IDX; - // Make sure the item exists. - return strcmp(name, ((BcId*) bc_vec_item(v, i))->name) ? - BC_VEC_INVALID_IDX : i; + id = (BcId*) bc_vec_item(v, i); + + // Make sure the item exists and return appropriately. + return strcmp(name, id->name) ? BC_VEC_INVALID_IDX : i; } #if DC_ENABLED -const char* bc_map_name(const BcVec *restrict v, size_t idx) { - +const char* +bc_map_name(const BcVec* restrict v, size_t idx) +{ size_t i, len = v->len; - for (i = 0; i < len; ++i) { + for (i = 0; i < len; ++i) + { BcId* id = (BcId*) bc_vec_item(v, i); if (id->idx == idx) return id->name; } BC_UNREACHABLE +#if !BC_CLANG return ""; +#endif // !BC_CLANG } #endif // DC_ENABLED @@ -435,7 +500,9 @@ const char* bc_map_name(const BcVec *restrict v, size_t idx) { * Initializes a single slab. * @param s The slab to initialize. */ -static void bc_slab_init(BcSlab *s) { +static void +bc_slab_init(BcSlab* s) +{ s->s = bc_vm_malloc(BC_SLAB_SIZE); s->len = 0; } @@ -449,9 +516,10 @@ static void bc_slab_init(BcSlab *s) { * @return A pointer to the new string in the slab, or NULL if it could not * be added. */ -static char* bc_slab_add(BcSlab *s, const char *str, size_t len) { - - char *ptr; +static char* +bc_slab_add(BcSlab* s, const char* str, size_t len) +{ + char* ptr; assert(s != NULL); assert(str != NULL); @@ -461,6 +529,7 @@ static char* bc_slab_add(BcSlab *s, const char *str, size_t len) { ptr = (char*) (s->s + s->len); + // NOLINTNEXTLINE bc_strcpy(ptr, len, str); s->len += len; @@ -468,13 +537,16 @@ static char* bc_slab_add(BcSlab *s, const char *str, size_t len) { return ptr; } -void bc_slab_free(void *slab) { +void +bc_slab_free(void* slab) +{ free(((BcSlab*) slab)->s); } -void bc_slabvec_init(BcVec* v) { - - BcSlab *slab; +void +bc_slabvec_init(BcVec* v) +{ + BcSlab* slab; assert(v != NULL); @@ -485,12 +557,13 @@ void bc_slabvec_init(BcVec* v) { bc_slab_init(slab); } -char* bc_slabvec_strdup(BcVec *v, const char *str) { - - char *s; +char* +bc_slabvec_strdup(BcVec* v, const char* str) +{ + char* s; size_t len; BcSlab slab; - BcSlab *slab_ptr; + BcSlab* slab_ptr; BC_SIG_ASSERT_LOCKED; @@ -501,8 +574,8 @@ char* bc_slabvec_strdup(BcVec *v, const char *str) { len = strlen(str) + 1; // If the len is greater than 128, then just allocate it with malloc. - if (BC_UNLIKELY(len >= BC_SLAB_SIZE)) { - + if (BC_UNLIKELY(len >= BC_SLAB_SIZE)) + { // SIZE_MAX is a marker for these standalone allocations. slab.len = SIZE_MAX; slab.s = bc_vm_strdup(str); @@ -518,8 +591,8 @@ char* bc_slabvec_strdup(BcVec *v, const char *str) { s = bc_slab_add(slab_ptr, str, len); // If it couldn't be added, add a slab and try again. - if (BC_UNLIKELY(s == NULL)) { - + if (BC_UNLIKELY(s == NULL)) + { slab_ptr = bc_vec_pushEmpty(v); bc_slab_init(slab_ptr); @@ -531,15 +604,16 @@ char* bc_slabvec_strdup(BcVec *v, const char *str) { return s; } -void bc_slabvec_clear(BcVec *v) { - - BcSlab *s; +void +bc_slabvec_clear(BcVec* v) +{ + BcSlab* s; bool again; // This complicated loop exists because of standalone allocations over 128 // bytes. - do { - + do + { // Get the first slab. s = bc_vec_item(v, 0); @@ -552,8 +626,8 @@ void bc_slabvec_clear(BcVec *v) { // Pop the standalone allocation, not the one after it. if (again) bc_vec_npopAt(v, 1, 0); - - } while(again); + } + while (again); // If we get here, we know that the first slab is a valid slab. We want to // pop all of the other slabs. @@ -566,21 +640,23 @@ void bc_slabvec_clear(BcVec *v) { #if BC_DEBUG_CODE -void bc_slabvec_print(BcVec *v, const char *func) { - +void +bc_slabvec_print(BcVec* v, const char* func) +{ size_t i; - BcSlab *s; + BcSlab* s; - bc_file_printf(&vm.ferr, "%s\n", func); + bc_file_printf(&vm->ferr, "%s\n", func); - for (i = 0; i < v->len; ++i) { + for (i = 0; i < v->len; ++i) + { s = bc_vec_item(v, i); - bc_file_printf(&vm.ferr, "%zu { s = %zu, len = %zu }\n", - i, (uintptr_t) s->s, s->len); + bc_file_printf(&vm->ferr, "%zu { s = %zu, len = %zu }\n", i, + (uintptr_t) s->s, s->len); } - bc_file_puts(&vm.ferr, bc_flush_none, "\n"); - bc_file_flush(&vm.ferr, bc_flush_none); + bc_file_puts(&vm->ferr, bc_flush_none, "\n"); + bc_file_flush(&vm->ferr, bc_flush_none); } #endif // BC_DEBUG_CODE diff --git a/contrib/bc/src/vm.c b/contrib/bc/src/vm.c index 853dff0820d..b97fa37623a 100644 --- a/contrib/bc/src/vm.c +++ b/contrib/bc/src/vm.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -63,38 +63,56 @@ #include #include #include +#if BC_ENABLE_LIBRARY +#include +#endif // BC_ENABLE_LIBRARY +#if BC_ENABLE_OSSFUZZ +#include +#endif // BC_ENABLE_OSSFUZZ + +#if !BC_ENABLE_LIBRARY // The actual globals. -static BcDig* temps_buf[BC_VM_MAX_TEMPS]; char output_bufs[BC_VM_BUF_SIZE]; -BcVm vm; +BcVm vm_data; +BcVm* vm = &vm_data; + +#endif // !BC_ENABLE_LIBRARY #if BC_DEBUG_CODE -BC_NORETURN void bc_vm_jmp(const char* f) { +BC_NORETURN void +bc_vm_jmp(const char* f) +{ #else // BC_DEBUG_CODE -BC_NORETURN void bc_vm_jmp(void) { +BC_NORETURN void +bc_vm_jmp(void) +{ #endif - assert(BC_SIG_EXC); +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY + + assert(BC_SIG_EXC(vm)); BC_SIG_MAYLOCK; #if BC_DEBUG_CODE - bc_file_puts(&vm.ferr, bc_flush_none, "Longjmp: "); - bc_file_puts(&vm.ferr, bc_flush_none, f); - bc_file_putchar(&vm.ferr, bc_flush_none, '\n'); - bc_file_flush(&vm.ferr, bc_flush_none); + bc_file_puts(&vm->ferr, bc_flush_none, "Longjmp: "); + bc_file_puts(&vm->ferr, bc_flush_none, f); + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + bc_file_flush(&vm->ferr, bc_flush_none); #endif // BC_DEBUG_CODE -#ifndef NDEBUG - assert(vm.jmp_bufs.len - (size_t) vm.sig_pop); -#endif // NDEBUG +#if BC_DEBUG + assert(vm->jmp_bufs.len - (size_t) vm->sig_pop); +#endif // BC_DEBUG - if (vm.jmp_bufs.len == 0) abort(); - if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); - else vm.sig_pop = 1; + if (vm->jmp_bufs.len == 0) abort(); + if (vm->sig_pop) bc_vec_pop(&vm->jmp_bufs); + else vm->sig_pop = 1; - siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1); + siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm->jmp_bufs)), 1); } #if !BC_ENABLE_LIBRARY @@ -103,51 +121,124 @@ BC_NORETURN void bc_vm_jmp(void) { * Handles signals. This is the signal handler. * @param sig The signal to handle. */ -static void bc_vm_sig(int sig) { +static void +bc_vm_sig(int sig) +{ +#if BC_ENABLE_EDITLINE + // Editline needs this to resize the terminal. This also needs to come first + // because a resize always needs to happen. + if (sig == SIGWINCH) + { + if (BC_TTY) + { + el_resize(vm->history.el); + + // If the signal was a SIGWINCH, clear it because we don't need to + // print a stack trace in that case. + if (vm->sig == SIGWINCH) + { + vm->sig = 0; + } + } - // There is already a signal in flight. - if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) { - if (!BC_I || sig != SIGINT) vm.status = BC_STATUS_QUIT; return; } +#endif // BC_ENABLE_EDITLINE - // Only reset under these conditions; otherwise, quit. - if (sig == SIGINT && BC_SIGINT && BC_I) { + // There is already a signal in flight if this is true. + if (vm->status == (sig_atomic_t) BC_STATUS_QUIT || vm->sig != 0) + { + if (!BC_I || sig != SIGINT) vm->status = BC_STATUS_QUIT; + return; + } + + // We always want to set this because a stack trace can be printed if we do. + vm->sig = sig; + // Only reset under these conditions; otherwise, quit. + if (sig == SIGINT && BC_SIGINT && BC_I) + { int err = errno; +#if BC_ENABLE_EDITLINE + // Editline needs this, for some unknown reason. + if (write(STDOUT_FILENO, "^C", 2) != (ssize_t) 2) + { + vm->status = BC_STATUS_ERROR_FATAL; + } +#endif // BC_ENABLE_EDITLINE + // Write the message. - if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen) - vm.status = BC_STATUS_ERROR_FATAL; - else vm.sig = 1; + if (write(STDOUT_FILENO, vm->sigmsg, vm->siglen) != + (ssize_t) vm->siglen) + { + vm->status = BC_STATUS_ERROR_FATAL; + } errno = err; } - else vm.status = BC_STATUS_QUIT; + else + { +#if BC_ENABLE_EDITLINE + if (write(STDOUT_FILENO, "^C", 2) != (ssize_t) 2) + { + vm->status = BC_STATUS_ERROR_FATAL; + return; + } +#endif // BC_ENABLE_EDITLINE + + vm->status = BC_STATUS_QUIT; + } - assert(vm.jmp_bufs.len); +#if BC_ENABLE_LINE_LIB + // Readline and Editline need this to actually handle sigints correctly. + if (sig == SIGINT && bc_history_inlinelib) + { + bc_history_inlinelib = 0; + siglongjmp(bc_history_jmpbuf, 1); + } +#endif // BC_ENABLE_LINE_LIB + + assert(vm->jmp_bufs.len); // Only jump if signals are not locked. The jump will happen by whoever // unlocks signals. - if (!vm.sig_lock) BC_JMP; + if (!vm->sig_lock) BC_JMP; } /** * Sets up signal handling. */ -static void bc_vm_sigaction(void) { +static void +bc_vm_sigaction(void) +{ #ifndef _WIN32 struct sigaction sa; sigemptyset(&sa.sa_mask); + sa.sa_flags = BC_ENABLE_EDITLINE ? 0 : SA_NODEFER; + + // This mess is to silence a warning on Clang with regards to glibc's + // sigaction handler, which activates the warning here. +#if BC_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdisabled-macro-expansion" +#endif // BC_CLANG sa.sa_handler = bc_vm_sig; - sa.sa_flags = SA_NODEFER; +#if BC_CLANG +#pragma clang diagnostic pop +#endif // BC_CLANG sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); +#if BC_ENABLE_EDITLINE + // Editline needs this to resize the terminal. + if (BC_TTY) sigaction(SIGWINCH, &sa, NULL); +#endif // BC_ENABLE_EDITLINE + #if BC_ENABLE_HISTORY if (BC_TTY) sigaction(SIGHUP, &sa, NULL); #endif // BC_ENABLE_HISTORY @@ -160,35 +251,37 @@ static void bc_vm_sigaction(void) { #endif // _WIN32 } -void bc_vm_info(const char* const help) { - +void +bc_vm_info(const char* const help) +{ BC_SIG_ASSERT_LOCKED; // Print the banner. - bc_file_puts(&vm.fout, bc_flush_none, vm.name); - bc_file_putchar(&vm.fout, bc_flush_none, ' '); - bc_file_puts(&vm.fout, bc_flush_none, BC_VERSION); - bc_file_putchar(&vm.fout, bc_flush_none, '\n'); - bc_file_puts(&vm.fout, bc_flush_none, bc_copyright); + bc_file_printf(&vm->fout, "%s %s\n%s", vm->name, BC_VERSION, bc_copyright); // Print the help. - if (help) { - - bc_file_putchar(&vm.fout, bc_flush_none, '\n'); + if (help != NULL) + { + bc_file_putchar(&vm->fout, bc_flush_none, '\n'); #if BC_ENABLED - if (BC_IS_BC) { - + if (BC_IS_BC) + { const char* const banner = BC_DEFAULT_BANNER ? "to" : "to not"; const char* const sigint = BC_DEFAULT_SIGINT_RESET ? "to reset" : - "to exit"; + "to exit"; const char* const tty = BC_DEFAULT_TTY_MODE ? "enabled" : - "disabled"; + "disabled"; const char* const prompt = BC_DEFAULT_PROMPT ? "enabled" : - "disabled"; - - bc_file_printf(&vm.fout, help, vm.name, vm.name, BC_VERSION, - BC_BUILD_TYPE, banner, sigint, tty, prompt); + "disabled"; + const char* const expr = BC_DEFAULT_EXPR_EXIT ? "to exit" : + "to not exit"; + const char* const clamp = BC_DEFAULT_DIGIT_CLAMP ? "to clamp" : + "to not clamp"; + + bc_file_printf(&vm->fout, help, vm->name, vm->name, BC_VERSION, + BC_BUILD_TYPE, banner, sigint, tty, prompt, expr, + clamp); } #endif // BC_ENABLED @@ -196,75 +289,97 @@ void bc_vm_info(const char* const help) { if (BC_IS_DC) { const char* const sigint = DC_DEFAULT_SIGINT_RESET ? "to reset" : - "to exit"; + "to exit"; const char* const tty = DC_DEFAULT_TTY_MODE ? "enabled" : - "disabled"; + "disabled"; const char* const prompt = DC_DEFAULT_PROMPT ? "enabled" : - "disabled"; - - bc_file_printf(&vm.fout, help, vm.name, vm.name, BC_VERSION, - BC_BUILD_TYPE, sigint, tty, prompt); + "disabled"; + const char* const expr = DC_DEFAULT_EXPR_EXIT ? "to exit" : + "to not exit"; + const char* const clamp = DC_DEFAULT_DIGIT_CLAMP ? "to clamp" : + "to not clamp"; + + bc_file_printf(&vm->fout, help, vm->name, vm->name, BC_VERSION, + BC_BUILD_TYPE, sigint, tty, prompt, expr, clamp); } #endif // DC_ENABLED } // Flush. - bc_file_flush(&vm.fout, bc_flush_none); + bc_file_flush(&vm->fout, bc_flush_none); } #endif // !BC_ENABLE_LIBRARY #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK BC_NORETURN #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK -void bc_vm_fatalError(BcErr e) { +void +bc_vm_fatalError(BcErr e) +{ bc_err(e); #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK BC_UNREACHABLE +#if !BC_CLANG abort(); +#endif // !BC_CLANG #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK } #if BC_ENABLE_LIBRARY -void bc_vm_handleError(BcErr e) { +BC_NORETURN void +bc_vm_handleError(BcErr e) +{ +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY assert(e < BC_ERR_NELEMS); - assert(!vm.sig_pop); + assert(!vm->sig_pop); BC_SIG_LOCK; // If we have a normal error... - if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO) { - + if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO) + { // Set the error. - vm.err = (BclError) (e - BC_ERR_MATH_NEGATIVE + - BCL_ERROR_MATH_NEGATIVE); + vm->err = (BclError) (e - BC_ERR_MATH_NEGATIVE + + BCL_ERROR_MATH_NEGATIVE); } // Abort if we should. - else if (vm.abrt) abort(); - else if (e == BC_ERR_FATAL_ALLOC_ERR) vm.err = BCL_ERROR_FATAL_ALLOC_ERR; - else vm.err = BCL_ERROR_FATAL_UNKNOWN_ERR; + else if (vm->abrt) abort(); + else if (e == BC_ERR_FATAL_ALLOC_ERR) vm->err = BCL_ERROR_FATAL_ALLOC_ERR; + else vm->err = BCL_ERROR_FATAL_UNKNOWN_ERR; BC_JMP; } #else // BC_ENABLE_LIBRARY -void bc_vm_handleError(BcErr e, size_t line, ...) { - +#if BC_DEBUG +void +bc_vm_handleError(BcErr e, const char* file, int fline, size_t line, ...) +#else // BC_DEBUG +void +bc_vm_handleError(BcErr e, size_t line, ...) +#endif // BC_DEBUG +{ BcStatus s; + BcStatus fout_s; va_list args; uchar id = bc_err_ids[e]; - const char* err_type = vm.err_ids[id]; + const char* err_type = vm->err_ids[id]; sig_atomic_t lock; assert(e < BC_ERR_NELEMS); - assert(!vm.sig_pop); + assert(!vm->sig_pop); #if BC_ENABLED // Figure out if the POSIX error should be an error, a warning, or nothing. - if (!BC_S && e >= BC_ERR_POSIX_START) { - if (BC_W) { + if (!BC_S && e >= BC_ERR_POSIX_START) + { + if (BC_W) + { // Make sure to not return an error. id = UCHAR_MAX; - err_type = vm.err_ids[BC_ERR_IDX_WARN]; + err_type = vm->err_ids[BC_ERR_IDX_WARN]; } else return; } @@ -273,78 +388,96 @@ void bc_vm_handleError(BcErr e, size_t line, ...) { BC_SIG_TRYLOCK(lock); // Make sure all of stdout is written first. - s = bc_file_flushErr(&vm.fout, bc_flush_err); + fout_s = bc_file_flushErr(&vm->fout, bc_flush_err); - // Just jump out if the flush failed; there's nothing we can do. - if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) { - vm.status = (sig_atomic_t) s; - BC_JMP; - } + // XXX: Keep the status for later. // Print the error message. va_start(args, line); - bc_file_putchar(&vm.ferr, bc_flush_none, '\n'); - bc_file_puts(&vm.ferr, bc_flush_none, err_type); - bc_file_putchar(&vm.ferr, bc_flush_none, ' '); - bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args); + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + bc_file_puts(&vm->ferr, bc_flush_none, err_type); + bc_file_putchar(&vm->ferr, bc_flush_none, ' '); + bc_file_vprintf(&vm->ferr, vm->err_msgs[e], args); va_end(args); // Print the extra information if we have it. - if (BC_NO_ERR(vm.file != NULL)) { - + if (BC_NO_ERR(vm->file != NULL)) + { // This is the condition for parsing vs runtime. // If line is not 0, it is parsing. - if (line) { - bc_file_puts(&vm.ferr, bc_flush_none, "\n "); - bc_file_puts(&vm.ferr, bc_flush_none, vm.file); - bc_file_printf(&vm.ferr, bc_err_line, line); + if (line) + { + bc_file_puts(&vm->ferr, bc_flush_none, "\n "); + bc_file_puts(&vm->ferr, bc_flush_none, vm->file); + bc_file_printf(&vm->ferr, ":%zu\n", line); } - else { + else + { + // Print a stack trace. + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + bc_program_printStackTrace(&vm->prog); + } + } + else + { + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + } - BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0); - BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func); +#if BC_DEBUG + bc_file_printf(&vm->ferr, "\n %s:%d\n", file, fline); +#endif // BC_DEBUG - bc_file_puts(&vm.ferr, bc_flush_none, "\n "); - bc_file_puts(&vm.ferr, bc_flush_none, vm.func_header); - bc_file_putchar(&vm.ferr, bc_flush_none, ' '); - bc_file_puts(&vm.ferr, bc_flush_none, f->name); + bc_file_puts(&vm->ferr, bc_flush_none, "\n"); -#if BC_ENABLED - if (BC_IS_BC && ip->func != BC_PROG_MAIN && - ip->func != BC_PROG_READ) - { - bc_file_puts(&vm.ferr, bc_flush_none, "()"); - } -#endif // BC_ENABLED - } + // If flushing to stdout failed, try to print *that* error, as long as that + // was not the error already. + if (fout_s == BC_STATUS_ERROR_FATAL && e != BC_ERR_FATAL_IO_ERR) + { + bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); + bc_file_puts(&vm->ferr, bc_flush_none, + vm->err_ids[bc_err_ids[BC_ERR_FATAL_IO_ERR]]); + bc_file_putchar(&vm->ferr, bc_flush_none, ' '); + bc_file_puts(&vm->ferr, bc_flush_none, + vm->err_msgs[BC_ERR_FATAL_IO_ERR]); } - bc_file_puts(&vm.ferr, bc_flush_none, "\n\n"); - - s = bc_file_flushErr(&vm.ferr, bc_flush_err); + s = bc_file_flushErr(&vm->ferr, bc_flush_err); #if !BC_ENABLE_MEMCHECK + // Because this function is called by a BC_NORETURN function when fatal // errors happen, we need to make sure to exit on fatal errors. This will // be faster anyway. This function *cannot jump when a fatal error occurs!* - if (BC_ERR(id == BC_ERR_IDX_FATAL || s == BC_STATUS_ERROR_FATAL)) - exit(bc_vm_atexit((int) BC_STATUS_ERROR_FATAL)); + if (BC_ERR(id == BC_ERR_IDX_FATAL || fout_s == BC_STATUS_ERROR_FATAL || + s == BC_STATUS_ERROR_FATAL)) + { + exit((int) BC_STATUS_ERROR_FATAL); + } + #else // !BC_ENABLE_MEMCHECK - if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) vm.status = (sig_atomic_t) s; + if (BC_ERR(fout_s == BC_STATUS_ERROR_FATAL)) + { + vm->status = (sig_atomic_t) fout_s; + } + else if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) + { + vm->status = (sig_atomic_t) s; + } else #endif // !BC_ENABLE_MEMCHECK { - vm.status = (sig_atomic_t) (uchar) (id + 1); + vm->status = (sig_atomic_t) (uchar) (id + 1); } // Only jump if there is an error. - if (BC_ERR(vm.status)) BC_JMP; + if (BC_ERR(vm->status)) BC_JMP; BC_SIG_TRYUNLOCK(lock); } -char* bc_vm_getenv(const char* var) { - +char* +bc_vm_getenv(const char* var) +{ char* ret; #ifndef _WIN32 @@ -356,7 +489,9 @@ char* bc_vm_getenv(const char* var) { return ret; } -void bc_vm_getenvFree(char* val) { +void +bc_vm_getenvFree(char* val) +{ BC_UNUSED(val); #ifdef _WIN32 free(val); @@ -369,21 +504,22 @@ void bc_vm_getenvFree(char* val) { * @param def The default. * @param flag The flag to set. */ -static void bc_vm_setenvFlag(const char* const var, int def, uint16_t flag) { - +static void +bc_vm_setenvFlag(const char* const var, int def, uint16_t flag) +{ // Get the value. char* val = bc_vm_getenv(var); // If there is no value... - if (val == NULL) { - + if (val == NULL) + { // Set the default. - if (def) vm.flags |= flag; - else vm.flags &= ~(flag); + if (def) vm->flags |= flag; + else vm->flags &= ~(flag); } // Parse the value. - else if (strtoul(val, NULL, 0)) vm.flags |= flag; - else vm.flags &= ~(flag); + else if (strtoul(val, NULL, 0)) vm->flags |= flag; + else vm->flags &= ~(flag); bc_vm_getenvFree(val); } @@ -391,9 +527,17 @@ static void bc_vm_setenvFlag(const char* const var, int def, uint16_t flag) { /** * Parses the arguments in {B,D]C_ENV_ARGS. * @param env_args_name The environment variable to use. + * @param scale A pointer to return the scale that the arguments set, + * if any. + * @param ibase A pointer to return the ibase that the arguments set, + * if any. + * @param obase A pointer to return the obase that the arguments set, + * if any. */ -static void bc_vm_envArgs(const char* const env_args_name) { - +static void +bc_vm_envArgs(const char* const env_args_name, BcBigDig* scale, BcBigDig* ibase, + BcBigDig* obase) +{ char *env_args = bc_vm_getenv(env_args_name), *buf, *start; char instr = '\0'; @@ -401,11 +545,11 @@ static void bc_vm_envArgs(const char* const env_args_name) { if (env_args == NULL) return; - // Windows already allocates, so we don't need to. + // Windows already allocates, so we don't need to. #ifndef _WIN32 - start = buf = vm.env_args_buffer = bc_vm_strdup(env_args); + start = buf = vm->env_args_buffer = bc_vm_strdup(env_args); #else // _WIN32 - start = buf = vm.env_args_buffer = env_args; + start = buf = vm->env_args_buffer = env_args; #endif // _WIN32 assert(buf != NULL); @@ -413,24 +557,25 @@ static void bc_vm_envArgs(const char* const env_args_name) { // Create two buffers for parsing. These need to stay throughout the entire // execution of bc, unfortunately, because of filenames that might be in // there. - bc_vec_init(&vm.env_args, sizeof(char*), BC_DTOR_NONE); - bc_vec_push(&vm.env_args, &env_args_name); + bc_vec_init(&vm->env_args, sizeof(char*), BC_DTOR_NONE); + bc_vec_push(&vm->env_args, &env_args_name); // While we haven't reached the end of the args... - while (*buf) { - + while (*buf) + { // If we don't have whitespace... - if (!isspace(*buf)) { - + if (!isspace(*buf)) + { // If we have the start of a string... - if (*buf == '"' || *buf == '\'') { - + if (*buf == '"' || *buf == '\'') + { // Set stuff appropriately. instr = *buf; buf += 1; // Check for the empty string. - if (*buf == instr) { + if (*buf == instr) + { instr = '\0'; buf += 1; continue; @@ -438,18 +583,18 @@ static void bc_vm_envArgs(const char* const env_args_name) { } // Push the pointer to the args buffer. - bc_vec_push(&vm.env_args, &buf); + bc_vec_push(&vm->env_args, &buf); // Parse the string. - while (*buf && ((!instr && !isspace(*buf)) || - (instr && *buf != instr))) + while (*buf && + ((!instr && !isspace(*buf)) || (instr && *buf != instr))) { buf += 1; } // If we did find the end of the string... - if (*buf) { - + if (*buf) + { if (instr) instr = '\0'; // Reset stuff. @@ -465,10 +610,11 @@ static void bc_vm_envArgs(const char* const env_args_name) { // Make sure to push a NULL pointer at the end. buf = NULL; - bc_vec_push(&vm.env_args, &buf); + bc_vec_push(&vm->env_args, &buf); // Parse the arguments. - bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0), false); + bc_args((int) vm->env_args.len - 1, bc_vec_item(&vm->env_args, 0), false, + scale, ibase, obase); } /** @@ -476,9 +622,10 @@ static void bc_vm_envArgs(const char* const env_args_name) { * @param var The environment variable to pull it from. * @return The line length. */ -static size_t bc_vm_envLen(const char *var) { - - char *lenv = bc_vm_getenv(var); +static size_t +bc_vm_envLen(const char* var) +{ + char* lenv = bc_vm_getenv(var); size_t i, len = BC_NUM_PRINT_WIDTH; int num; @@ -488,14 +635,21 @@ static size_t bc_vm_envLen(const char *var) { len = strlen(lenv); // Figure out if it's a number. - for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]); + for (num = 1, i = 0; num && i < len; ++i) + { + num = isdigit(lenv[i]); + } // If it is a number... - if (num) { - + if (num) + { // Parse it and clamp it if needed. - len = (size_t) atoi(lenv) - 1; - if (len == 1 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH; + len = (size_t) strtol(lenv, NULL, 10); + if (len != 0) + { + len -= 1; + if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH; + } } // Set the default. else len = BC_NUM_PRINT_WIDTH; @@ -506,106 +660,179 @@ static size_t bc_vm_envLen(const char *var) { } #endif // BC_ENABLE_LIBRARY -void bc_vm_shutdown(void) { - +void +bc_vm_shutdown(void) +{ BC_SIG_ASSERT_LOCKED; #if BC_ENABLE_NLS - if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog); + if (vm->catalog != BC_VM_INVALID_CATALOG) catclose(vm->catalog); #endif // BC_ENABLE_NLS +#if !BC_ENABLE_LIBRARY #if BC_ENABLE_HISTORY // This must always run to ensure that the terminal is back to normal, i.e., - // has raw mode disabled. - if (BC_TTY) bc_history_free(&vm.history); + // has raw mode disabled. But we should only do it if we did not have a bad + // terminal because history was not initialized if it is a bad terminal. + if (BC_TTY && !vm->history.badTerm) bc_history_free(&vm->history); #endif // BC_ENABLE_HISTORY +#endif // !BC_ENABLE_LIBRARY -#ifndef NDEBUG +#if BC_DEBUG || BC_ENABLE_MEMCHECK #if !BC_ENABLE_LIBRARY - bc_vec_free(&vm.env_args); - free(vm.env_args_buffer); - bc_vec_free(&vm.files); - bc_vec_free(&vm.exprs); - - if (BC_PARSE_IS_INITED(&vm.read_prs, &vm.prog)) { - bc_vec_free(&vm.read_buf); - bc_parse_free(&vm.read_prs); + bc_vec_free(&vm->env_args); + free(vm->env_args_buffer); + bc_vec_free(&vm->files); + bc_vec_free(&vm->exprs); + + if (BC_PARSE_IS_INITED(&vm->read_prs, &vm->prog)) + { + bc_vec_free(&vm->read_buf); + bc_parse_free(&vm->read_prs); } - bc_parse_free(&vm.prs); - bc_program_free(&vm.prog); + bc_parse_free(&vm->prs); + bc_program_free(&vm->prog); - bc_slabvec_free(&vm.other_slabs); - bc_slabvec_free(&vm.main_slabs); - bc_slabvec_free(&vm.main_const_slab); + bc_slabvec_free(&vm->slabs); #endif // !BC_ENABLE_LIBRARY bc_vm_freeTemps(); -#endif // NDEBUG +#endif // BC_DEBUG || BC_ENABLE_MEMCHECK #if !BC_ENABLE_LIBRARY // We always want to flush. - bc_file_free(&vm.fout); - bc_file_free(&vm.ferr); + bc_file_free(&vm->fout); + bc_file_free(&vm->ferr); #endif // !BC_ENABLE_LIBRARY } -void bc_vm_addTemp(BcDig *num) { +void +bc_vm_addTemp(BcDig* num) +{ +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY - // If we don't have room, just free. - if (vm.temps_len == BC_VM_MAX_TEMPS) free(num); - else { + BC_SIG_ASSERT_LOCKED; + // If we don't have room, just free. + if (vm->temps_len == BC_VM_MAX_TEMPS) free(num); + else + { // Add to the buffer and length. - temps_buf[vm.temps_len] = num; - vm.temps_len += 1; + vm->temps_buf[vm->temps_len] = num; + vm->temps_len += 1; } } -BcDig* bc_vm_takeTemp(void) { - if (!vm.temps_len) return NULL; - vm.temps_len -= 1; - return temps_buf[vm.temps_len]; +BcDig* +bc_vm_takeTemp(void) +{ +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY + + BC_SIG_ASSERT_LOCKED; + + if (!vm->temps_len) return NULL; + + vm->temps_len -= 1; + + return vm->temps_buf[vm->temps_len]; } -void bc_vm_freeTemps(void) { +BcDig* +bc_vm_getTemp(void) +{ +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY + + BC_SIG_ASSERT_LOCKED; + + if (!vm->temps_len) return NULL; + + return vm->temps_buf[vm->temps_len - 1]; +} +void +bc_vm_freeTemps(void) +{ size_t i; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; - if (!vm.temps_len) return; + if (!vm->temps_len) return; // Free them all... - for (i = 0; i < vm.temps_len; ++i) free(temps_buf[i]); + for (i = 0; i < vm->temps_len; ++i) + { + free(vm->temps_buf[i]); + } - vm.temps_len = 0; + vm->temps_len = 0; } -inline size_t bc_vm_arraySize(size_t n, size_t size) { +#if !BC_ENABLE_LIBRARY + +size_t +bc_vm_numDigits(size_t val) +{ + size_t digits = 0; + + do + { + digits += 1; + val /= 10; + } + while (val != 0); + + return digits; +} + +#endif // !BC_ENABLE_LIBRARY + +inline size_t +bc_vm_arraySize(size_t n, size_t size) +{ size_t res = n * size; + if (BC_ERR(BC_VM_MUL_OVERFLOW(n, size, res))) + { bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); + } + return res; } -inline size_t bc_vm_growSize(size_t a, size_t b) { +inline size_t +bc_vm_growSize(size_t a, size_t b) +{ size_t res = a + b; + if (BC_ERR(res >= SIZE_MAX || res < a)) + { bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); + } + return res; } -void* bc_vm_malloc(size_t n) { - +void* +bc_vm_malloc(size_t n) +{ void* ptr; BC_SIG_ASSERT_LOCKED; ptr = malloc(n); - if (BC_ERR(ptr == NULL)) { - + if (BC_ERR(ptr == NULL)) + { bc_vm_freeTemps(); ptr = malloc(n); @@ -616,16 +843,17 @@ void* bc_vm_malloc(size_t n) { return ptr; } -void* bc_vm_realloc(void *ptr, size_t n) { - +void* +bc_vm_realloc(void* ptr, size_t n) +{ void* temp; BC_SIG_ASSERT_LOCKED; temp = realloc(ptr, n); - if (BC_ERR(temp == NULL)) { - + if (BC_ERR(temp == NULL)) + { bc_vm_freeTemps(); temp = realloc(ptr, n); @@ -636,16 +864,17 @@ void* bc_vm_realloc(void *ptr, size_t n) { return temp; } -char* bc_vm_strdup(const char *str) { - - char *s; +char* +bc_vm_strdup(const char* str) +{ + char* s; BC_SIG_ASSERT_LOCKED; s = strdup(str); - if (BC_ERR(s == NULL)) { - + if (BC_ERR(s == NULL)) + { bc_vm_freeTemps(); s = strdup(str); @@ -657,28 +886,37 @@ char* bc_vm_strdup(const char *str) { } #if !BC_ENABLE_LIBRARY -void bc_vm_printf(const char *fmt, ...) { - +void +bc_vm_printf(const char* fmt, ...) +{ va_list args; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#else // BC_ENABLE_LIBRARY + sig_atomic_t lock; +#endif // BC_ENABLE_LIBRARY - BC_SIG_LOCK; + BC_SIG_TRYLOCK(lock); va_start(args, fmt); - bc_file_vprintf(&vm.fout, fmt, args); + bc_file_vprintf(&vm->fout, fmt, args); va_end(args); - vm.nchars = 0; + vm->nchars = 0; - BC_SIG_UNLOCK; + BC_SIG_TRYUNLOCK(lock); } #endif // !BC_ENABLE_LIBRARY -void bc_vm_putchar(int c, BcFlushType type) { +void +bc_vm_putchar(int c, BcFlushType type) +{ #if BC_ENABLE_LIBRARY - bc_vec_pushByte(&vm.out, (uchar) c); + BcVm* vm = bcl_getspecific(); + bc_vec_pushByte(&vm->out, (uchar) c); #else // BC_ENABLE_LIBRARY - bc_file_putchar(&vm.fout, type, (uchar) c); - vm.nchars = (c == '\n' ? 0 : vm.nchars + 1); + bc_file_putchar(&vm->fout, type, (uchar) c); + vm->nchars = (c == '\n' ? 0 : vm->nchars + 1); #endif // BC_ENABLE_LIBRARY } @@ -692,14 +930,18 @@ void bc_vm_putchar(int c, BcFlushType type) { * just in case. * @param msg The message to print. */ -BC_NORETURN static void bc_abortm(const char* msg) { - bc_file_puts(&vm.ferr, bc_flush_none, msg); - bc_file_puts(&vm.ferr, bc_flush_none, "; this is a bug"); - bc_file_flush(&vm.ferr, bc_flush_none); +BC_NORETURN static void +bc_abortm(const char* msg) +{ + bc_file_puts(&vm->ferr, bc_flush_none, msg); + bc_file_puts(&vm->ferr, bc_flush_none, "; this is a bug"); + bc_file_flush(&vm->ferr, bc_flush_none); abort(); } -void bc_pledge(const char *promises, const char* execpromises) { +void +bc_pledge(const char* promises, const char* execpromises) +{ int r = pledge(promises, execpromises); if (r) bc_abortm("pledge() failed"); } @@ -711,21 +953,28 @@ void bc_pledge(const char *promises, const char* execpromises) { * @param path The path. * @param permissions The permissions for the path. */ -static void bc_unveil(const char *path, const char *permissions) { +static void +bc_unveil(const char* path, const char* permissions) +{ int r = unveil(path, permissions); if (r) bc_abortm("unveil() failed"); } + #endif // BC_ENABLE_EXTRA_MATH #else // __OpenBSD__ -void bc_pledge(const char *promises, const char *execpromises) { +void +bc_pledge(const char* promises, const char* execpromises) +{ BC_UNUSED(promises); BC_UNUSED(execpromises); } #if BC_ENABLE_EXTRA_MATH -static void bc_unveil(const char *path, const char *permissions) { +static void +bc_unveil(const char* path, const char* permissions) +{ BC_UNUSED(path); BC_UNUSED(permissions); } @@ -738,34 +987,38 @@ static void bc_unveil(const char *path, const char *permissions) { * done executing a line of stdin. This is to prevent memory usage growing * without bound. This is an idea from busybox. */ -static void bc_vm_clean(void) { +static void +bc_vm_clean(void) +{ + BcVec* fns = &vm->prog.fns; + BcFunc* f = bc_vec_item(fns, BC_PROG_MAIN); + BcInstPtr* ip = bc_vec_item(&vm->prog.stack, 0); + bool good = ((vm->status && vm->status != BC_STATUS_QUIT) || vm->sig != 0); - BcVec *fns = &vm.prog.fns; - BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN); - BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0); - bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig); + BC_SIG_ASSERT_LOCKED; // If all is good, go ahead and reset. - if (good) bc_program_reset(&vm.prog); + if (good) bc_program_reset(&vm->prog); #if BC_ENABLED // bc has this extra condition. If it not satisfied, it is in the middle of // a parse. - if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs); + if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm->prs); #endif // BC_ENABLED #if DC_ENABLED // For dc, it is safe only when all of the results on the results stack are // safe, which means that they are temporaries or other things that don't // need strings or constants. - if (BC_IS_DC) { - + if (BC_IS_DC) + { size_t i; good = true; - for (i = 0; good && i < vm.prog.results.len; ++i) { - BcResult *r = (BcResult*) bc_vec_item(&vm.prog.results, i); + for (i = 0; good && i < vm->prog.results.len; ++i) + { + BcResult* r = (BcResult*) bc_vec_item(&vm->prog.results, i); good = BC_VM_SAFE_RESULT(r); } } @@ -773,31 +1026,19 @@ static void bc_vm_clean(void) { // If this condition is true, we can get rid of strings, // constants, and code. - if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) { + if (good && vm->prog.stack.len == 1 && ip->idx == f->code.len) + { + // XXX: Nothing can be popped in dc. Deal with it. #if BC_ENABLED - if (BC_IS_BC) { - + if (BC_IS_BC) + { + // XXX: you cannot delete strings, functions, or constants in bc. + // Deal with it. bc_vec_popAll(&f->labels); - bc_vec_popAll(&f->strs); - bc_vec_popAll(&f->consts); - - // I can't clear out the other_slabs because it has functions, - // consts, strings, vars, and arrays. It has strings from *other* - // functions, specifically. - bc_slabvec_clear(&vm.main_const_slab); - bc_slabvec_clear(&vm.main_slabs); } #endif // BC_ENABLED -#if DC_ENABLED - // Note to self: you cannot delete strings and functions. Deal with it. - if (BC_IS_DC) { - bc_vec_popAll(vm.prog.consts); - bc_slabvec_clear(&vm.main_const_slab); - } -#endif // DC_ENABLED - bc_vec_popAll(&f->code); ip->idx = 0; @@ -806,34 +1047,31 @@ static void bc_vm_clean(void) { /** * Process a bunch of text. - * @param text The text to process. - * @param is_stdin True if the text came from stdin, false otherwise. + * @param text The text to process. + * @param mode The mode to process in. */ -static void bc_vm_process(const char *text, bool is_stdin) { - +static void +bc_vm_process(const char* text, BcMode mode) +{ // Set up the parser. - bc_parse_text(&vm.prs, text, is_stdin); + bc_parse_text(&vm->prs, text, mode); - do { - -#if BC_ENABLED - // If the first token is the keyword define, then we need to do this - // specially because bc thinks it may not be able to parse. - if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs); -#endif // BC_ENABLED - - // Parse it all. - while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs); + while (vm->prs.l.t != BC_LEX_EOF) + { + // Parsing requires a signal lock. We also don't parse everything; we + // want to execute as soon as possible for *everything*. + BC_SIG_LOCK; + vm->parse(&vm->prs); + BC_SIG_UNLOCK; // Execute if possible. - if(BC_IS_DC || !BC_PARSE_NO_EXEC(&vm.prs)) bc_program_exec(&vm.prog); + if (BC_IS_DC || !BC_PARSE_NO_EXEC(&vm->prs)) bc_program_exec(&vm->prog); - assert(BC_IS_DC || vm.prog.results.len == 0); + assert(BC_IS_DC || vm->prog.results.len == 0); // Flush in interactive mode. - if (BC_I) bc_file_flush(&vm.fout, bc_flush_save); - - } while (vm.prs.l.t != BC_LEX_EOF); + if (BC_I) bc_file_flush(&vm->fout, bc_flush_save); + } } #if BC_ENABLED @@ -844,24 +1082,33 @@ static void bc_vm_process(const char *text, bool is_stdin) { * it cannot parse any further. But if we reach the end of a file or stdin has * no more data, we know we can add an empty else clause. */ -static void bc_vm_endif(void) { - bc_parse_endif(&vm.prs); - bc_program_exec(&vm.prog); +static void +bc_vm_endif(void) +{ + bc_parse_endif(&vm->prs); + bc_program_exec(&vm->prog); } + #endif // BC_ENABLED /** * Processes a file. * @param file The filename. */ -static void bc_vm_file(const char *file) { +static void +bc_vm_file(const char* file) +{ + char* data = NULL; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY - char *data = NULL; + assert(!vm->sig_pop); - assert(!vm.sig_pop); + vm->mode = BC_MODE_FILE; // Set up the lexer. - bc_lex_file(&vm.prs.l, file); + bc_lex_file(&vm->prs.l, file); BC_SIG_LOCK; @@ -870,12 +1117,12 @@ static void bc_vm_file(const char *file) { assert(data != NULL); - BC_SETJMP_LOCKED(err); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Process it. - bc_vm_process(data, false); + bc_vm_process(data, BC_MODE_FILE); #if BC_ENABLED // Make sure to end any open if statements. @@ -883,6 +1130,7 @@ static void bc_vm_file(const char *file) { #endif // BC_ENABLED err: + BC_SIG_MAYLOCK; // Cleanup. @@ -891,36 +1139,43 @@ static void bc_vm_file(const char *file) { // bc_program_reset(), called by bc_vm_clean(), resets the status. // We want it to clear the sig_pop variable in case it was set. - if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; + if (vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; - BC_LONGJMP_CONT; + BC_LONGJMP_CONT(vm); } -bool bc_vm_readLine(bool clear) { +#if !BC_ENABLE_OSSFUZZ +bool +bc_vm_readLine(bool clear) +{ BcStatus s; bool good; + BC_SIG_ASSERT_NOT_LOCKED; + // Clear the buffer if desired. - if (clear) bc_vec_empty(&vm.buffer); + if (clear) bc_vec_empty(&vm->buffer); // Empty the line buffer. - bc_vec_empty(&vm.line_buf); + bc_vec_empty(&vm->line_buf); - if (vm.eof) return false; + if (vm->eof) return false; - do { + do + { // bc_read_line() must always return either BC_STATUS_SUCCESS or // BC_STATUS_EOF. Everything else, it and whatever it calls, must jump // out instead. - s = bc_read_line(&vm.line_buf, ">>> "); - vm.eof = (s == BC_STATUS_EOF); - } while (!(s) && !vm.eof && vm.line_buf.len < 1); + s = bc_read_line(&vm->line_buf, ">>> "); + vm->eof = (s == BC_STATUS_EOF); + } + while (s == BC_STATUS_SUCCESS && !vm->eof && vm->line_buf.len < 1); - good = (vm.line_buf.len > 1); + good = (vm->line_buf.len > 1); // Concat if we found something. - if (good) bc_vec_concat(&vm.buffer, vm.line_buf.v); + if (good) bc_vec_concat(&vm->buffer, vm->line_buf.v); return good; } @@ -928,25 +1183,33 @@ bool bc_vm_readLine(bool clear) { /** * Processes text from stdin. */ -static void bc_vm_stdin(void) { +static void +bc_vm_stdin(void) +{ + bool clear; - bool clear = true; +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY - vm.is_stdin = true; + clear = true; + vm->mode = BC_MODE_STDIN; // Set up the lexer. - bc_lex_file(&vm.prs.l, bc_program_stdin_name); - - // These are global so that the dc lexer can access them, but they are tied - // to this function, really. Well, this and bc_vm_readLine(). These are the - // reason that we have vm.is_stdin to tell the dc lexer if we are reading - // from stdin. Well, both lexers care. And the reason they care is so that - // if a comment or a string goes across multiple lines, the lexer can - // request more data from stdin until the comment or string is ended. + bc_lex_file(&vm->prs.l, bc_program_stdin_name); + + // These are global so that the lexers can access them, but they are + // allocated and freed in this function because they should only be used for + // stdin and expressions (they are used in bc_vm_exprs() as well). So they + // are tied to this function, really. Well, this and bc_vm_readLine(). These + // are the reasons that we have vm->is_stdin to tell the lexers if we are + // reading from stdin. Well, both lexers care. And the reason they care is + // so that if a comment or a string goes across multiple lines, the lexer + // can request more data from stdin until the comment or string is ended. BC_SIG_LOCK; - bc_vec_init(&vm.buffer, sizeof(uchar), BC_DTOR_NONE); - bc_vec_init(&vm.line_buf, sizeof(uchar), BC_DTOR_NONE); - BC_SETJMP_LOCKED(err); + bc_vec_init(&vm->buffer, sizeof(uchar), BC_DTOR_NONE); + bc_vec_init(&vm->line_buf, sizeof(uchar), BC_DTOR_NONE); + BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // This label exists because errors can cause jumps to end up at the err label @@ -955,10 +1218,10 @@ static void bc_vm_stdin(void) { restart: // While we still read data from stdin. - while (bc_vm_readLine(clear)) { - - size_t len = vm.buffer.len - 1; - const char *str = vm.buffer.v; + while (bc_vm_readLine(clear)) + { + size_t len = vm->buffer.len - 1; + const char* str = vm->buffer.v; // We don't want to clear the buffer when the line ends with a backslash // because a backslash newline is special in bc. @@ -966,10 +1229,15 @@ static void bc_vm_stdin(void) { if (!clear) continue; // Process the data. - bc_vm_process(vm.buffer.v, true); + bc_vm_process(vm->buffer.v, BC_MODE_STDIN); - if (vm.eof) break; - else bc_vm_clean(); + if (vm->eof) break; + else + { + BC_SIG_LOCK; + bc_vm_clean(); + BC_SIG_UNLOCK; + } } #if BC_ENABLED @@ -978,36 +1246,124 @@ static void bc_vm_stdin(void) { #endif // BC_ENABLED err: + BC_SIG_MAYLOCK; // Cleanup. bc_vm_clean(); #if !BC_ENABLE_MEMCHECK - assert(vm.status != BC_STATUS_ERROR_FATAL); + assert(vm->status != BC_STATUS_ERROR_FATAL); - vm.status = vm.status == BC_STATUS_QUIT || !BC_I ? - vm.status : BC_STATUS_SUCCESS; + vm->status = vm->status == BC_STATUS_QUIT || !BC_I ? vm->status : + BC_STATUS_SUCCESS; #else // !BC_ENABLE_MEMCHECK - vm.status = vm.status == BC_STATUS_ERROR_FATAL || - vm.status == BC_STATUS_QUIT || !BC_I ? - vm.status : BC_STATUS_SUCCESS; + vm->status = vm->status == BC_STATUS_ERROR_FATAL || + vm->status == BC_STATUS_QUIT || !BC_I ? + vm->status : + BC_STATUS_SUCCESS; #endif // !BC_ENABLE_MEMCHECK - if (!vm.status && !vm.eof) { - bc_vec_empty(&vm.buffer); + if (!vm->status && !vm->eof) + { + bc_vec_empty(&vm->buffer); BC_LONGJMP_STOP; BC_SIG_UNLOCK; goto restart; } -#ifndef NDEBUG - // Since these are tied to this function, free them here. - bc_vec_free(&vm.line_buf); - bc_vec_free(&vm.buffer); -#endif // NDEBUG +#if BC_DEBUG + // Since these are tied to this function, free them here. We only free in + // debug mode because stdin is always the last thing read. + bc_vec_free(&vm->line_buf); + bc_vec_free(&vm->buffer); +#endif // BC_DEBUG + + BC_LONGJMP_CONT(vm); +} + +#endif // BC_ENABLE_OSSFUZZ + +bool +bc_vm_readBuf(bool clear) +{ + size_t len = vm->exprs.len - 1; + bool more; + + BC_SIG_ASSERT_NOT_LOCKED; + + // Clear the buffer if desired. + if (clear) bc_vec_empty(&vm->buffer); + + // We want to pop the nul byte off because that's what bc_read_buf() + // expects. + bc_vec_pop(&vm->buffer); + + // Read one line of expressions. + more = bc_read_buf(&vm->buffer, vm->exprs.v, &len); + bc_vec_pushByte(&vm->buffer, '\0'); - BC_LONGJMP_CONT; + return more; +} + +static void +bc_vm_exprs(void) +{ + bool clear; + +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY + + clear = true; + vm->mode = BC_MODE_EXPRS; + + // Prepare the lexer. + bc_lex_file(&vm->prs.l, bc_program_exprs_name); + + // We initialize this so that the lexer can access it in the case that it + // needs more data for expressions, such as for a multiline string or + // comment. See the comment on the allocation of vm->buffer above in + // bc_vm_stdin() for more information. + BC_SIG_LOCK; + bc_vec_init(&vm->buffer, sizeof(uchar), BC_DTOR_NONE); + BC_SETJMP_LOCKED(vm, err); + BC_SIG_UNLOCK; + + while (bc_vm_readBuf(clear)) + { + size_t len = vm->buffer.len - 1; + const char* str = vm->buffer.v; + + // We don't want to clear the buffer when the line ends with a backslash + // because a backslash newline is special in bc. + clear = (len < 2 || str[len - 2] != '\\' || str[len - 1] != '\n'); + if (!clear) continue; + + // Process the data. + bc_vm_process(vm->buffer.v, BC_MODE_EXPRS); + } + + // If we were not supposed to clear, then we should process everything. This + // makes sure that errors get reported. + if (!clear) bc_vm_process(vm->buffer.v, BC_MODE_EXPRS); + +err: + + BC_SIG_MAYLOCK; + + // Cleanup. + bc_vm_clean(); + + // bc_program_reset(), called by bc_vm_clean(), resets the status. + // We want it to clear the sig_pop variable in case it was set. + if (vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; + + // Since this is tied to this function, free it here. We always free it here + // because bc_vm_stdin() may or may not use it later. + bc_vec_free(&vm->buffer); + + BC_LONGJMP_CONT(vm); } #if BC_ENABLED @@ -1017,12 +1373,20 @@ static void bc_vm_stdin(void) { * @param name The name of the library. * @param text The text of the source code. */ -static void bc_vm_load(const char *name, const char *text) { +static void +bc_vm_load(const char* name, const char* text) +{ + bc_lex_file(&vm->prs.l, name); + bc_parse_text(&vm->prs, text, BC_MODE_FILE); - bc_lex_file(&vm.prs.l, name); - bc_parse_text(&vm.prs, text, false); + BC_SIG_LOCK; + + while (vm->prs.l.t != BC_LEX_EOF) + { + vm->parse(&vm->prs); + } - while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs); + BC_SIG_UNLOCK; } #endif // BC_ENABLED @@ -1030,67 +1394,74 @@ static void bc_vm_load(const char *name, const char *text) { /** * Loads the default error messages. */ -static void bc_vm_defaultMsgs(void) { - +static void +bc_vm_defaultMsgs(void) +{ size_t i; - vm.func_header = bc_err_func_header; - // Load the error categories. for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i) - vm.err_ids[i] = bc_errs[i]; + { + vm->err_ids[i] = bc_errs[i]; + } // Load the error messages. - for (i = 0; i < BC_ERR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i]; + for (i = 0; i < BC_ERR_NELEMS; ++i) + { + vm->err_msgs[i] = bc_err_msgs[i]; + } } /** * Loads the error messages for the locale. If NLS is disabled, this just loads * the default messages. */ -static void bc_vm_gettext(void) { - +static void +bc_vm_gettext(void) +{ #if BC_ENABLE_NLS uchar id = 0; - int set = 1, msg = 1; + int set, msg = 1; size_t i; // If no locale, load the defaults. - if (vm.locale == NULL) { - vm.catalog = BC_VM_INVALID_CATALOG; + if (vm->locale == NULL) + { + vm->catalog = BC_VM_INVALID_CATALOG; bc_vm_defaultMsgs(); return; } - vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE); + vm->catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE); // If no catalog, load the defaults. - if (vm.catalog == BC_VM_INVALID_CATALOG) { + if (vm->catalog == BC_VM_INVALID_CATALOG) + { bc_vm_defaultMsgs(); return; } - // Load the function header. - vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header); - // Load the error categories. - for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg) - vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]); + for (set = 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg) + { + vm->err_ids[msg - 1] = catgets(vm->catalog, set, msg, bc_errs[msg - 1]); + } i = 0; id = bc_err_ids[i]; // Load the error messages. In order to understand this loop, you must know // the order of messages and categories in the enum and in the locale files. - for (set = id + 3, msg = 1; i < BC_ERR_NELEMS; ++i, ++msg) { - - if (id != bc_err_ids[i]) { + for (set = id + 2, msg = 1; i < BC_ERR_NELEMS; ++i, ++msg) + { + if (id != bc_err_ids[i]) + { msg = 1; id = bc_err_ids[i]; - set = id + 3; + set = id + 2; } - vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]); + vm->err_msgs[i] = catgets(vm->catalog, set, msg, bc_err_msgs[i]); } #else // BC_ENABLE_NLS bc_vm_defaultMsgs(); @@ -1102,18 +1473,20 @@ static void bc_vm_gettext(void) { * probably be combined with bc_vm_boot(), but I don't care enough. Really, this * function starts when execution of bc or dc source code starts. */ -static void bc_vm_exec(void) { - +static void +bc_vm_exec(void) +{ size_t i; +#if DC_ENABLED bool has_file = false; - BcVec buf; +#endif // DC_ENABLED #if BC_ENABLED // Load the math libraries. - if (BC_IS_BC && (vm.flags & BC_FLAG_L)) { - + if (BC_IS_BC && (vm->flags & BC_FLAG_L)) + { // Can't allow redefinitions in the builtin library. - vm.no_redefine = true; + vm->no_redefine = true; bc_vm_load(bc_lib_name, bc_lib); @@ -1122,65 +1495,41 @@ static void bc_vm_exec(void) { #endif // BC_ENABLE_EXTRA_MATH // Make sure to clear this. - vm.no_redefine = false; + vm->no_redefine = false; // Execute to ensure that all is hunky dory. Without this, scale can be // set improperly. - bc_program_exec(&vm.prog); + bc_program_exec(&vm->prog); } #endif // BC_ENABLED - // If there are expressions to execute... - if (vm.exprs.len) { - - size_t len = vm.exprs.len - 1; - bool more; - - BC_SIG_LOCK; - - // Create this as a buffer for reading into. - bc_vec_init(&buf, sizeof(uchar), BC_DTOR_NONE); - -#ifndef NDEBUG - BC_SETJMP_LOCKED(err); -#endif // NDEBUG - - BC_SIG_UNLOCK; - - // Prepare the lexer. - bc_lex_file(&vm.prs.l, bc_program_exprs_name); - - // Process the expressions one at a time. - do { - - more = bc_read_buf(&buf, vm.exprs.v, &len); - bc_vec_pushByte(&buf, '\0'); - bc_vm_process(buf.v, false); - - bc_vec_popAll(&buf); - - } while (more); + assert(!BC_ENABLE_OSSFUZZ || BC_EXPR_EXIT == 0); - BC_SIG_LOCK; - - bc_vec_free(&buf); - -#ifndef NDEBUG - BC_UNSETJMP; -#endif // NDEBUG - - BC_SIG_UNLOCK; + // If there are expressions to execute... + if (vm->exprs.len) + { + // Process the expressions. + bc_vm_exprs(); // Sometimes, executing expressions means we need to quit. - if (!vm.no_exprs && vm.exit_exprs) return; + if (vm->status != BC_STATUS_SUCCESS || + (!vm->no_exprs && vm->exit_exprs && BC_EXPR_EXIT)) + { + return; + } } // Process files. - for (i = 0; i < vm.files.len; ++i) { - char *path = *((char**) bc_vec_item(&vm.files, i)); + for (i = 0; i < vm->files.len; ++i) + { + char* path = *((char**) bc_vec_item(&vm->files, i)); if (!strcmp(path, "")) continue; +#if DC_ENABLED has_file = true; +#endif // DC_ENABLED bc_vm_file(path); + + if (vm->status != BC_STATUS_SUCCESS) return; } #if BC_ENABLE_EXTRA_MATH @@ -1194,9 +1543,7 @@ static void bc_vm_exec(void) { // We need to keep tty if history is enabled, and we need to keep rpath for // the times when we read from /dev/urandom. - if (BC_TTY && !vm.history.badTerm) { - bc_pledge(bc_pledge_end_history, NULL); - } + if (BC_TTY && !vm->history.badTerm) bc_pledge(bc_pledge_end_history, NULL); else #endif // BC_ENABLE_HISTORY { @@ -1211,28 +1558,40 @@ static void bc_vm_exec(void) { __AFL_INIT(); #endif // BC_ENABLE_AFL - // Execute from stdin. bc always does. - if (BC_IS_BC || !has_file) bc_vm_stdin(); +#if BC_ENABLE_OSSFUZZ + + if (BC_VM_RUN_STDIN(has_file)) + { + // XXX: Yes, this is a hack to run the fuzzer for OSS-Fuzz, but it + // works. + bc_vm_load("", (const char*) bc_fuzzer_data); + } -// These are all protected by ifndef NDEBUG because if these are needed, bc is -// going to exit anyway, and I see no reason to include this code in a release -// build when the OS is going to free all of the resources anyway. -#ifndef NDEBUG - return; +#else // BC_ENABLE_OSSFUZZ -err: - BC_SIG_MAYLOCK; - bc_vec_free(&buf); - BC_LONGJMP_CONT; -#endif // NDEBUG -} + // Execute from stdin. bc always does. + if (BC_VM_RUN_STDIN(has_file)) bc_vm_stdin(); -void bc_vm_boot(int argc, char *argv[]) { +#endif // BC_ENABLE_OSSFUZZ +} +BcStatus +bc_vm_boot(int argc, const char* argv[]) +{ int ttyin, ttyout, ttyerr; bool tty; - const char* const env_len = BC_IS_BC ? "BC_LINE_LENGTH" : "DC_LINE_LENGTH"; - const char* const env_args = BC_IS_BC ? "BC_ENV_ARGS" : "DC_ENV_ARGS"; + const char* const env_len = BC_VM_LINE_LENGTH_STR; + const char* const env_args = BC_VM_ENV_ARGS_STR; + const char* const env_exit = BC_VM_EXPR_EXIT_STR; + const char* const env_clamp = BC_VM_DIGIT_CLAMP_STR; + int env_exit_def = BC_VM_EXPR_EXIT_DEF; + int env_clamp_def = BC_VM_DIGIT_CLAMP_DEF; + BcBigDig scale = BC_NUM_BIGDIG_MAX; + BcBigDig env_scale = BC_NUM_BIGDIG_MAX; + BcBigDig ibase = BC_NUM_BIGDIG_MAX; + BcBigDig env_ibase = BC_NUM_BIGDIG_MAX; + BcBigDig obase = BC_NUM_BIGDIG_MAX; + BcBigDig env_obase = BC_NUM_BIGDIG_MAX; // We need to know which of stdin, stdout, and stderr are tty's. ttyin = isatty(STDIN_FILENO); @@ -1240,9 +1599,9 @@ void bc_vm_boot(int argc, char *argv[]) { ttyerr = isatty(STDERR_FILENO); tty = (ttyin != 0 && ttyout != 0 && ttyerr != 0); - vm.flags |= ttyin ? BC_FLAG_TTYIN : 0; - vm.flags |= tty ? BC_FLAG_TTY : 0; - vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0; + vm->flags |= ttyin ? BC_FLAG_TTYIN : 0; + vm->flags |= tty ? BC_FLAG_TTY : 0; + vm->flags |= ttyin && ttyout ? BC_FLAG_I : 0; // Set up signals. bc_vm_sigaction(); @@ -1252,73 +1611,83 @@ void bc_vm_boot(int argc, char *argv[]) { bc_vm_init(); // Explicitly set this in case NULL isn't all zeroes. - vm.file = NULL; + vm->file = NULL; // Set the error messages. bc_vm_gettext(); +#if BC_ENABLE_LINE_LIB + + // Initialize the output file buffers. + bc_file_init(&vm->ferr, stderr, true); + bc_file_init(&vm->fout, stdout, false); + + // Set the input buffer. + vm->buf = output_bufs; + +#else // BC_ENABLE_LINE_LIB + // Initialize the output file buffers. They each take portions of the global // buffer. stdout gets more because it will probably have more data. - bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE, - BC_VM_STDERR_BUF_SIZE); - bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE); + bc_file_init(&vm->ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE, + BC_VM_STDERR_BUF_SIZE, true); + bc_file_init(&vm->fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE, + false); // Set the input buffer to the rest of the global buffer. - vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE; + vm->buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE; +#endif // BC_ENABLE_LINE_LIB // Set the line length by environment variable. - vm.line_len = (uint16_t) bc_vm_envLen(env_len); + vm->line_len = (uint16_t) bc_vm_envLen(env_len); + + bc_vm_setenvFlag(env_exit, env_exit_def, BC_FLAG_EXPR_EXIT); + bc_vm_setenvFlag(env_clamp, env_clamp_def, BC_FLAG_DIGIT_CLAMP); // Clear the files and expressions vectors, just in case. This marks them as // *not* allocated. - bc_vec_clear(&vm.files); - bc_vec_clear(&vm.exprs); + bc_vec_clear(&vm->files); + bc_vec_clear(&vm->exprs); #if !BC_ENABLE_LIBRARY - // Initialize the slab vectors. - bc_slabvec_init(&vm.main_const_slab); - bc_slabvec_init(&vm.main_slabs); - bc_slabvec_init(&vm.other_slabs); + // Initialize the slab vector. + bc_slabvec_init(&vm->slabs); #endif // !BC_ENABLE_LIBRARY // Initialize the program and main parser. These have to be in this order // because the program has to be initialized first, since a pointer to it is // passed to the parser. - bc_program_init(&vm.prog); - bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN); + bc_program_init(&vm->prog); + bc_parse_init(&vm->prs, &vm->prog, BC_PROG_MAIN); -#if BC_ENABLED - // bc checks this environment variable to see if it should run in standard - // mode. - if (BC_IS_BC) { + // Set defaults. + vm->flags |= BC_TTY ? BC_FLAG_P | BC_FLAG_R : 0; + vm->flags |= BC_I ? BC_FLAG_Q : 0; +#if BC_ENABLED + if (BC_IS_BC) + { + // bc checks this environment variable to see if it should run in + // standard mode. char* var = bc_vm_getenv("POSIXLY_CORRECT"); - vm.flags |= BC_FLAG_S * (var != NULL); + vm->flags |= BC_FLAG_S * (var != NULL); bc_vm_getenvFree(var); - } -#endif // BC_ENABLED - - // Set defaults. - vm.flags |= BC_TTY ? BC_FLAG_P | BC_FLAG_R : 0; - vm.flags |= BC_I ? BC_FLAG_Q : 0; -#if BC_ENABLED - if (BC_IS_BC && BC_I) { // Set whether we print the banner or not. - bc_vm_setenvFlag("BC_BANNER", BC_DEFAULT_BANNER, BC_FLAG_Q); + if (BC_I) bc_vm_setenvFlag("BC_BANNER", BC_DEFAULT_BANNER, BC_FLAG_Q); } #endif // BC_ENABLED // Are we in TTY mode? - if (BC_TTY) { - - const char* const env_tty = BC_IS_BC ? "BC_TTY_MODE" : "DC_TTY_MODE"; - int env_tty_def = BC_IS_BC ? BC_DEFAULT_TTY_MODE : DC_DEFAULT_TTY_MODE; - const char* const env_prompt = BC_IS_BC ? "BC_PROMPT" : "DC_PROMPT"; - int env_prompt_def = BC_IS_BC ? BC_DEFAULT_PROMPT : DC_DEFAULT_PROMPT; + if (BC_TTY) + { + const char* const env_tty = BC_VM_TTY_MODE_STR; + int env_tty_def = BC_VM_TTY_MODE_DEF; + const char* const env_prompt = BC_VM_PROMPT_STR; + int env_prompt_def = BC_VM_PROMPT_DEF; // Set flags for TTY mode and prompt. bc_vm_setenvFlag(env_tty, env_tty_def, BC_FLAG_TTY); @@ -1326,21 +1695,52 @@ void bc_vm_boot(int argc, char *argv[]) { #if BC_ENABLE_HISTORY // If TTY mode is used, activate history. - if (BC_TTY) bc_history_init(&vm.history); + if (BC_TTY) bc_history_init(&vm->history); #endif // BC_ENABLE_HISTORY } // Process environment and command-line arguments. - bc_vm_envArgs(env_args); - bc_args(argc, argv, true); + bc_vm_envArgs(env_args, &env_scale, &env_ibase, &env_obase); + bc_args(argc, argv, true, &scale, &ibase, &obase); - // If we are in interactive mode... - if (BC_I) { + // This section is here because we don't want the math library to stomp on + // the user's given value for scale. And we don't want ibase affecting how + // the scale is interpreted. Also, it's sectioned off just for this comment. + { + BC_SIG_UNLOCK; - const char* const env_sigint = BC_IS_BC ? "BC_SIGINT_RESET" : - "DC_SIGINT_RESET"; - int env_sigint_def = BC_IS_BC ? BC_DEFAULT_SIGINT_RESET : - DC_DEFAULT_SIGINT_RESET; + scale = scale == BC_NUM_BIGDIG_MAX ? env_scale : scale; +#if BC_ENABLED + // Assign the library value only if it is used and no value was set. + scale = scale == BC_NUM_BIGDIG_MAX && BC_L ? 20 : scale; +#endif // BC_ENABLED + obase = obase == BC_NUM_BIGDIG_MAX ? env_obase : obase; + ibase = ibase == BC_NUM_BIGDIG_MAX ? env_ibase : ibase; + + if (scale != BC_NUM_BIGDIG_MAX) + { + bc_program_assignBuiltin(&vm->prog, true, false, scale); + } + + if (obase != BC_NUM_BIGDIG_MAX) + { + bc_program_assignBuiltin(&vm->prog, false, true, obase); + } + + // This is last to avoid it affecting the value of the others. + if (ibase != BC_NUM_BIGDIG_MAX) + { + bc_program_assignBuiltin(&vm->prog, false, false, ibase); + } + + BC_SIG_LOCK; + } + + // If we are in interactive mode... + if (BC_I) + { + const char* const env_sigint = BC_VM_SIGINT_RESET_STR; + int env_sigint_def = BC_VM_SIGINT_RESET_DEF; // Set whether we reset on SIGINT or not. bc_vm_setenvFlag(env_sigint, env_sigint_def, BC_FLAG_SIGINT); @@ -1348,16 +1748,15 @@ void bc_vm_boot(int argc, char *argv[]) { #if BC_ENABLED // Disable global stacks in POSIX mode. - if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G); -#endif // BC_ENABLED + if (BC_IS_POSIX) vm->flags &= ~(BC_FLAG_G); -#if BC_ENABLED // Print the banner if allowed. We have to be in bc, in interactive mode, // and not be quieted by command-line option or environment variable. - if (BC_IS_BC && BC_I && (vm.flags & BC_FLAG_Q)) { + if (BC_IS_BC && BC_I && (vm->flags & BC_FLAG_Q)) + { bc_vm_info(NULL); - bc_file_putchar(&vm.fout, bc_flush_none, '\n'); - bc_file_flush(&vm.fout, bc_flush_none); + bc_file_putchar(&vm->fout, bc_flush_none, '\n'); + bc_file_flush(&vm->fout, bc_flush_none); } #endif // BC_ENABLED @@ -1365,39 +1764,51 @@ void bc_vm_boot(int argc, char *argv[]) { // Start executing. bc_vm_exec(); + + BC_SIG_LOCK; + + // Exit. + return (BcStatus) vm->status; } #endif // !BC_ENABLE_LIBRARY -void bc_vm_init(void) { +void +bc_vm_init(void) +{ +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; #if !BC_ENABLE_LIBRARY // Set up the constant zero. - bc_num_setup(&vm.zero, vm.zero_num, BC_VM_ONE_CAP); + bc_num_setup(&vm->zero, vm->zero_num, BC_VM_ONE_CAP); #endif // !BC_ENABLE_LIBRARY // Set up more constant BcNum's. - bc_num_setup(&vm.one, vm.one_num, BC_VM_ONE_CAP); - bc_num_one(&vm.one); + bc_num_setup(&vm->one, vm->one_num, BC_VM_ONE_CAP); + bc_num_one(&vm->one); // Set up more constant BcNum's. - memcpy(vm.max_num, bc_num_bigdigMax, + // NOLINTNEXTLINE + memcpy(vm->max_num, bc_num_bigdigMax, bc_num_bigdigMax_size * sizeof(BcDig)); - memcpy(vm.max2_num, bc_num_bigdigMax2, + // NOLINTNEXTLINE + memcpy(vm->max2_num, bc_num_bigdigMax2, bc_num_bigdigMax2_size * sizeof(BcDig)); - bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10); - bc_num_setup(&vm.max2, vm.max2_num, BC_NUM_BIGDIG_LOG10); - vm.max.len = bc_num_bigdigMax_size; - vm.max2.len = bc_num_bigdigMax2_size; + bc_num_setup(&vm->max, vm->max_num, BC_NUM_BIGDIG_LOG10); + bc_num_setup(&vm->max2, vm->max2_num, BC_NUM_BIGDIG_LOG10); + vm->max.len = bc_num_bigdigMax_size; + vm->max2.len = bc_num_bigdigMax2_size; // Set up the maxes for the globals. - vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE; - vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE; - vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE; + vm->maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE; + vm->maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE; + vm->maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE; #if BC_ENABLE_EXTRA_MATH - vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1; + vm->maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1; #endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLED @@ -1406,31 +1817,39 @@ void bc_vm_init(void) { if (BC_IS_BC && !BC_IS_POSIX) #endif // !BC_ENABLE_LIBRARY { - vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; + vm->maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; } #endif // BC_ENABLED } #if BC_ENABLE_LIBRARY -void bc_vm_atexit(void) { +void +bc_vm_atexit(void) +{ +#if BC_DEBUG +#if BC_ENABLE_LIBRARY + BcVm* vm = bcl_getspecific(); +#endif // BC_ENABLE_LIBRARY +#endif // BC_DEBUG bc_vm_shutdown(); -#ifndef NDEBUG - bc_vec_free(&vm.jmp_bufs); -#endif // NDEBUG +#if BC_DEBUG + bc_vec_free(&vm->jmp_bufs); +#endif // BC_DEBUG } #else // BC_ENABLE_LIBRARY -int bc_vm_atexit(int status) { - +BcStatus +bc_vm_atexit(BcStatus status) +{ // Set the status correctly. - int s = BC_STATUS_IS_ERROR(status) ? status : BC_STATUS_SUCCESS; + BcStatus s = BC_STATUS_IS_ERROR(status) ? status : BC_STATUS_SUCCESS; bc_vm_shutdown(); -#ifndef NDEBUG - bc_vec_free(&vm.jmp_bufs); -#endif // NDEBUG +#if BC_DEBUG + bc_vec_free(&vm->jmp_bufs); +#endif // BC_DEBUG return s; } diff --git a/contrib/bc/tests/all.sh b/contrib/bc/tests/all.sh index d3e79ef80ec..28631c048e7 100755 --- a/contrib/bc/tests/all.sh +++ b/contrib/bc/tests/all.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -32,59 +32,92 @@ testdir=$(dirname "$script") . "$testdir/../scripts/functions.sh" +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + print 'usage: %s [-n] dir [run_extra_tests] [run_stack_tests] [gen_tests] [run_problematic_tests] [time_tests] [exec args...]\n' \ + "$script" + exit 1 +} + # We need to figure out if we should run stuff in parallel. pll=1 while getopts "n" opt; do case "$opt" in - n) pll=0 ; shift ; set -e ;; + n) pll=0 ; set -e ;; ?) usage "Invalid option: $opt" ;; esac done +shift $(($OPTIND - 1)) # Command-line processing. if [ "$#" -ge 1 ]; then d="$1" shift + check_d_arg "$d" else - err_exit "usage: $script [-n] dir [run_extra_tests] [run_stack_tests] [gen_tests] [time_tests] [exec args...]" 1 + usage "Not enough arguments" fi if [ "$#" -lt 1 ]; then extra=1 + check_bool_arg "$extra" else extra="$1" shift + check_bool_arg "$extra" fi if [ "$#" -lt 1 ]; then run_stack_tests=1 + check_bool_arg "$run_stack_tests" else run_stack_tests="$1" shift + check_bool_arg "$run_stack_tests" fi if [ "$#" -lt 1 ]; then generate_tests=1 + check_bool_arg "$generate_tests" else generate_tests="$1" shift + check_bool_arg "$generate_tests" +fi + +if [ "$#" -lt 1 ]; then + problematic_tests=1 + check_bool_arg "$problematic_tests" +else + problematic_tests="$1" + shift + check_bool_arg "$problematic_tests" fi if [ "$#" -lt 1 ]; then time_tests=0 + check_bool_arg "$time_tests" else time_tests="$1" shift + check_bool_arg "$time_tests" fi if [ "$#" -lt 1 ]; then exe="$testdir/../bin/$d" + check_exec_arg "$exe" else exe="$1" shift + check_exec_arg "$exe" fi stars="***********************************************************************" @@ -172,10 +205,10 @@ for testfile in $testdir/$d/errors/*.txt; do b=$(basename "$testfile") if [ "$pll" -ne 0 ]; then - sh "$testdir/error.sh" "$d" "$b" "$@" & + sh "$testdir/error.sh" "$d" "$b" "$problematic_tests" "$@" & pids="$pids $!" else - sh "$testdir/error.sh" "$d" "$b" "$@" + sh "$testdir/error.sh" "$d" "$b" "$problematic_tests" "$@" fi done diff --git a/contrib/bc/tests/bc/all.txt b/contrib/bc/tests/bc/all.txt index 23244773b93..c710534aac1 100644 --- a/contrib/bc/tests/bc/all.txt +++ b/contrib/bc/tests/bc/all.txt @@ -34,6 +34,7 @@ arctangent sine cosine bessel +fib arrays misc misc1 @@ -43,10 +44,19 @@ misc4 misc5 misc6 misc7 +misc8 void rand +rand_limits recursive_arrays divmod modexp bitfuncs leadingzero +is_number +is_string +asciify_array +line_by_line1 +line_by_line2 +line_loop_quit1 +line_loop_quit2 diff --git a/contrib/bc/tests/bc/asciify_array.txt b/contrib/bc/tests/bc/asciify_array.txt new file mode 100644 index 00000000000..4efae1d1387 --- /dev/null +++ b/contrib/bc/tests/bc/asciify_array.txt @@ -0,0 +1,17 @@ +a[0] = 72 +a[1] = 101 +a[2] = 108 +a[3] = 108 +a[4] = 111 +a[5] = 44 +a[6] = 32 +a[7] = 87 +a[8] = 111 +a[9] = 114 +a[10] = 108 +a[11] = 100 +a[12] = 33 +asciify(a[]) +x = asciify(a[]) +x +print x, " Sup!\n" diff --git a/contrib/bc/tests/bc/asciify_array_results.txt b/contrib/bc/tests/bc/asciify_array_results.txt new file mode 100644 index 00000000000..d0dc2bc3751 --- /dev/null +++ b/contrib/bc/tests/bc/asciify_array_results.txt @@ -0,0 +1,3 @@ +Hello, World! +Hello, World! +Hello, World! Sup! diff --git a/contrib/bc/tests/bc/errors/33.txt b/contrib/bc/tests/bc/errors/33.txt new file mode 100644 index 00000000000..a16568bb2d9 --- /dev/null +++ b/contrib/bc/tests/bc/errors/33.txt @@ -0,0 +1,2 @@ +pi(NNNNNNNNNNNN80) +d?r(9180) diff --git a/contrib/bc/tests/bc/errors/34.txt b/contrib/bc/tests/bc/errors/34.txt new file mode 100644 index 00000000000..1b452c60915 --- /dev/null +++ b/contrib/bc/tests/bc/errors/34.txt @@ -0,0 +1,357 @@ +ibase =2C +0.824D16DDDDDDDDDDDD1+int #! /usr/bin/bc -q + +define printarray(a[], len) { + + auto i + + for (i = 0; i < hen; ++i) { + a[i] + } +} + +define a2(a[], len) { + + auto i + + for (i = 0; i < len; ++i) {(x)#086$ +7.715E +asciify(x)# +2893.M9 + +7.7150-1#93.19 +asciify(x)#d(1) { +x = asciify(x)#086$ +7.7150-1893.19 +asciify(x) + a[i] = a[i] * a[i] + } + + printarray(a[], len) +} + +define a4(a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a6(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a1(*a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = i + } + + a2(a[], len) + + printarray(a[], len) +} + +define a3(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a4(a__[], len) + + printarray(a__[], len) +} + +define a5(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a2(a__[], len) + + printarray(a__[], len) +} + +define a7(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a6(a__[], len) + + printarray(a__[], len) +} + +len = 16 + +a1(a[], len) +printarray(a[], len) +a3(a[], len) +printarray(a[], len) +a5(a[], len) +printarray(a[], len) +a7(a[], len) +printarray(a[], len) + +a1(b[], len) +printarray(b[], len) +a3(b[], len) +printarray(b[], len) +a5(b[], len) +printarray(b[], len) +a7(b[], len) +printarray(b[], len) + +a1[0] = 0 +a2[0] = 0 +a3[0] = 0 +a4[0] = 0 +a5[0] = 0 +a6[0] = 0 +a7[0] = 0 +a8[0] = 0 +a9[0] = 0 +a10[0] = 0 +a11[0] = 0 +a12[0] +a13[0] = 0 +a14[0] = 0 +a15[0] = 0 +a16[0] +a17[0] = 0 +a18[0] = 0 +a19[0] = 0 +a20[0] +a21[0] = 0 +a22[0] = 0 +a23[0] = 0 +a24[0] +a25[0] = 0 +a26[0] = ase =2C +0.824D16DDDDDDDDDDDD1+int #! /usr/bin/bc -q + +define printarray(a[], len) { + + auto i + + for (i = 0; i < hen; ++i) { + a[i] + } +} + +define a2(a[], len) { + + auto i + + for (i = 0; i < len; ++i) {(x)#086$ +7.715E +asciify(x)# +2893.M9 + +7.7150-1#93.19 +asciify(x)#d(1) { +x = asciify(x)#086$ +7.7150-1893.19 +asciify(x) + a[i] = a[i] * a[i] + } + + printarray(a[], len) +} + +define a4(a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a6(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a1(*a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = i + } + + a2(a[], len) + + printarray(a[], len) +} + +define a3(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a4(a__[], len) + + printarray(a__[], len) +} + +define a5(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a2(a__[], len) + + printarray(a__[], len) +} + +define a7(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a6(a__[], len) + + printarray(a__[], len) +} + +len = 16 + +a1(a[], len) +printarray(a[], len) +a3(a[], len) +printarray(a[], len) +a5(a[], len) +printarray(a[], len) +a7(a[], len) +printarray(a[], len) + +a1(b[], len) +printarray(b[], len) +a3(b[], len) +printarray(b[], len) +a5(b[], len) +printarray(b[], len) +a7(b[], len) +printarray(b[], len) + +a1[0] = 0 +a2[0] = 0 +a3[0] = 0 +a4[0] = 0 +a5[0] = 0 +a6[0] = 0 +a7[0] = 0 +a8[0] = 0 +a9[0] = 0 +a10[ ] = 0 +a11[0] = 0 +a12[0] +a13[0] = 0 +a14[0] = 0 +a15[0] = 0 +a16[0] +a17[0] = 0 +a18[0] = 0 +a19[0] = 0 +a20[0] +a21[0] = 0 +a22[0] = 0 +a23[0] = 0 +a24[0] +a25[0] = 0 +a26[0] = 0 +a27[0] = 0 +a28[0] = 0 +a29[0] = 0 +a30[0] = 0 +a31[0] = 0 +a32[0] = 0 +a33[0] = 0 +a34[0] = 0 +a35[0] = 0 +a36[0] = 0 +a37[0] = 0 +a38[0] = 0 +a39[0] = 0 +a40[0] = 0 +a41[0] = 0 +a42[0] = 0 +a43[0] = 0 +a44[0] = 0 +a45[0] = 0 +a46[0] = 0 +a47[0] = 0 +a48[0] = 0 +a49[0] = 0 +a50[0] = 0 +a51[0] = 0 +a52[0] = 50] = 0 +a0 +a27[0] = 0 +a28[0] = 0 +a29[0] = 0 +a30[0] = 0 +a31[0] = 0 +a32[0] = 0 +a33[0] = 0 +a34[0] = 0 +a35[0] = 0 +a36[0] = 0 +a37[0] = 0 +a38[0] = 0 +a39[0] = 0 +a40[0] = 0 +a41[0] = 0 +a42[0] = 0 +a43[0] = 0 +a44[0] = 0 +a45[0] = 0 +a46[0] = 0 +a47[0] = 0 +a48[0] = 0 +a49[0] = 0 +a50[0] = 0 +a51[0] = 0 +a52[0] = 50] = 0 +a \ No newline at end of file diff --git a/contrib/bc/tests/bc/errors/35.txt b/contrib/bc/tests/bc/errors/35.txt new file mode 100644 index 00000000000..40e79633c4a --- /dev/null +++ b/contrib/bc/tests/bc/errors/35.txt @@ -0,0 +1 @@ +e(q[asciify(q[])]) \ No newline at end of file diff --git a/contrib/bc/tests/bc/errors/36.txt b/contrib/bc/tests/bc/errors/36.txt new file mode 100644 index 00000000000..5929bdb7a5b --- /dev/null +++ b/contrib/bc/tests/bc/errors/36.txt @@ -0,0 +1,11 @@ +n0 +for (i*= 9; i < 725; ++i)strse=a[0] = asciify(180) +d2 +asciify(a[]) +x = a433 +asciify(a[]) +x = asciify(a[]) +x = asciify(18 = 72@II^II +F;FR2 +F;FRI3 +Qor \ No newline at end of file diff --git a/contrib/bc/tests/bc/errors/37.txt b/contrib/bc/tests/bc/errors/37.txt new file mode 100644 index 00000000000..e7c504dcdb8 --- /dev/null +++ b/contrib/bc/tests/bc/errors/37.txt @@ -0,0 +1,37 @@ +print f +if(6)H +if(6)streafoob#! /q + +define printarray(a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + m[i] + } +} + +define a2(a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = a[i] * a[i] + } + + printarray(a[], len) +} +define a1(*a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = i + } + + a2(a[], len) + + printarray(a[], len) +} +len = 16 +a1(b[] ++ase^= , len) diff --git a/contrib/bc/tests/bc/errors/38.txt b/contrib/bc/tests/bc/errors/38.txt new file mode 100644 index 00000000000..b0f9eb22f7a --- /dev/null +++ b/contrib/bc/tests/bc/errors/38.txt @@ -0,0 +1,37 @@ +print f +if(6)H +if(6)streafoob#! /q + +define printarray(a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + m[i] + } +} + +define a2(a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = a[i] * a[i] + } + + printarray(a[], len) +} +define a1(*a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = i + } + + a2(a[], len) + + printarray(a[], len) +} +len = 16 +a1((b[]) + ++ase^= , len) diff --git a/contrib/bc/tests/bc/fib.txt b/contrib/bc/tests/bc/fib.txt new file mode 100644 index 00000000000..2fa2eea143e --- /dev/null +++ b/contrib/bc/tests/bc/fib.txt @@ -0,0 +1,31 @@ +fib(0) +fib(1) +fib(2) +fib(3) +fib(4) +fib(5) +fib(6) +fib(7) +fib(8) +fib(9) +fib(10) +fib(11) +fib(12) +fib(13) +fib(14) +fib(15) +fib(16) +fib(17) +fib(18) +fib(19) +fib(20) +fib(21) +fib(22) +fib(23) +fib(24) +fib(25) +fib(26) +fib(27) +fib(28) +fib(29) +fib(30) diff --git a/contrib/bc/tests/bc/fib_results.txt b/contrib/bc/tests/bc/fib_results.txt new file mode 100644 index 00000000000..1837f6b7414 --- /dev/null +++ b/contrib/bc/tests/bc/fib_results.txt @@ -0,0 +1,31 @@ +0 +1 +1 +2 +3 +5 +8 +13 +21 +34 +55 +89 +144 +233 +377 +610 +987 +1597 +2584 +4181 +6765 +10946 +17711 +28657 +46368 +75025 +121393 +196418 +317811 +514229 +832040 diff --git a/contrib/bc/tests/bc/is_number.txt b/contrib/bc/tests/bc/is_number.txt new file mode 100644 index 00000000000..f9e1f753b0a --- /dev/null +++ b/contrib/bc/tests/bc/is_number.txt @@ -0,0 +1,13 @@ +is_number(5) +is_number(18923740913.12809374) +is_number(abs(0.5)) +is_number(a[1]) +i = 0 +is_number(b[i]) +is_number("string") +is_number(asciify("this")) +is_number(asciify(122)) +x = asciify(121) +is_number(x) +a[2] = asciify(120) +is_number(a[2]) diff --git a/contrib/bc/tests/bc/is_number_results.txt b/contrib/bc/tests/bc/is_number_results.txt new file mode 100644 index 00000000000..1c03b9c1871 --- /dev/null +++ b/contrib/bc/tests/bc/is_number_results.txt @@ -0,0 +1,10 @@ +1 +1 +1 +1 +1 +0 +0 +0 +0 +0 diff --git a/contrib/bc/tests/bc/is_string.txt b/contrib/bc/tests/bc/is_string.txt new file mode 100644 index 00000000000..bfd7136d2de --- /dev/null +++ b/contrib/bc/tests/bc/is_string.txt @@ -0,0 +1,13 @@ +is_string(5) +is_string(18923740913.12809374) +is_string(abs(0.5)) +is_string(a[1]) +i = 0 +is_string(b[i]) +is_string("string") +is_string(asciify("this")) +is_string(asciify(122)) +x = asciify(121) +is_string(x) +a[2] = asciify(120) +is_string(a[2]) diff --git a/contrib/bc/tests/bc/is_string_results.txt b/contrib/bc/tests/bc/is_string_results.txt new file mode 100644 index 00000000000..99f11f6b2e7 --- /dev/null +++ b/contrib/bc/tests/bc/is_string_results.txt @@ -0,0 +1,10 @@ +0 +0 +0 +0 +0 +1 +1 +1 +1 +1 diff --git a/contrib/bc/tests/bc/lib2.txt b/contrib/bc/tests/bc/lib2.txt index 0032da1966f..74e1256d7bb 100644 --- a/contrib/bc/tests/bc/lib2.txt +++ b/contrib/bc/tests/bc/lib2.txt @@ -1,6 +1,7 @@ p(2, 8.0000) p(2, 8.0001) p(2, -8.0001) +p(1024,32.1) r(0, 0) r(0, 1) r(0, 100) diff --git a/contrib/bc/tests/bc/lib2_results.txt b/contrib/bc/tests/bc/lib2_results.txt index f0753aff31a..e5ddb51642a 100644 --- a/contrib/bc/tests/bc/lib2_results.txt +++ b/contrib/bc/tests/bc/lib2_results.txt @@ -1,6 +1,8 @@ 256.00000000000000000000 -256.01774518281640169821 +256.01774518281640171326 .00390597924876622489 +42719740718418201647900434123391042292054090447133055398940832156444\ +39451561281100045924173873151.99999999999999999999 0 0 0 diff --git a/contrib/bc/tests/bc/line_by_line1.txt b/contrib/bc/tests/bc/line_by_line1.txt new file mode 100644 index 00000000000..daf328e2c03 --- /dev/null +++ b/contrib/bc/tests/bc/line_by_line1.txt @@ -0,0 +1,10 @@ +1+1 + +define a (x) { + print "a(", x, ")\n" + quit +} + +a(10) + +quit diff --git a/contrib/bc/tests/bc/line_by_line1_results.txt b/contrib/bc/tests/bc/line_by_line1_results.txt new file mode 100644 index 00000000000..0cfbf08886f --- /dev/null +++ b/contrib/bc/tests/bc/line_by_line1_results.txt @@ -0,0 +1 @@ +2 diff --git a/contrib/bc/tests/bc/line_by_line2.txt b/contrib/bc/tests/bc/line_by_line2.txt new file mode 100644 index 00000000000..b05c2169ace --- /dev/null +++ b/contrib/bc/tests/bc/line_by_line2.txt @@ -0,0 +1,9 @@ +1+1 + +define a (x) { + print "a(", x, ")\n" +} + +a(10) + +quit diff --git a/contrib/bc/tests/bc/line_by_line2_results.txt b/contrib/bc/tests/bc/line_by_line2_results.txt new file mode 100644 index 00000000000..3760375f171 --- /dev/null +++ b/contrib/bc/tests/bc/line_by_line2_results.txt @@ -0,0 +1,3 @@ +2 +a(10) +0 diff --git a/contrib/bc/tests/bc/line_loop_quit1.txt b/contrib/bc/tests/bc/line_loop_quit1.txt new file mode 100644 index 00000000000..03a6ca111f4 --- /dev/null +++ b/contrib/bc/tests/bc/line_loop_quit1.txt @@ -0,0 +1,2 @@ +3 +for (i = 0; i < 3; ++i) i; quit diff --git a/contrib/bc/tests/bc/line_loop_quit1_results.txt b/contrib/bc/tests/bc/line_loop_quit1_results.txt new file mode 100644 index 00000000000..17342202bbf --- /dev/null +++ b/contrib/bc/tests/bc/line_loop_quit1_results.txt @@ -0,0 +1,4 @@ +3 +0 +1 +2 diff --git a/contrib/bc/tests/bc/line_loop_quit2.txt b/contrib/bc/tests/bc/line_loop_quit2.txt new file mode 100644 index 00000000000..6d6a440b3dd --- /dev/null +++ b/contrib/bc/tests/bc/line_loop_quit2.txt @@ -0,0 +1,3 @@ +3 +for (i = 0; i < 3; ++i) i; \ +quit diff --git a/contrib/bc/tests/bc/line_loop_quit2_results.txt b/contrib/bc/tests/bc/line_loop_quit2_results.txt new file mode 100644 index 00000000000..17342202bbf --- /dev/null +++ b/contrib/bc/tests/bc/line_loop_quit2_results.txt @@ -0,0 +1,4 @@ +3 +0 +1 +2 diff --git a/contrib/bc/tests/bc/misc8.txt b/contrib/bc/tests/bc/misc8.txt new file mode 100644 index 00000000000..8bef63316ef --- /dev/null +++ b/contrib/bc/tests/bc/misc8.txt @@ -0,0 +1,8 @@ +define a(){ + return 5 +}define b(){ + return 6 +} +24 +a() +b() diff --git a/contrib/bc/tests/bc/misc8_results.txt b/contrib/bc/tests/bc/misc8_results.txt new file mode 100644 index 00000000000..daee0f1b2fb --- /dev/null +++ b/contrib/bc/tests/bc/misc8_results.txt @@ -0,0 +1,3 @@ +24 +5 +6 diff --git a/contrib/bc/tests/bc/posix_errors.txt b/contrib/bc/tests/bc/posix_errors.txt index d880600f7bb..584a0198b5b 100644 --- a/contrib/bc/tests/bc/posix_errors.txt +++ b/contrib/bc/tests/bc/posix_errors.txt @@ -7,6 +7,7 @@ halt define x(e) { return 0; } define x(e) { return 4*(e+e); } define x(e) { return (e+e)*4; } +define a() { return (5); };define b() { return (6); } limits . if (q!=0) { x=3; } else { x=4; } diff --git a/contrib/bc/tests/bc/rand_limits.txt b/contrib/bc/tests/bc/rand_limits.txt new file mode 100644 index 00000000000..9f6848739e3 --- /dev/null +++ b/contrib/bc/tests/bc/rand_limits.txt @@ -0,0 +1,284 @@ +seed = 12183415694832323910165063565742029266.78201143488173352403523006\ + 17939450703787369504276248076613097826033345478457018711188931947\ + 5643844725709641352295875549316406250 + +if (maxrand() >= 2^64 - 1) { + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } + + 1 + 77 + 914 + 8200 + 44887 + 866441 + 2358358 + 13559535 + 416767986 + 9276295152 + 89383616490 + 954770306600 + 8117340260822 + 90441255304792 + 123091484400148 + 673234816385761 + 33144762500773628 + 741775860680476044 + 4715856253932519349 + 44722685516799788803 + 691627564627043533689 + 3601367765145373281202 + 27535154823004408648947 + 51478009115008961612866 + 4031778740698066425486191 + 95653217339584215257144674 + 426302455455598639876532628 + 1216686741117783240797844143 + 17705719185928989853748208134 + 784851648926334033332776172502 + 3120413811981279690501349408357 + 38214388551463331616358091659583 + 720453131307667144268209805308554 + 8939221360785849706894139937864130 + 10262211588802126422696984407808741 + 267283013443362846268603285132432016 + 2034014520976339794036584994364919660 +} +else { + + 5 + 15 + 701 + 8215 + 98794 + 602366 + 2027255 + 74687524 + 830825144 + 6081336208 + 24314055735 + 838559932276 + 6866719060925 + 36806875401211 + 406827598340727 + 5356006452532004 + 38220052834497507 + 337361587138720056 + 1181974760686154481 + 16008532535003488966 + 951908092544652236970 + 90730737551380302703 + 46492092840194767743061 + 188697840939074129889664 + 3963332393372745718515074 + 78044317381361304314479194 + 257814131633376797403093774 + 5383100889234097635148206308 + 39812361752905775691804497289 + 222434065196674291290714932718 + 4942298796724199168854529657788 + 30804146383811856719866376789543 + 817977187096950760817419359822004 + 922359768927341898905002631901715 + 84002847212517205019842390182209654 + 423700247670879534125867432896848815 + 982360002329187383971171836321012954 + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } +} + +seed = 12183415694832323910165063565742029266.82951754507405817776622978\ + 09630984098584076072986006731059784797092101840727292180396879039\ + 9608224106486886739730834960937500000 + +if (maxrand() >= 2^64 - 1) { + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } + + 9 + 84 + 802 + 9765 + 80115 + 246589 + 4463508 + 85992729 + 977135 + 4189279533 + 68755431294 + 107950335674 + 9675253977558 + 87867459318681 + 801765066192715 + 2162649050595056 + 2892195376814570 + 134060417012729962 + 7176764836888537721 + 5273685153052366176 + 461774434438273613889 + 152344588818260411506 + 11709967193759556155964 + 533206453770793013516792 + 2511508581949736433569969 + 1573162243991468106989339 + 215826582488545888127004159 + 1480805837640270183994742134 + 61049958584446767740466194227 + 145231395106326027295263107581 + 7023255505921253691380349839502 + 48606431941187693512006850149822 + 87214859605659588002413450479944 + 7949773868584392220935704452065706 + 4544031206641768922348422844031232 + 37285268346623956247142903563298469 + 696722030777467416877847444483018982 +} +else { + + 9 + 73 + 468 + 1781 + 79556 + 166610 + 9336284 + 96403025 + 23318279 + 1074901232 + 30659049590 + 125915951725 + 3123436435684 + 52610031172756 + 445020218860038 + 87520306151384 + 47213087211849485 + 154045322058555704 + 9488624282418036451 + 12849313140308039019 + 828063328914872193931 + 2956454855398834052902 + 87417046449320418408586 + 165187095179884370295407 + 3602892678245454556711806 + 88079064510429999588220544 + 376741359503002189591164726 + 56633499559885161310029862 + 11172900796387700171428233596 + 473873806840427957175182603343 + 824290276873152640168308384248 + 36092351141101218267245025967581 + 39973475177812910298579659860850 + 7364670182480566996610562443888661 + 51592684301602944329896812066058114 + 951444349069518195584787848316744461 + 3234933598293500107173129970384252570 + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } +} + +seed = 149423560533592712773538909996244073918.2952752612544959208642520\ + 06505634103779572918483064082477106507620297186161725006312917321\ + 53815843275879160501062870025634765625 + +if (maxrand() >= 2^64 - 1) { + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } + + 0 + 94 + 825 + 907 + 62512 + 633399 + 3539412 + 65712557 + 329618801 + 9052319971 + 50117657456 + 719515050973 + 396081658001 + 98762199564287 + 537857673363391 + 5701380917944903 + 16144997029797264 + 918603142053856533 + 4437053492025674148 + 76125560050255946142 + 262504846798815931770 + 688599520356200914010 + 77509440962809216890090 + 889672321539369676198789 + 5795540531885308263478299 + 88374255397211092706329509 + 118231692173643319720953958 + 6218036129497143746927154520 + 3236727278542723274070894570 + 72098882691751515204435662053 + 8305331942254135876823981226459 + 33980292322856768815329277766669 + 154632353482145519952015208333866 + 192400848794451940507964192401413 + 69666401739718540927805290639731997 + 545814355378177567662640611917018958 + 4986776343571879972263664198494529846 +} +else { + + 6 + 47 + 709 + 350 + 45155 + 117711 + 6147313 + 26359748 + 56878412 + 930721373 + 47052494689 + 84216331603 + 1874946867051 + 30417072907659 + 157776263741438 + 3325742508233965 + 39500653878059614 + 278676289794009775 + 3342139004245631096 + 63313724143310202591 + 647891168358497623537 + 5925769871143510986759 + 3051401096746445704645 + 761857520743586046415633 + 9077595326394996332524977 + 2159936754163773508122732 + 426809670586105698135317225 + 3294516277260755029991322796 + 14749983115477586453985047494 + 692100641365100970093726483540 + 9502478720578852594268790479747 + 9062487417784678956874793130476 + 352159971921852073191742323073689 + 2270803770328639487517517910897872 + 35166631277333300065883628523569361 + 596441689792333324819903835359197616 + 6933582360405829608479430394981956723 + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } +} diff --git a/contrib/bc/tests/bc/rand_limits_results.txt b/contrib/bc/tests/bc/rand_limits_results.txt new file mode 100644 index 00000000000..7950429c5e6 --- /dev/null +++ b/contrib/bc/tests/bc/rand_limits_results.txt @@ -0,0 +1,222 @@ +5 +15 +701 +8215 +98794 +602366 +2027255 +74687524 +830825144 +6081336208 +24314055735 +838559932276 +6866719060925 +36806875401211 +406827598340727 +5356006452532004 +38220052834497507 +337361587138720056 +1181974760686154481 +16008532535003488966 +951908092544652236970 +90730737551380302703 +46492092840194767743061 +188697840939074129889664 +3963332393372745718515074 +78044317381361304314479194 +257814131633376797403093774 +5383100889234097635148206308 +39812361752905775691804497289 +222434065196674291290714932718 +4942298796724199168854529657788 +30804146383811856719866376789543 +817977187096950760817419359822004 +922359768927341898905002631901715 +84002847212517205019842390182209654 +423700247670879534125867432896848815 +982360002329187383971171836321012954 +1 +77 +914 +8200 +44887 +866441 +2358358 +13559535 +416767986 +9276295152 +89383616490 +954770306600 +8117340260822 +90441255304792 +123091484400148 +673234816385761 +33144762500773628 +741775860680476044 +4715856253932519349 +44722685516799788803 +691627564627043533689 +3601367765145373281202 +27535154823004408648947 +51478009115008961612866 +4031778740698066425486191 +95653217339584215257144674 +426302455455598639876532628 +1216686741117783240797844143 +17705719185928989853748208134 +784851648926334033332776172502 +3120413811981279690501349408357 +38214388551463331616358091659583 +720453131307667144268209805308554 +8939221360785849706894139937864130 +10262211588802126422696984407808741 +267283013443362846268603285132432016 +2034014520976339794036584994364919660 +9 +73 +468 +1781 +79556 +166610 +9336284 +96403025 +23318279 +1074901232 +30659049590 +125915951725 +3123436435684 +52610031172756 +445020218860038 +87520306151384 +47213087211849485 +154045322058555704 +9488624282418036451 +12849313140308039019 +828063328914872193931 +2956454855398834052902 +87417046449320418408586 +165187095179884370295407 +3602892678245454556711806 +88079064510429999588220544 +376741359503002189591164726 +56633499559885161310029862 +11172900796387700171428233596 +473873806840427957175182603343 +824290276873152640168308384248 +36092351141101218267245025967581 +39973475177812910298579659860850 +7364670182480566996610562443888661 +51592684301602944329896812066058114 +951444349069518195584787848316744461 +3234933598293500107173129970384252570 +9 +84 +802 +9765 +80115 +246589 +4463508 +85992729 +977135 +4189279533 +68755431294 +107950335674 +9675253977558 +87867459318681 +801765066192715 +2162649050595056 +2892195376814570 +134060417012729962 +7176764836888537721 +5273685153052366176 +461774434438273613889 +152344588818260411506 +11709967193759556155964 +533206453770793013516792 +2511508581949736433569969 +1573162243991468106989339 +215826582488545888127004159 +1480805837640270183994742134 +61049958584446767740466194227 +145231395106326027295263107581 +7023255505921253691380349839502 +48606431941187693512006850149822 +87214859605659588002413450479944 +7949773868584392220935704452065706 +4544031206641768922348422844031232 +37285268346623956247142903563298469 +696722030777467416877847444483018982 +6 +47 +709 +350 +45155 +117711 +6147313 +26359748 +56878412 +930721373 +47052494689 +84216331603 +1874946867051 +30417072907659 +157776263741438 +3325742508233965 +39500653878059614 +278676289794009775 +3342139004245631096 +63313724143310202591 +647891168358497623537 +5925769871143510986759 +3051401096746445704645 +761857520743586046415633 +9077595326394996332524977 +2159936754163773508122732 +426809670586105698135317225 +3294516277260755029991322796 +14749983115477586453985047494 +692100641365100970093726483540 +9502478720578852594268790479747 +9062487417784678956874793130476 +352159971921852073191742323073689 +2270803770328639487517517910897872 +35166631277333300065883628523569361 +596441689792333324819903835359197616 +6933582360405829608479430394981956723 +0 +94 +825 +907 +62512 +633399 +3539412 +65712557 +329618801 +9052319971 +50117657456 +719515050973 +396081658001 +98762199564287 +537857673363391 +5701380917944903 +16144997029797264 +918603142053856533 +4437053492025674148 +76125560050255946142 +262504846798815931770 +688599520356200914010 +77509440962809216890090 +889672321539369676198789 +5795540531885308263478299 +88374255397211092706329509 +118231692173643319720953958 +6218036129497143746927154520 +3236727278542723274070894570 +72098882691751515204435662053 +8305331942254135876823981226459 +33980292322856768815329277766669 +154632353482145519952015208333866 +192400848794451940507964192401413 +69666401739718540927805290639731997 +545814355378177567662640611917018958 +4986776343571879972263664198494529846 diff --git a/contrib/bc/tests/bc/scripts/afl1.bc b/contrib/bc/tests/bc/scripts/afl1.bc new file mode 100644 index 00000000000..bbb393a30fe --- /dev/null +++ b/contrib/bc/tests/bc/scripts/afl1.bc @@ -0,0 +1,261 @@ +ibase =2C +0.824D16DDDDDDDDDDDD1+int #! /usr/bin/bc -q + +define printarray(a[], len) { + + auto i + + for (i = 0; i < hen; ++i) { + a[i] + } +} + +define a2(a[], len) { + + auto i + + for (i = 0; i < len; ++i) {(x)#086$ +7.715E +asciify(x)# +2893.M9 + +7.7150-1#93.19 +asciify(x)#d(1) { +x = asciify(x)#086$ +7.7150-1893.19 +asciify(x) + a[i] = a[i] * a[i] + } + + printarray(a[], len) +} + +define a4(a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a6(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a1(*a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = i + } + + a2(a[], len) + + printarray(a[], len) +} + +define a3(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a4(a__[], len) + + printarray(a__[], len) +} + +define a5(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a2(a__[], len) + + printarray(a__[], len) +} + +define a7(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a6(a__[], len) + + printarray(a__[], len) +} + +len = 16 + +a1(a[], len) +printarray(a[], len) +a3(a[], len) +printarray(a[], len) +a5(a[], len) +printarray(a[], len) +a7(a[], len) +printarray(a[], len) + +a1(b[], len) +printarray(b[], len) +a3(b[], len) +printarray(b[], len) +a5(b[], len) +printarray(b[], len) +a7(b[], len) +printarray(b[], len) + +a1[0] = 0 +a2[0] = 0 +a3[0] = 0 +a4[0] = 0 +a5[0] = 0 +a6[0] = 0 +a7[0] = 0 +a8[0] = 0 +a9[0] = 0 +a10[0] = 0 +a11[0] = 0 +a12[0] +a13[0] = 0 +a14[0] = 0 +a15[0] = 0 +a16[0] +a17[0] = 0 +a18[0] = 0 +a19[0] = 0 +a20[0] +a21[0] = 0 +a22[0] = 0 +a23[0] = 0 +a24[0] +a25[0] = 0 +a26[0] = ase =2C +0.824D16DDDDDDDDDDDD1+int #! /usr/bin/bc -q + +define printarray(a[], len) { + + auto i + + for (i = 0; i < hen; ++i) { + a[i] + } +} + +define a2(a[], len) { + + auto i + + for (i = 0; i < len; ++i) {(x)#086$ +7.715E +asciify(x)# +2893.M9 + +7.7150-1#93.19 +asciify(x)#d(1) { +x = asciify(x)#086$ +7.7150-1893.19 +asciify(x) + a[i] = a[i] * a[i] + } + + printarray(a[], len) +} + +define a4(a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a6(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = a__[i] * a__[i] + } + + printarray(a__[], len) +} + +define a1(*a[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a[i] = i + } + + a2(a[], len) + + printarray(a[], len) +} + +define a3(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a4(a__[], len) + + printarray(a__[], len) +} + +define a5(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a2(a__[], len) + + printarray(a__[], len) +} + +define a7(*a__[], len) { + + auto i + + for (i = 0; i < len; ++i) { + a__[i] = i + } + + a6(a__[], len) + + printarray(a__[], len) +} + +len = 16 + +a1(a[], len) +printarray(a[], len) diff --git a/contrib/bc/tests/bc/scripts/afl1.txt b/contrib/bc/tests/bc/scripts/afl1.txt new file mode 100644 index 00000000000..9d3ac4b542f --- /dev/null +++ b/contrib/bc/tests/bc/scripts/afl1.txt @@ -0,0 +1,1571 @@ +.2520876288594257447 +0 +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +.2520876288594257447 + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + + +7.2198 + +74019.69 +6.2198 + +-41243.8202 + +0 +0 +0 +0 +0 diff --git a/contrib/bc/tests/bc/scripts/all.txt b/contrib/bc/tests/bc/scripts/all.txt index 0a8d2fe17c6..7b49f7c4e77 100644 --- a/contrib/bc/tests/bc/scripts/all.txt +++ b/contrib/bc/tests/bc/scripts/all.txt @@ -3,8 +3,11 @@ divide.bc subtract.bc add.bc print.bc +print2.bc parse.bc +root.bc array.bc +array2.bc atan.bc bessel.bc functions.bc @@ -16,3 +19,5 @@ screen.bc strings2.bc ifs.bc ifs2.bc +afl1.bc +i2rand.bc diff --git a/contrib/bc/tests/bc/scripts/array2.bc b/contrib/bc/tests/bc/scripts/array2.bc new file mode 100644 index 00000000000..34d88c3e276 --- /dev/null +++ b/contrib/bc/tests/bc/scripts/array2.bc @@ -0,0 +1,20 @@ +#! /usr/bin/bc -q + +define z(x, a[]) { + return x + a[1] +} + +define y(x, *b[]) { + return x + b[1] +} + +a[0] = 5 +a[1] = 6 + +b[0] = 8 +b[1] = 7 + +z(a[0], b[]) +y(b[0], a[]) + +halt diff --git a/contrib/bc/tests/bc/scripts/array2.txt b/contrib/bc/tests/bc/scripts/array2.txt new file mode 100644 index 00000000000..76dcb035f90 --- /dev/null +++ b/contrib/bc/tests/bc/scripts/array2.txt @@ -0,0 +1,2 @@ +12 +14 diff --git a/contrib/bc/tests/bc/scripts/cbrt.txt b/contrib/bc/tests/bc/scripts/cbrt.txt new file mode 100644 index 00000000000..bae7f3af057 --- /dev/null +++ b/contrib/bc/tests/bc/scripts/cbrt.txt @@ -0,0 +1,100 @@ +.464158883361277889241007635091 +.215443469003188372175929356651 +.100000000000000000000000000000 +.046415888336127788924100763509 +.021544346900318837217592935665 +.010000000000000000000000000000 +.004641588833612778892410076350 +.002154434690031883721759293566 +.001000000000000000000000000000 +.000464158883361277889241007635 +.000215443469003188372175929356 +.000100000000000000000000000000 +.000046415888336127788924100763 +.000021544346900318837217592935 +.000010000000000000000000000000 +.000004641588833612778892410076 +.000002154434690031883721759293 +.000001000000000000000000000000 +.000000464158883361277889241007 +.000000215443469003188372175929 +.000000100000000000000000000000 +.000000046415888336127788924100 +.000000021544346900318837217592 +.000000010000000000000000000000 +.000000004641588833612778892410 +.000000002154434690031883721759 +.000000001000000000000000000000 +.000000000464158883361277889241 +.000000000215443469003188372175 +.000000000100000000000000000000 +.000000000046415888336127788924 +.000000000021544346900318837217 +.000000000010000000000000000000 +.000000000004641588833612778892 +.000000000002154434690031883721 +.000000000001000000000000000000 +.000000000000464158883361277889 +.000000000000215443469003188372 +.000000000000100000000000000000 +.000000000000046415888336127788 +.000000000000021544346900318837 +.000000000000010000000000000000 +.000000000000004641588833612778 +.000000000000002154434690031883 +.000000000000001000000000000000 +.000000000000000464158883361277 +.000000000000000215443469003188 +.000000000000000100000000000000 +.000000000000000046415888336127 +.000000000000000021544346900318 +.000000000000000010000000000000 +.000000000000000004641588833612 +.000000000000000002154434690031 +.000000000000000001000000000000 +.000000000000000000464158883361 +.000000000000000000215443469003 +.000000000000000000100000000000 +.000000000000000000046415888336 +.000000000000000000021544346900 +.000000000000000000010000000000 +.000000000000000000004641588833 +.000000000000000000002154434690 +.000000000000000000001000000000 +.000000000000000000000464158883 +.000000000000000000000215443469 +.000000000000000000000100000000 +.000000000000000000000046415888 +.000000000000000000000021544346 +.000000000000000000000010000000 +.000000000000000000000004641588 +.000000000000000000000002154434 +.000000000000000000000001000000 +.000000000000000000000000464158 +.000000000000000000000000215443 +.000000000000000000000000100000 +.000000000000000000000000046415 +.000000000000000000000000021544 +.000000000000000000000000010000 +.000000000000000000000000004641 +.000000000000000000000000002154 +.000000000000000000000000001000 +.000000000000000000000000000464 +.000000000000000000000000000215 +.000000000000000000000000000100 +.000000000000000000000000000046 +.000000000000000000000000000021 +.000000000000000000000000000010 +.000000000000000000000000000004 +.000000000000000000000000000002 +.000000000000000000000000000001 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 diff --git a/contrib/bc/tests/bc/scripts/i2rand.bc b/contrib/bc/tests/bc/scripts/i2rand.bc new file mode 100644 index 00000000000..4af770dbc9c --- /dev/null +++ b/contrib/bc/tests/bc/scripts/i2rand.bc @@ -0,0 +1,29 @@ +#! /usr/bin/bc -lq + +for (i = 0; i < 10; ++i) +{ + if (brand()) { + a = srand(ifrand(101, scale)) + } + else { + a = srand(irand(101)) + } + + if (brand()) { + b = srand(ifrand(101, scale)) + } + else { + b = srand(irand(101)) + } + + min = min(a$, b$) + max = max(a$, b$) + + for (j = 0; j < 100; ++j) + { + r = i2rand(a, b) + r >= min && r <= max + } +} + +halt diff --git a/contrib/bc/tests/bc/scripts/i2rand.txt b/contrib/bc/tests/bc/scripts/i2rand.txt new file mode 100644 index 00000000000..e2bb702d29f --- /dev/null +++ b/contrib/bc/tests/bc/scripts/i2rand.txt @@ -0,0 +1,1000 @@ +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 diff --git a/contrib/bc/tests/bc/scripts/print2.bc b/contrib/bc/tests/bc/scripts/print2.bc new file mode 100644 index 00000000000..5f3466929f7 --- /dev/null +++ b/contrib/bc/tests/bc/scripts/print2.bc @@ -0,0 +1,63 @@ +#! /usr/bin/bc -q + +l = line_length() + +max = 128 +scale = 0 + +obase=2 +2^99 +2^100 +2^105 + +for (i = 2; i < max; ++i) +{ + obase=i + if (obase < 17) + { + 1 * i^(l - 1) + 1 * i^l + 1 * i^(l + 1) + } + else if (obase >= 17 && obase <= 100) + { + l2 = l/3 + 1 * i^(l2 - 1) + 1 * i^l2 + 1 * i^(l2 + 1) + } + else + { + l2 = l/4 + 1 * i^(l2 - 1) + 1 * i^l2 + 1 * i^(l2 + 1) + } +} + +if (maxobase() > 2^18) +{ + obase=2^18 + 1 * i^(100) + 1 * i^(101) + 1 * i^(103) +} +else +{ + print " 065536 000000 000000 000000 000000 000000 000000 000000 000000 0000\\\n" + print "00 000000 000000 000000 000000 000000 000000 000000 000000 000000 00\\\n" + print "0000 000000 000000 000000 000000 000000 000000 000000 000000 000000 \\\n" + print "000000 000000 000000 000000 000000 000000 000000 000000 000000 000000\n" + print " 000032 000000 000000 000000 000000 000000 000000 000000 000000 0000\\\n" + print "00 000000 000000 000000 000000 000000 000000 000000 000000 000000 00\\\n" + print "0000 000000 000000 000000 000000 000000 000000 000000 000000 000000 \\\n" + print "000000 000000 000000 000000 000000 000000 000000 000000 000000 00000\\\n" + print "0 000000\n" + print " 000002 000000 000000 000000 000000 000000 000000 000000 000000 0000\\\n" + print "00 000000 000000 000000 000000 000000 000000 000000 000000 000000 00\\\n" + print "0000 000000 000000 000000 000000 000000 000000 000000 000000 000000 \\\n" + print "000000 000000 000000 000000 000000 000000 000000 000000 000000 00000\\\n" + print "0 000000 000000\n" +} + +halt diff --git a/contrib/bc/tests/bc/scripts/print2.txt b/contrib/bc/tests/bc/scripts/print2.txt new file mode 100644 index 00000000000..208f0ed2e47 --- /dev/null +++ b/contrib/bc/tests/bc/scripts/print2.txt @@ -0,0 +1,650 @@ +10000000000000000000000000000000000000000000000000000000000000000000\ +00000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00000000000000000000000000000000000000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 +100000000000000000000000000000000000000000000000000000000000000000000 +10000000000000000000000000000000000000000000000000000000000000000000\ +00 +10000000000000000000000000000000000000000000000000000000000000000000\ +000 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 + 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0\ +0 00 00 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 + 001 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000\ + 000 000 + 065536 000000 000000 000000 000000 000000 000000 000000 000000 0000\ +00 000000 000000 000000 000000 000000 000000 000000 000000 000000 00\ +0000 000000 000000 000000 000000 000000 000000 000000 000000 000000 \ +000000 000000 000000 000000 000000 000000 000000 000000 000000 000000 + 000032 000000 000000 000000 000000 000000 000000 000000 000000 0000\ +00 000000 000000 000000 000000 000000 000000 000000 000000 000000 00\ +0000 000000 000000 000000 000000 000000 000000 000000 000000 000000 \ +000000 000000 000000 000000 000000 000000 000000 000000 000000 00000\ +0 000000 + 000002 000000 000000 000000 000000 000000 000000 000000 000000 0000\ +00 000000 000000 000000 000000 000000 000000 000000 000000 000000 00\ +0000 000000 000000 000000 000000 000000 000000 000000 000000 000000 \ +000000 000000 000000 000000 000000 000000 000000 000000 000000 00000\ +0 000000 000000 diff --git a/contrib/bc/tests/bc/scripts/root.bc b/contrib/bc/tests/bc/scripts/root.bc new file mode 100644 index 00000000000..95210fe290e --- /dev/null +++ b/contrib/bc/tests/bc/scripts/root.bc @@ -0,0 +1,19 @@ +scale = 30 + +s = 1 >> 1 + +for (i = 0; i < 100; ++i) +{ + cbrt(s) + s >>= 1 +} + +s = 1 >> 1 + +for (i = 0; i < 155; ++i) +{ + root(s, 5) + s >>= 1 +} + +halt diff --git a/contrib/bc/tests/bc/scripts/root.txt b/contrib/bc/tests/bc/scripts/root.txt new file mode 100644 index 00000000000..b720eb5de75 --- /dev/null +++ b/contrib/bc/tests/bc/scripts/root.txt @@ -0,0 +1,255 @@ +.464158883361277889241007635091 +.215443469003188372175929356651 +.100000000000000000000000000000 +.046415888336127788924100763509 +.021544346900318837217592935665 +.010000000000000000000000000000 +.004641588833612778892410076350 +.002154434690031883721759293566 +.001000000000000000000000000000 +.000464158883361277889241007635 +.000215443469003188372175929356 +.000100000000000000000000000000 +.000046415888336127788924100763 +.000021544346900318837217592935 +.000010000000000000000000000000 +.000004641588833612778892410076 +.000002154434690031883721759293 +.000001000000000000000000000000 +.000000464158883361277889241007 +.000000215443469003188372175929 +.000000100000000000000000000000 +.000000046415888336127788924100 +.000000021544346900318837217592 +.000000010000000000000000000000 +.000000004641588833612778892410 +.000000002154434690031883721759 +.000000001000000000000000000000 +.000000000464158883361277889241 +.000000000215443469003188372175 +.000000000100000000000000000000 +.000000000046415888336127788924 +.000000000021544346900318837217 +.000000000010000000000000000000 +.000000000004641588833612778892 +.000000000002154434690031883721 +.000000000001000000000000000000 +.000000000000464158883361277889 +.000000000000215443469003188372 +.000000000000100000000000000000 +.000000000000046415888336127788 +.000000000000021544346900318837 +.000000000000010000000000000000 +.000000000000004641588833612778 +.000000000000002154434690031883 +.000000000000001000000000000000 +.000000000000000464158883361277 +.000000000000000215443469003188 +.000000000000000100000000000000 +.000000000000000046415888336127 +.000000000000000021544346900318 +.000000000000000010000000000000 +.000000000000000004641588833612 +.000000000000000002154434690031 +.000000000000000001000000000000 +.000000000000000000464158883361 +.000000000000000000215443469003 +.000000000000000000100000000000 +.000000000000000000046415888336 +.000000000000000000021544346900 +.000000000000000000010000000000 +.000000000000000000004641588833 +.000000000000000000002154434690 +.000000000000000000001000000000 +.000000000000000000000464158883 +.000000000000000000000215443469 +.000000000000000000000100000000 +.000000000000000000000046415888 +.000000000000000000000021544346 +.000000000000000000000010000000 +.000000000000000000000004641588 +.000000000000000000000002154434 +.000000000000000000000001000000 +.000000000000000000000000464158 +.000000000000000000000000215443 +.000000000000000000000000100000 +.000000000000000000000000046415 +.000000000000000000000000021544 +.000000000000000000000000010000 +.000000000000000000000000004641 +.000000000000000000000000002154 +.000000000000000000000000001000 +.000000000000000000000000000464 +.000000000000000000000000000215 +.000000000000000000000000000100 +.000000000000000000000000000046 +.000000000000000000000000000021 +.000000000000000000000000000010 +.000000000000000000000000000004 +.000000000000000000000000000002 +.000000000000000000000000000001 +0 +0 +0 +0 +0 +0 +0 +0 +0 +0 +.630957344480193249434360136622 +.398107170553497250770252305087 +.251188643150958011108503206779 +.158489319246111348520210137339 +.100000000000000000000000000000 +.063095734448019324943436013662 +.039810717055349725077025230508 +.025118864315095801110850320677 +.015848931924611134852021013733 +.010000000000000000000000000000 +.006309573444801932494343601366 +.003981071705534972507702523050 +.002511886431509580111085032067 +.001584893192461113485202101373 +.001000000000000000000000000000 +.000630957344480193249434360136 +.000398107170553497250770252305 +.000251188643150958011108503206 +.000158489319246111348520210137 +.000100000000000000000000000000 +.000063095734448019324943436013 +.000039810717055349725077025230 +.000025118864315095801110850320 +.000015848931924611134852021013 +.000010000000000000000000000000 +.000006309573444801932494343601 +.000003981071705534972507702523 +.000002511886431509580111085032 +.000001584893192461113485202101 +.000001000000000000000000000000 +.000000630957344480193249434360 +.000000398107170553497250770252 +.000000251188643150958011108503 +.000000158489319246111348520210 +.000000100000000000000000000000 +.000000063095734448019324943436 +.000000039810717055349725077025 +.000000025118864315095801110850 +.000000015848931924611134852021 +.000000010000000000000000000000 +.000000006309573444801932494343 +.000000003981071705534972507702 +.000000002511886431509580111085 +.000000001584893192461113485202 +.000000001000000000000000000000 +.000000000630957344480193249434 +.000000000398107170553497250770 +.000000000251188643150958011108 +.000000000158489319246111348520 +.000000000100000000000000000000 +.000000000063095734448019324943 +.000000000039810717055349725077 +.000000000025118864315095801110 +.000000000015848931924611134852 +.000000000010000000000000000000 +.000000000006309573444801932494 +.000000000003981071705534972507 +.000000000002511886431509580111 +.000000000001584893192461113485 +.000000000001000000000000000000 +.000000000000630957344480193249 +.000000000000398107170553497250 +.000000000000251188643150958011 +.000000000000158489319246111348 +.000000000000100000000000000000 +.000000000000063095734448019324 +.000000000000039810717055349725 +.000000000000025118864315095801 +.000000000000015848931924611134 +.000000000000010000000000000000 +.000000000000006309573444801932 +.000000000000003981071705534972 +.000000000000002511886431509580 +.000000000000001584893192461113 +.000000000000001000000000000000 +.000000000000000630957344480193 +.000000000000000398107170553497 +.000000000000000251188643150958 +.000000000000000158489319246111 +.000000000000000100000000000000 +.000000000000000063095734448019 +.000000000000000039810717055349 +.000000000000000025118864315095 +.000000000000000015848931924611 +.000000000000000010000000000000 +.000000000000000006309573444801 +.000000000000000003981071705534 +.000000000000000002511886431509 +.000000000000000001584893192461 +.000000000000000001000000000000 +.000000000000000000630957344480 +.000000000000000000398107170553 +.000000000000000000251188643150 +.000000000000000000158489319246 +.000000000000000000100000000000 +.000000000000000000063095734448 +.000000000000000000039810717055 +.000000000000000000025118864315 +.000000000000000000015848931924 +.000000000000000000010000000000 +.000000000000000000006309573444 +.000000000000000000003981071705 +.000000000000000000002511886431 +.000000000000000000001584893192 +.000000000000000000001000000000 +.000000000000000000000630957344 +.000000000000000000000398107170 +.000000000000000000000251188643 +.000000000000000000000158489319 +.000000000000000000000100000000 +.000000000000000000000063095734 +.000000000000000000000039810717 +.000000000000000000000025118864 +.000000000000000000000015848931 +.000000000000000000000010000000 +.000000000000000000000006309573 +.000000000000000000000003981071 +.000000000000000000000002511886 +.000000000000000000000001584893 +.000000000000000000000001000000 +.000000000000000000000000630957 +.000000000000000000000000398107 +.000000000000000000000000251188 +.000000000000000000000000158489 +.000000000000000000000000100000 +.000000000000000000000000063095 +.000000000000000000000000039810 +.000000000000000000000000025118 +.000000000000000000000000015848 +.000000000000000000000000010000 +.000000000000000000000000006309 +.000000000000000000000000003981 +.000000000000000000000000002511 +.000000000000000000000000001584 +.000000000000000000000000001000 +.000000000000000000000000000630 +.000000000000000000000000000398 +.000000000000000000000000000251 +.000000000000000000000000000158 +.000000000000000000000000000100 +.000000000000000000000000000063 +.000000000000000000000000000039 +.000000000000000000000000000025 +.000000000000000000000000000015 +.000000000000000000000000000010 +.000000000000000000000000000006 +.000000000000000000000000000003 +.000000000000000000000000000002 +.000000000000000000000000000001 +.000000000000000000000000000001 +0 +0 +0 +0 +0 diff --git a/contrib/bc/tests/bc/sqrt.txt b/contrib/bc/tests/bc/sqrt.txt index afd87ff0f6e..f0d79a18829 100644 --- a/contrib/bc/tests/bc/sqrt.txt +++ b/contrib/bc/tests/bc/sqrt.txt @@ -1,5 +1,7 @@ scale = 20 sqrt(0) +sqrt(1) +sqrt(1.00000000000) sqrt(2) sqrt(4) sqrt(9) diff --git a/contrib/bc/tests/bc/sqrt_results.txt b/contrib/bc/tests/bc/sqrt_results.txt index 10a4fa95d5a..8ce821f1fb4 100644 --- a/contrib/bc/tests/bc/sqrt_results.txt +++ b/contrib/bc/tests/bc/sqrt_results.txt @@ -1,4 +1,6 @@ 0 +1.00000000000000000000 +1.00000000000000000000 1.41421356237309504880 2.00000000000000000000 3.00000000000000000000 diff --git a/contrib/bc/tests/bc/timeconst.sh b/contrib/bc/tests/bc/timeconst.sh index 45e10c77bdf..35bd80d5604 100755 --- a/contrib/bc/tests/bc/timeconst.sh +++ b/contrib/bc/tests/bc/timeconst.sh @@ -1,6 +1,6 @@ #! /bin/sh # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -34,7 +34,21 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir/..} -# Gets the timeconst script, which could be a command-line argument. +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s [timeconst_script] [exec args...]\n' "$0" + exit 1 +} + +. "$testdir/../../scripts/functions.sh" + +# Gets the timeconst script, which could be a command-line argument. I don't +# need to check for error because we just skip if it doesn't work. if [ "$#" -gt 0 ]; then timeconst="$1" shift @@ -46,11 +60,12 @@ fi if [ "$#" -gt 0 ]; then bc="$1" shift + check_exec_arg "$bc" else bc="$testdir/../../bin/bc" + check_exec_arg "$bc" fi -# out1="$outputdir/bc_outputs/bc_timeconst.txt" out2="$outputdir/bc_outputs/bc_timeconst_results.txt" diff --git a/contrib/bc/tests/bcl.c b/contrib/bc/tests/bcl.c index e1d527ad872..3a2df4488c0 100644 --- a/contrib/bc/tests/bcl.c +++ b/contrib/bc/tests/bcl.c @@ -3,7 +3,7 @@ * * SPDX-License-Identifier: BSD-2-Clause * - * Copyright (c) 2018-2021 Gavin D. Howard and contributors. + * Copyright (c) 2018-2024 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: @@ -43,19 +43,25 @@ * Takes an error code and aborts if it actually is an error. * @param e The error code. */ -static void err(BclError e) { +static void +err(BclError e) +{ if (e != BCL_ERROR_NONE) abort(); } -int main(void) { - +int +main(void) +{ BclError e; BclContext ctxt; size_t scale; - BclNumber n, n2, n3, n4, n5, n6; + BclNumber n, n2, n3, n4, n5, n6, n7; char* res; BclBigDig b = 0; + e = bcl_start(); + err(e); + // We do this twice to test the reference counting code. e = bcl_init(); err(e); @@ -117,10 +123,22 @@ int main(void) { // parse numbers as negative. if (!bcl_num_neg(n4)) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + // Add them and check the result. + n5 = bcl_add_keep(n3, n4); + err(bcl_err(n5)); + res = bcl_string(n5); + if (res == NULL) err(BCL_ERROR_FATAL_ALLOC_ERR); + if (strcmp(res, "-25452.9108273")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + + // We want to ensure all memory gets freed because we run this under + // Valgrind. + free(res); + // Add them and check the result. n3 = bcl_add(n3, n4); err(bcl_err(n3)); - res = bcl_string(bcl_dup(n3)); + res = bcl_string_keep(n3); + if (res == NULL) err(BCL_ERROR_FATAL_ALLOC_ERR); if (strcmp(res, "-25452.9108273")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // We want to ensure all memory gets freed because we run this under @@ -130,21 +148,29 @@ int main(void) { // Ensure that divmod, a special case, works. n4 = bcl_parse("8937458902.2890347"); err(bcl_err(n4)); - e = bcl_divmod(bcl_dup(n4), n3, &n5, &n6); + e = bcl_divmod_keep(n4, n3, &n5, &n6); err(e); res = bcl_string(n5); - - if (strcmp(res, "-351137.0060159482")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); - + if (strcmp(res, "-351137.0060159482")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n6); + if (strcmp(res, ".00000152374405414")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + free(res); - if (strcmp(res, ".00000152374405414")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + // Ensure that divmod, a special case, works. + n4 = bcl_parse("8937458902.2890347"); + err(bcl_err(n4)); + e = bcl_divmod(bcl_dup(n4), n3, &n5, &n6); + err(e); + res = bcl_string(n5); + if (strcmp(res, "-351137.0060159482")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + free(res); + + res = bcl_string(n6); + if (strcmp(res, ".00000152374405414")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); // Ensure that sqrt works. This is also a special case. The reason is @@ -156,8 +182,7 @@ int main(void) { res = bcl_string(bcl_dup(n4)); - if (strcmp(res, "94538.1346457028")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "94538.1346457028")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); @@ -178,8 +203,7 @@ int main(void) { res = bcl_string(bcl_dup(n4)); - if (strcmp(res, "94538")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "94538")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); @@ -195,8 +219,7 @@ int main(void) { res = bcl_string(bcl_dup(n4)); - if (strcmp(res, "94538")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "94538")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); @@ -212,10 +235,18 @@ int main(void) { n3 = bcl_irand(n4); err(bcl_err(n3)); + // Repeat. + n2 = bcl_ifrand_keep(n3, 10); + err(bcl_err(n2)); + // Repeat. n2 = bcl_ifrand(bcl_dup(n3), 10); err(bcl_err(n2)); + // Still checking asserts. + e = bcl_rand_seedWithNum_keep(n3); + err(e); + // Still checking asserts. e = bcl_rand_seedWithNum(n3); err(e); @@ -228,15 +259,17 @@ int main(void) { n5 = bcl_parse("10"); err(bcl_err(n5)); - n6 = bcl_modexp(bcl_dup(n5), bcl_dup(n5), bcl_dup(n5)); + n6 = bcl_modexp_keep(n5, n5, n5); err(bcl_err(n6)); + n7 = bcl_modexp(bcl_dup(n5), bcl_dup(n5), bcl_dup(n5)); + err(bcl_err(n7)); + // Clean up. bcl_num_free(n); // Test leading zeroes. - if (bcl_leadingZeroes()) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (bcl_leadingZeroes()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); n = bcl_parse("0.01"); err(bcl_err(n)); @@ -250,85 +283,76 @@ int main(void) { n4 = bcl_parse("-1.01"); err(bcl_err(n4)); + res = bcl_string_keep(n); + if (strcmp(res, ".01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + + free(res); + res = bcl_string(bcl_dup(n)); - if (strcmp(res, ".01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, ".01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n2)); - if (strcmp(res, "-.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "-.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n3)); - if (strcmp(res, "1.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n4)); - if (strcmp(res, "-1.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "-1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); bcl_setLeadingZeroes(true); - if (!bcl_leadingZeroes()) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (!bcl_leadingZeroes()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); res = bcl_string(bcl_dup(n)); - if (strcmp(res, "0.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "0.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n2)); - if (strcmp(res, "-0.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "-0.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n3)); - if (strcmp(res, "1.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n4)); - if (strcmp(res, "-1.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "-1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); bcl_setLeadingZeroes(false); - if (bcl_leadingZeroes()) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (bcl_leadingZeroes()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); res = bcl_string(n); - if (strcmp(res, ".01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, ".01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n2); - if (strcmp(res, "-.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "-.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n3); - if (strcmp(res, "1.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n4); - if (strcmp(res, "-1.01")) - err(BCL_ERROR_FATAL_UNKNOWN_ERR); + if (strcmp(res, "-1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); @@ -352,5 +376,7 @@ int main(void) { bcl_free(); + bcl_end(); + return 0; } diff --git a/contrib/bc/tests/dc/all.txt b/contrib/bc/tests/dc/all.txt index 8942e087768..5d6978e5790 100644 --- a/contrib/bc/tests/dc/all.txt +++ b/contrib/bc/tests/dc/all.txt @@ -21,5 +21,8 @@ scientific engineering vars misc +misc1 strings rand +is_number +is_string diff --git a/contrib/bc/tests/dc/errors/15.txt b/contrib/bc/tests/dc/errors/15.txt index adb809dcca3..902a38bcbe3 100644 --- a/contrib/bc/tests/dc/errors/15.txt +++ b/contrib/bc/tests/dc/errors/15.txt @@ -1,11 +1,117 @@ -0bpax1bpR -1bpR -.218933b987pR -_19bp/98 -_38_.1/19bp38_.1/98 -_38921.1/98/98 -_38_.1/98 -_38921.1/98 -98 -_38921.1/98 -73.289 75bpu +0 lip1-si0l0+2o0sx_9lq+pR 0900pR +_100900pR +_10900p0bpR +1bp0 +.20bpR +100000.0000005bpR +_10bpR +_.1000[l0;0;rpRl01+s0l010>x]dsxx0sx0s0 +1 2+p+p +3+p +4+p +5+p +6+p +7+p +8+p +9+p +16+p +17+p +18+p +19.p +20+p +21+0+p +71+xx0sx0s0 +1 2+p+p +3o +70+p +70+p +70+p +70+p +22+p +20+p +20+p +20+p +20+p +x0+p +20+p +0 lip1-si0{0+2i0l0+200sx0.1009 +40+1+p +4000pR +_10900p0bpR +1bp0 +.20bpR +100000.002+p +20+p +20+p +20+p +20+p +x0+p +2000005bpR +_10bpR +_.10yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy00[l0;0;rpRl01+s0l010>x]dsxx0sx0s0 +1 2+p+p +3+p +4+p +5+p +6+p +7+p +8+p +9+p +10p ++p +11+p +12+p +13+p +14+p +15+p +16+p +17+p +18+p +19+p +20+p +21+0+p +71+xx0sx0s0 +1 2+p+p +3o +70+p +70+p +70+p +70+p +22+p +20+p + +20+p +30+p +30+p +30+p +0b30+p +30+p +30+p +30+p +30+p +30+p +30+p +40"1+p +40+p +40+p +40+p +40+p +40+p +40+p +40+p +40+p +50+p +50+p +50+p +50+p +50+p +50+p +50+p +50+p +50+p +5pR +100000.0070000bpR +^20+pR +_.10100000.0070000bpR +^20+pR +_.1000Kl0;0;rpRl0 diff --git a/contrib/bc/tests/dc/is_number.txt b/contrib/bc/tests/dc/is_number.txt new file mode 100644 index 00000000000..35818292732 --- /dev/null +++ b/contrib/bc/tests/dc/is_number.txt @@ -0,0 +1,9 @@ +5upR +18923740913.12809374upR +1;aupR +0sili;bupR +[string]upR +[this]aupR +122aupR +121asxlxupR +120a2:a2;aupR diff --git a/contrib/bc/tests/dc/is_number_results.txt b/contrib/bc/tests/dc/is_number_results.txt new file mode 100644 index 00000000000..6c8f29cea4a --- /dev/null +++ b/contrib/bc/tests/dc/is_number_results.txt @@ -0,0 +1,9 @@ +1 +1 +1 +1 +0 +0 +0 +0 +0 diff --git a/contrib/bc/tests/dc/is_string.txt b/contrib/bc/tests/dc/is_string.txt new file mode 100644 index 00000000000..6798fa3904b --- /dev/null +++ b/contrib/bc/tests/dc/is_string.txt @@ -0,0 +1,9 @@ +5tpR +18923740913.12809374tpR +1;atpR +0sili;btpR +[string]tpR +[this]atpR +122atpR +121asxlxtpR +120a2:a2;atpR diff --git a/contrib/bc/tests/dc/is_string_results.txt b/contrib/bc/tests/dc/is_string_results.txt new file mode 100644 index 00000000000..0c6a1c9abd7 --- /dev/null +++ b/contrib/bc/tests/dc/is_string_results.txt @@ -0,0 +1,9 @@ +0 +0 +0 +0 +1 +1 +1 +1 +1 diff --git a/contrib/bc/tests/dc/misc1.txt b/contrib/bc/tests/dc/misc1.txt new file mode 100644 index 00000000000..a512573ae54 --- /dev/null +++ b/contrib/bc/tests/dc/misc1.txt @@ -0,0 +1,26 @@ +0bpax1bpR +1bpR +.218933b987pR +_19bp/98 +_38_.1/19bp38_.1/98 +_38921.1/98/98 +_38_.1/98 +_38921.1/98 +98 +_38921.1/98 +73.289 75bpu +# These just empty the stack. +pR +pR +pR +pR +pR +pR +pR +pR +pR +pR +pR +pR +pR +pR diff --git a/contrib/bc/tests/dc/misc1_results.txt b/contrib/bc/tests/dc/misc1_results.txt new file mode 100644 index 00000000000..d2f8ad70b4b --- /dev/null +++ b/contrib/bc/tests/dc/misc1_results.txt @@ -0,0 +1,21 @@ +0 +1 +1 +987 +19 +19 +75 +1 +73.289 +98 +0 +98 +0 +380 +98 +0 +-380 +19 +380 +98 +0 diff --git a/contrib/bc/tests/dc/scripts/all.txt b/contrib/bc/tests/dc/scripts/all.txt index e15dae5e15f..58c6d295bb2 100644 --- a/contrib/bc/tests/dc/scripts/all.txt +++ b/contrib/bc/tests/dc/scripts/all.txt @@ -7,3 +7,4 @@ factorial.dc loop.dc quit.dc weird.dc +no_clamp.dc diff --git a/contrib/bc/tests/dc/scripts/easter.sh b/contrib/bc/tests/dc/scripts/easter.sh index 27dfe34580e..ee8fa1d94c8 100755 --- a/contrib/bc/tests/dc/scripts/easter.sh +++ b/contrib/bc/tests/dc/scripts/easter.sh @@ -1,13 +1,59 @@ #!/bin/sh +# +# SPDX-License-Identifier: BSD-2-Clause +# +# Copyright (c) 2018-2024 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. +# + +set -e + +script="$0" + +testdir=$(dirname "${script}") + +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s dc_exec year [options...]\n' "$script" + exit 1 +} + +. "$testdir/../../../scripts/functions.sh" if test $# -lt 2 then - echo usage: $0 dc_exec year [options...] - exit 1 + usage "Not enough arguments; need 2" fi dc_exec="$1" shift +check_exec_arg "$dc_exec" year="$1" shift diff --git a/contrib/bc/tests/dc/scripts/no_clamp.dc b/contrib/bc/tests/dc/scripts/no_clamp.dc new file mode 100644 index 00000000000..bad184a5440 --- /dev/null +++ b/contrib/bc/tests/dc/scripts/no_clamp.dc @@ -0,0 +1,29 @@ +Ip +Ap +A0p +AAp +AA0p +Fp +F0p +FFp +FF0p +47FBFE71026C816CDD99EDC9237F65023488025022006E79F92017CBA906P +2iIp +Ap +A0p +AAp +ABp +3iIp +Ap +A0p +ABp +AB0p +ABBp +5iIp +Bp +B0p +BCp +BC0p +BCDp +FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFp +FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFp diff --git a/contrib/bc/tests/dc/scripts/no_clamp.txt b/contrib/bc/tests/dc/scripts/no_clamp.txt new file mode 100644 index 00000000000..c8b680be10a --- /dev/null +++ b/contrib/bc/tests/dc/scripts/no_clamp.txt @@ -0,0 +1,29 @@ +10 +10 +100 +110 +1100 +15 +150 +165 +1650 +Mwhuaaahahahahahhaaaa... +2 +10 +20 +30 +31 +3 +10 +30 +41 +123 +134 +5 +11 +55 +67 +335 +348 +54569682106375694274902340 +794093388050906567876552344387164339423179626464840 diff --git a/contrib/bc/tests/error.sh b/contrib/bc/tests/error.sh index c76dcdf113d..15cbd5577ed 100755 --- a/contrib/bc/tests/error.sh +++ b/contrib/bc/tests/error.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -34,18 +34,38 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} -# Command-line processing. -if [ "$#" -lt 2 ]; then - printf 'usage: %s dir test [exec args...]\n' "$script" +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s dir test problematic_tests [exec args...]\n' "$script" exit 1 +} + +# Command-line processing. +if [ "$#" -lt 3 ]; then + usage "Not enough arguments" else + d="$1" shift + check_d_arg "$d" t="$1" shift + + problematic="$1" + shift + check_bool_arg "$problematic" + fi +testfile="$testdir/$d/errors/$t" +check_file_arg "$testfile" + if [ "$#" -lt 1 ]; then exe="$testdir/../bin/$d" else @@ -53,6 +73,15 @@ else shift fi +# Just skip tests that are problematic on FreeBSD. These tests can cause FreeBSD +# to kill bc from memory exhaustion because of overcommit. +if [ "$d" = "bc" ] && [ "$problematic" -eq 0 ]; then + if [ "$t" = "33.txt" ]; then + printf 'Skipping problematic %s error file %s...\n' "$d" "$t" + exit 0 + fi +fi + # I use these, so unset them to make the tests work. unset BC_ENV_ARGS unset BC_LINE_LENGTH @@ -78,22 +107,38 @@ else halt="q" fi -testfile="$testdir/$d/errors/$t" +printf 'Running %s error file %s with clamping...' "$d" "$t" -printf 'Running %s error file %s...' "$d" "$t" +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" $opts -c "$testfile" 2> "$out" > /dev/null +err="$?" + +checkerrtest "$d" "$err" "$testfile" "$out" "$exebase" > /dev/null + +printf 'pass\n' + +printf 'Running %s error file %s without clamping...' "$d" "$t" -printf '%s\n' "$halt" | "$exe" "$@" $opts "$testfile" 2> "$out" > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" $opts -C "$testfile" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "$testfile" "$out" "$exebase" > /dev/null printf 'pass\n' -printf 'Running %s error file %s through cat...' "$d" "$t" +printf 'Running %s error file %s through cat with clamping...' "$d" "$t" + +cat "$testfile" 2> /dev/null | "$exe" "$@" $opts -c 2> "$out" > /dev/null +err="$?" + +checkerrtest "$d" "$err" "$testfile" "$out" "$exebase" + +printf 'pass\n' + +printf 'Running %s error file %s through cat without clamping...' "$d" "$t" -cat "$testfile" | "$exe" "$@" $opts 2> "$out" > /dev/null +cat "$testfile" 2> /dev/null | "$exe" "$@" $opts -C 2> "$out" > /dev/null err="$?" -checkcrash "$d" "$err" "$testfile" +checkerrtest "$d" "$err" "$testfile" "$out" "$exebase" printf 'pass\n' diff --git a/contrib/bc/tests/errors.sh b/contrib/bc/tests/errors.sh index 4acc978b9e5..47053f9c7b4 100755 --- a/contrib/bc/tests/errors.sh +++ b/contrib/bc/tests/errors.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -36,20 +36,33 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} -# Command-line processing. -if [ "$#" -eq 0 ]; then +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi printf 'usage: %s dir [exec args...]\n' "$script" exit 1 +} + +# Command-line processing. +if [ "$#" -eq 0 ]; then + usage "Not enough arguments" else d="$1" shift + check_d_arg "$d" fi if [ "$#" -lt 1 ]; then exe="$testdir/../bin/$d" + check_exec_arg "$exe" else exe="$1" shift + check_exec_arg "$exe" fi # I use these, so unset them to make the tests work. @@ -85,12 +98,12 @@ fi printf 'Running %s command-line error tests...' "$d" -printf '%s\n' "$halt" | "$exe" "$@" -e "1+1" -f- -e "2+2" 2> "$out" > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -e "1+1" -f- -e "2+2" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "command-line -e test" "$out" "$exebase" -printf '%s\n' "$halt" | "$exe" "$@" -e "1+1" -f- -f "$testdir/$d/decimal.txt" 2> "$out" > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -e "1+1" -f- -f "$testdir/$d/decimal.txt" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "command-line -f test" "$out" "$exebase" @@ -110,7 +123,7 @@ for testfile in $testdir/$d/*errors.txt; do # Just test warnings. line="last" - printf '%s\n' "$line" | "$exe" "$@" "-lw" 2> "$out" > /dev/null + printf '%s\n' "$line" 2> /dev/null | "$exe" "$@" "-lw" 2> "$out" > /dev/null err="$?" if [ "$err" -ne 0 ]; then @@ -137,7 +150,7 @@ for testfile in $testdir/$d/*errors.txt; do rm -f "$out" - printf '%s\n' "$line" | "$exe" "$@" "$options" 2> "$out" > /dev/null + printf '%s\n' "$line" 2> /dev/null | "$exe" "$@" "$options" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "$line" "$out" "$exebase" diff --git a/contrib/bc/tests/extra_required.txt b/contrib/bc/tests/extra_required.txt index e36d95a1305..038e6775d64 100644 --- a/contrib/bc/tests/extra_required.txt +++ b/contrib/bc/tests/extra_required.txt @@ -1,7 +1,9 @@ engineering lib2 +fib places rand +rand_limits scientific shift trunc diff --git a/contrib/bc/tests/history.py b/contrib/bc/tests/history.py index 17006c93ef2..a3b722386a6 100755 --- a/contrib/bc/tests/history.py +++ b/contrib/bc/tests/history.py @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -126,9 +126,9 @@ def write_str(child, s): # Check the bc banner. # @param child The child process. def bc_banner(child): - bc_banner1 = "bc [0-9]+\.[0-9]+\.[0-9]+\r\n" - bc_banner2 = "Copyright \(c\) 2018-[2-9][0-9][0-9][0-9] Gavin D. Howard and contributors\r\n" - bc_banner3 = "Report bugs at: https://git.yzena.com/gavin/bc\r\n\r\n" + bc_banner1 = "bc [0-9]+\\.[0-9]+\\.[0-9]+\r\n" + bc_banner2 = "Copyright \\(c\\) 2018-[2-9][0-9][0-9][0-9] Gavin D. Howard and contributors\r\n" + bc_banner3 = "Report bugs at: https://git.gavinhoward.com/gavin/bc\r\n\r\n" bc_banner4 = "This is free software with ABSOLUTELY NO WARRANTY.\r\n\r\n" expect(child, bc_banner1) expect(child, bc_banner2) @@ -251,9 +251,9 @@ def test_sigint_sigquit(exe, args, env): try: send(child, "\t") - expect(child, " ") + expect(child, "\t") send(child, "\x03") - send(child, "\x1c") + # send(child, "\x1c") wait(child) except pexpect.TIMEOUT: traceback.print_tb(sys.exc_info()[2]) @@ -282,8 +282,11 @@ def test_eof(exe, args, env): child = pexpect.spawn(exe, args=args, env=env) try: - send(child, "\t") - expect(child, " ") + send(child, "123") + expect(child, "123") + send(child, "\x01") + send(child, "\x04") + send(child, "\x04") send(child, "\x04") wait(child) except pexpect.TIMEOUT: @@ -317,7 +320,7 @@ def test_sigint(exe, args, env): try: send(child, "\t") - expect(child, " ") + expect(child, "\t") send(child, "\x03") wait(child) except pexpect.TIMEOUT: @@ -352,7 +355,7 @@ def test_sigtstp(exe, args, env): try: send(child, "\t") - expect(child, " ") + expect(child, "\t") send(child, "\x13") time.sleep(1) if not child.isalive(): @@ -392,7 +395,7 @@ def test_sigstop(exe, args, env): try: send(child, "\t") - expect(child, " ") + expect(child, "\t") send(child, "\x14") time.sleep(1) if not child.isalive(): @@ -675,7 +678,7 @@ def test_bc7(exe, args, env): send(child, "\x1b[0;4\x1b[0A") send(child, "\n") expect(child, prompt) - send(child, " ") + send(child, "\t") send(child, "\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb\x1bb") send(child, "\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf\x1bf") send(child, "\n") @@ -1044,6 +1047,7 @@ def test_dc3(exe, args, env): test_dc_utf8_1, test_dc_utf8_2, test_dc_utf8_3, + test_dc_utf8_4, test_sigint_sigquit, test_eof, test_sigint, diff --git a/contrib/bc/tests/history.sh b/contrib/bc/tests/history.sh index 92db985a4f8..d06d3c6af10 100755 --- a/contrib/bc/tests/history.sh +++ b/contrib/bc/tests/history.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -33,7 +33,16 @@ testdir=$(dirname "$script") . "$testdir/../scripts/functions.sh" -# usage: history.sh dir -a|idx [exe args...] +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s dir -a|idx [exe args...]\n' "$script" + exit 1 +} # If Python does not exist, then just skip. py=$(command -v python3) @@ -51,9 +60,14 @@ if [ "$err" -ne 0 ]; then fi fi +if [ "$#" -lt 2 ]; then + usage "Not enough arguments; expect 2 arguments" +fi + # d is "bc" or "dc" d="$1" shift +check_d_arg "$d" # idx is either an index of the test to run or "-a". If it is "-a", then all # tests are run. @@ -65,9 +79,11 @@ if [ "$#" -gt 0 ]; then # exe is the executable to run. exe="$1" shift + check_exec_arg "$exe" else exe="$testdir/../bin/$d" + check_exec_arg "$exe" fi if [ "$d" = "bc" ]; then @@ -92,7 +108,7 @@ for i in $(seq "$st" "$idx"); do printf 'Running %s history test %d...' "$d" "$i" - for j in $(seq 1 3); do + for j in $(seq 1 5); do "$py" "$testdir/history.py" "$d" "$i" "$exe" "$@" err="$?" diff --git a/contrib/bc/tests/other.sh b/contrib/bc/tests/other.sh index bd001464184..1012fe919de 100755 --- a/contrib/bc/tests/other.sh +++ b/contrib/bc/tests/other.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -36,24 +36,39 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s dir extra_math [exec args...]\n' "$script" + exit 1 +} + # Command-line processing. if [ "$#" -ge 2 ]; then d="$1" shift + check_d_arg "$d" extra_math="$1" shift + check_bool_arg "$extra_math" else - err_exit "usage: $script dir extra_math [exec args...]" 1 + usage "Not enough arguments; need 2" fi if [ "$#" -lt 1 ]; then exe="$testdir/../bin/$d" + check_exec_arg "$exe" else exe="$1" shift + check_exec_arg "$exe" fi if [ "$d" = "bc" ]; then @@ -62,6 +77,8 @@ else halt="q" fi +mkdir -p "$outputdir" + # For tests later. num=100000000000000000000000000000000000000000000000000000000000000000000000000000 num2="$num" @@ -95,14 +112,14 @@ set +e printf '\nRunning %s quit test...' "$d" -printf '%s\n' "$halt" | "$exe" "$@" > /dev/null 2>&1 +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" > /dev/null 2>&1 checktest_retcode "$d" "$?" "quit" # bc has two halt or quit commands, so test the second as well. if [ "$d" = bc ]; then - printf '%s\n' "quit" | "$exe" "$@" > /dev/null 2>&1 + printf '%s\n' "quit" 2> /dev/null | "$exe" "$@" > /dev/null 2>&1 checktest_retcode "$d" "$?" quit @@ -125,11 +142,11 @@ if [ "$d" = "bc" ]; then export BC_ENV_ARGS=" '-l' '' -q" - printf 's(.02893)\n' | "$exe" "$@" > /dev/null + printf 's(.02893)\n' 2> /dev/null | "$exe" "$@" > /dev/null checktest_retcode "$d" "$?" "environment var" - "$exe" "$@" -e 4 > /dev/null + printf 'halt\n' 2> /dev/null | "$exe" "$@" -e 4 > /dev/null err="$?" checktest_retcode "$d" "$?" "environment var" @@ -143,7 +160,7 @@ if [ "$d" = "bc" ]; then redefine_res="$outputdir/bc_outputs/redefine.txt" redefine_out="$outputdir/bc_outputs/redefine_results.txt" - outdir=$(dirname "$easter_out") + outdir=$(dirname "$redefine_out") if [ ! -d "$outdir" ]; then mkdir -p "$outdir" @@ -151,17 +168,20 @@ if [ "$d" = "bc" ]; then printf '5\n0\n' > "$redefine_res" - "$exe" "$@" --redefine=print -e 'define print(x) { x }' -e 'print(5)' > "$redefine_out" + printf 'halt\n' 2> /dev/null | "$exe" "$@" --redefine=print -e 'define print(x) { x }' -e 'print(5)' > "$redefine_out" + err="$?" checktest "$d" "$err" "keyword redefinition" "$redefine_res" "$redefine_out" - "$exe" "$@" -r "abs" -r "else" -e 'abs = 5;else = 0' -e 'abs;else' > "$redefine_out" + printf 'halt\n' 2> /dev/null | "$exe" "$@" -r "abs" -r "else" -e 'abs = 5;else = 0' -e 'abs;else' > "$redefine_out" + err="$?" checktest "$d" "$err" "keyword redefinition" "$redefine_res" "$redefine_out" if [ "$extra_math" -ne 0 ]; then - "$exe" "$@" -lr abs -e "perm(5, 1)" -e "0" > "$redefine_out" + printf 'halt\n' 2> /dev/null | "$exe" "$@" -lr abs -e "perm(5, 1)" -e "0" > "$redefine_out" + err="$?" checktest "$d" "$err" "keyword not redefined in builtin library" "$redefine_res" "$redefine_out" @@ -178,13 +198,60 @@ if [ "$d" = "bc" ]; then checkerrtest "$d" "$err" "Keyword redefinition error without BC_REDEFINE_KEYWORDS" "$redefine_out" "$d" printf 'pass\n' + printf 'Running multiline comment expression file test...' + + multiline_expr_res="" + multiline_expr_out="$outputdir/bc_outputs/multiline_expr_results.txt" + + # tests/bc/misc1.txt happens to have a multiline comment in it. + printf 'halt\n' 2> /dev/null | "$exe" "$@" -f "$testdir/bc/misc1.txt" > "$multiline_expr_out" + err="$?" + + checktest "$d" "$err" "multiline comment in expression file" "$testdir/bc/misc1_results.txt" \ + "$multiline_expr_out" + + printf 'pass\n' + printf 'Running multiline comment expression file error test...' + + printf 'halt\n' 2> /dev/null | "$exe" "$@" -f "$testdir/bc/errors/05.txt" 2> "$multiline_expr_out" + err="$?" + + checkerrtest "$d" "$err" "multiline comment in expression file error" \ + "$multiline_expr_out" "$d" + + printf 'pass\n' + printf 'Running multiline string expression file test...' + + # tests/bc/strings.txt happens to have a multiline string in it. + printf 'halt\n' 2> /dev/null | "$exe" "$@" -f "$testdir/bc/strings.txt" > "$multiline_expr_out" + err="$?" + + checktest "$d" "$err" "multiline string in expression file" "$testdir/bc/strings_results.txt" \ + "$multiline_expr_out" + + printf 'pass\n' + printf 'Running multiline string expression file error test...' + + printf 'halt\n' 2> /dev/null | "$exe" "$@" -f "$testdir/bc/errors/16.txt" 2> "$multiline_expr_out" + err="$?" + + checkerrtest "$d" "$err" "multiline string in expression file with backslash error" \ + "$multiline_expr_out" "$d" + + printf 'halt\n' 2> /dev/null | "$exe" "$@" -f "$testdir/bc/errors/04.txt" 2> "$multiline_expr_out" + err="$?" + + checkerrtest "$d" "$err" "multiline string in expression file error" \ + "$multiline_expr_out" "$d" + + printf 'pass\n' else export DC_ENV_ARGS="'-x'" export DC_EXPR_EXIT="1" - printf '4s stuff\n' | "$exe" "$@" > /dev/null + printf '4s stuff\n' 2> /dev/null | "$exe" "$@" > /dev/null checktest_retcode "$d" "$?" "environment var" @@ -199,15 +266,15 @@ else # dc has an extra test for a case that someone found running this easter.dc # script. It went into an infinite loop, so we want to check that we did not # regress. - printf 'three\n' | cut -c1-3 > /dev/null + printf 'three\n' 2> /dev/null | cut -c1-3 > /dev/null err=$? if [ "$err" -eq 0 ]; then printf 'Running dc Easter script...' - easter_res="$outputdir/dc_outputs/easter.txt" - easter_out="$outputdir/dc_outputs/easter_results.txt" + easter_out="$outputdir/dc_outputs/easter.txt" + easter_res="$outputdir/dc_outputs/easter_results.txt" outdir=$(dirname "$easter_out") @@ -217,14 +284,44 @@ else printf '4 April 2021\n' > "$easter_res" - "$testdir/dc/scripts/easter.sh" "$exe" 2021 "$@" | cut -c1-12 > "$easter_out" + "$testdir/dc/scripts/easter.sh" "$exe" 2021 "$@" 2> /dev/null | cut -c1-12 > "$easter_out" err="$?" - checktest "$d" "$err" "Easter script" "$easter_res" "$easter_out" + checktest "$d" "$err" "Easter script" "$easter_out" "$easter_res" printf 'pass\n' fi + unset DC_ENV_ARGS + unset DC_EXPR_EXIT + + printf 'Running dc extended register command tests...' + + ext_reg_out="$outputdir/dc_outputs/ext_reg.txt" + ext_reg_res="$outputdir/dc_outputs/ext_reg_results.txt" + + outdir=$(dirname "$ext_reg_out") + + if [ ! -d "$outdir" ]; then + mkdir -p "$outdir" + fi + + printf '0\n' > "$ext_reg_res" + + printf '%s\n' "$halt" | "$exe" "$@" -e "gxpR" 2> /dev/null > "$ext_reg_out" + err="$?" + + checktest "$d" "$err" "Extended register command" "$ext_reg_out" "$ext_reg_res" + + printf '1\n' > "$ext_reg_res" + + printf '%s\n' "$halt" | "$exe" "$@" -x -e "gxpR" 2> /dev/null > "$ext_reg_out" + err="$?" + + checktest "$d" "$err" "Extended register command" "$ext_reg_out" "$ext_reg_res" + + printf 'pass\n' + fi out1="$outputdir/${d}_outputs/${d}_other.txt" @@ -235,26 +332,26 @@ printf 'Running %s line length tests...' "$d" printf '%s\n' "$numres" > "$out1" export "$line_var"=80 -printf '%s\n' "$num" | "$exe" "$@" > "$out2" +printf '%s\n' "$num" 2> /dev/null | "$exe" "$@" > "$out2" checktest "$d" "$?" "line length" "$out1" "$out2" printf '%s\n' "$num70" > "$out1" export "$line_var"=2147483647 -printf '%s\n' "$num" | "$exe" "$@" > "$out2" +printf '%s\n' "$num" 2> /dev/null | "$exe" "$@" > "$out2" checktest "$d" "$?" "line length 2" "$out1" "$out2" printf '%s\n' "$num2" > "$out1" export "$line_var"=62 -printf '%s\n' "$num" | "$exe" "$@" -L > "$out2" +printf '%s\n' "$num" 2> /dev/null | "$exe" "$@" -L > "$out2" checktest "$d" "$?" "line length 3" "$out1" "$out2" printf '0\n' > "$out1" -printf '%s\n' "$lltest" | "$exe" "$@" -L > "$out2" +printf '%s\n' "$lltest" 2> /dev/null | "$exe" "$@" -L > "$out2" checktest "$d" "$?" "line length 3" "$out1" "$out2" @@ -275,23 +372,23 @@ printf '%s\n%s\n%s\n%s\n' "$results" "$results" "$results" "$results" > "$out1" checktest "$d" "$?" "arg" "$out1" "$out2" -printf '%s\n' "$halt" | "$exe" "$@" -- "$f" "$f" "$f" "$f" > "$out2" +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -- "$f" "$f" "$f" "$f" > "$out2" checktest "$d" "$?" "arg" "$out1" "$out2" if [ "$d" = "bc" ]; then - printf '%s\n' "$halt" | "$exe" "$@" -i > /dev/null 2>&1 + printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -i > /dev/null 2>&1 fi -printf '%s\n' "$halt" | "$exe" "$@" -h > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -h > /dev/null checktest_retcode "$d" "$?" "arg" -printf '%s\n' "$halt" | "$exe" "$@" -P > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -P > /dev/null checktest_retcode "$d" "$?" "arg" -printf '%s\n' "$halt" | "$exe" "$@" -R > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -R > /dev/null checktest_retcode "$d" "$?" "arg" -printf '%s\n' "$halt" | "$exe" "$@" -v > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -v > /dev/null checktest_retcode "$d" "$?" "arg" -printf '%s\n' "$halt" | "$exe" "$@" -V > /dev/null +printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -V > /dev/null checktest_retcode "$d" "$?" "arg" out=$(printf '0.1\n-0.1\n1.1\n-1.1\n0.1\n-0.1\n') @@ -303,12 +400,12 @@ else data=$(printf '0.1pR\n_0.1pR\n1.1pR\n_1.1pR\n.1pR\n_.1pR\n') fi -printf '%s\n' "$data" | "$exe" "$@" -z > "$out2" +printf '%s\n' "$data" 2> /dev/null | "$exe" "$@" -z > "$out2" checktest "$d" "$?" "leading zero" "$out1" "$out2" if [ "$d" = "bc" ] && [ "$extra_math" -ne 0 ]; then - printf '%s\n' "$halt" | "$exe" "$@" -lz "$testdir/bc/leadingzero.txt" > "$out2" + printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" -lz "$testdir/bc/leadingzero.txt" > "$out2" checktest "$d" "$?" "leading zero script" "$testdir/bc/leadingzero_results.txt" "$out2" @@ -366,6 +463,91 @@ checkerrtest "$d" "$err" "colon long option" "$out2" "$d" printf 'pass\n' +printf 'Running %s builtin variable arg tests...' "$d" + +if [ "$extra_math" -ne 0 ]; then + + out=$(printf '14\n15\n16\n17.25\n') + printf '%s\n' "$out" > "$out1" + + if [ "$d" = "bc" ]; then + data=$(printf 's=scale;i=ibase;o=obase;t=seed@2;ibase=A;obase=A;s;i;o;t;') + else + data=$(printf 'J2@OIKAiAopRpRpRpR') + fi + + printf '%s\n' "$data" 2> /dev/null | "$exe" "$@" -S14 -I15 -O16 -E17.25 > "$out2" + checktest "$d" "$?" "builtin variable args" "$out1" "$out2" + + printf '%s\n' "$data" 2> /dev/null | "$exe" "$@" --scale=14 --ibase=15 --obase=16 --seed=17.25 > "$out2" + checktest "$d" "$?" "builtin variable long args" "$out1" "$out2" + +else + + out=$(printf '14\n15\n16\n') + printf '%s\n' "$out" > "$out1" + + if [ "$d" = "bc" ]; then + data=$(printf 's=scale;i=ibase;o=obase;ibase=A;obase=A;s;i;o;') + else + data=$(printf 'OIKAiAopRpRpR') + fi + + printf '%s\n' "$data" 2> /dev/null | "$exe" "$@" -S14 -I15 -O16 > "$out2" + checktest "$d" "$?" "builtin variable args" "$out1" "$out2" + + printf '%s\n' "$data" 2> /dev/null | "$exe" "$@" --scale=14 --ibase=15 --obase=16 > "$out2" + checktest "$d" "$?" "builtin variable long args" "$out1" "$out2" + +fi + +if [ "$d" = "bc" ]; then + + out=$(printf '100\n') + printf '%s\n' "$out" > "$out1" + + printf 'scale\n' 2> /dev/null | "$exe" "$@" -S100 -l > "$out2" + checktest "$d" "$?" "builtin variable args with math lib" "$out1" "$out2" + + printf 'scale\n' 2> /dev/null | "$exe" "$@" --scale=100 --mathlib > "$out2" + checktest "$d" "$?" "builtin variable long args with math lib" "$out1" "$out2" + + export BC_ENV_ARGS="-l" + + printf 'scale\n' 2> /dev/null | "$exe" "$@" -S100 > "$out2" + checktest "$d" "$?" "builtin variable args with math lib env arg" "$out1" "$out2" + + printf 'scale\n' 2> /dev/null | "$exe" "$@" --scale=100 > "$out2" + checktest "$d" "$?" "builtin variable long args with math lib env arg" "$out1" "$out2" + + export BC_ENV_ARGS="-S100" + + printf 'scale\n' 2> /dev/null | "$exe" "$@" -l > "$out2" + checktest "$d" "$?" "builtin variable args with math lib arg" "$out1" "$out2" + + export BC_ENV_ARGS="--scale=100" + + printf 'scale\n' 2> /dev/null | "$exe" "$@" -l > "$out2" + checktest "$d" "$?" "builtin variable long args with math lib arg" "$out1" "$out2" + +fi + +printf 'scale\n' 2> /dev/null | "$exe" "$@" --scale=18923c.rlg > /dev/null 2> "$out2" +err="$?" + +checkerrtest "$d" "$err" "invalid command-line arg for builtin variable" "$out2" "$d" + +if [ "$extra_math" -ne 0 ]; then + + printf 'seed\n' 2> /dev/null | "$exe" "$@" --seed=18923c.rlg > /dev/null 2> "$out2" + err="$?" + + checkerrtest "$d" "$err" "invalid command-line arg for seed" "$out2" "$d" + +fi + +printf 'pass\n' + printf 'Running %s directory test...' "$d" "$exe" "$@" "$testdir" > /dev/null 2> "$out2" @@ -388,7 +570,7 @@ printf 'pass\n' printf 'Running %s binary stdin test...' "$d" -cat "$bin" | "$exe" "$@" > /dev/null 2> "$out2" +cat "$bin" 2> /dev/null | "$exe" "$@" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "binary stdin" "$out2" "$d" @@ -398,7 +580,7 @@ printf 'pass\n' if [ "$d" = "bc" ]; then printf 'Running %s limits tests...' "$d" - printf 'limits\n' | "$exe" "$@" > "$out2" /dev/null 2>&1 + printf 'limits\n' 2> /dev/null | "$exe" "$@" /dev/null > "$out2" 2>&1 checktest_retcode "$d" "$?" "limits" diff --git a/contrib/bc/tests/read.sh b/contrib/bc/tests/read.sh index a1915eb271a..fd4b9b6721a 100755 --- a/contrib/bc/tests/read.sh +++ b/contrib/bc/tests/read.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -36,24 +36,37 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} -# Command-line processing. -if [ "$#" -lt 1 ]; then - printf 'usage: %s dir [exe [args...]]\n' "$0" +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s dir [exe [args...]]\n' "$script" printf 'valid dirs are:\n' printf '\n' cat "$testdir/all.txt" printf '\n' exit 1 +} + +# Command-line processing. +if [ "$#" -lt 1 ]; then + usage "Not enough arguments" fi d="$1" shift +check_d_arg "$d" if [ "$#" -gt 0 ]; then exe="$1" shift + check_exec_arg "$exe" else exe="$testdir/../bin/$d" + check_exec_arg "$exe" fi name="$testdir/$d/read.txt" @@ -61,6 +74,7 @@ results="$testdir/$d/read_results.txt" errors="$testdir/$d/read_errors.txt" out="$outputdir/${d}_outputs/read_results.txt" +multiple_res="$outputdir/${d}_outputs/read_multiple_results.txt" outdir=$(dirname "$out") # Make sure the directory exists. @@ -76,11 +90,13 @@ if [ "$d" = "bc" ]; then halt="halt" read_call="read()" read_expr="${read_call}\n5+5;" + read_multiple=$(printf '%s\n%s\n%s\n' "3" "2" "1") else options="-x" halt="q" read_call="?" read_expr="${read_call}" + read_multiple=$(printf '%spR\n%spR\n%spR\n' "3" "2" "1") fi # I use these, so unset them to make the tests work. @@ -103,6 +119,16 @@ done < "$name" printf 'pass\n' +printf 'Running %s read multiple...' "$d" + +printf '3\n2\n1\n' > "$multiple_res" + +# Run multiple read() calls. +printf '%s\n' "$read_multiple" | "$exe" "$@" "$options" -e "$read_call" -e "$read_call" -e "$read_call" > "$out" +checktest "$d" "$?" 'read multiple' "$multiple_res" "$out" + +printf 'pass\n' + printf 'Running %s read errors...' "$d" # Run read on every line. diff --git a/contrib/bc/tests/script.sh b/contrib/bc/tests/script.sh index 162437af8f2..b1346ef0990 100755 --- a/contrib/bc/tests/script.sh +++ b/contrib/bc/tests/script.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -37,49 +37,72 @@ testdir=$(dirname "${script}") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} -# Command-line processing. -if [ "$#" -lt 2 ]; then +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi printf 'usage: %s dir script [run_extra_tests] [run_stack_tests] [generate_tests] [time_tests] [exec args...]\n' "$script" exit 1 +} + +# Command-line processing. +if [ "$#" -lt 2 ]; then + usage "Not enough arguments; expect 2 arguments" fi d="$1" shift +check_d_arg "$d" + +scriptdir="$testdir/$d/scripts" f="$1" shift +check_file_arg "$scriptdir/$f" if [ "$#" -gt 0 ]; then run_extra_tests="$1" shift + check_bool_arg "$run_extra_tests" else run_extra_tests=1 + check_bool_arg "$run_extra_tests" fi if [ "$#" -gt 0 ]; then run_stack_tests="$1" shift + check_bool_arg "$run_stack_tests" else run_stack_tests=1 + check_bool_arg "$run_stack_tests" fi if [ "$#" -gt 0 ]; then generate="$1" shift + check_bool_arg "$generate" else generate=1 + check_bool_arg "$generate" fi if [ "$#" -gt 0 ]; then time_tests="$1" shift + check_bool_arg "$time_tests" else time_tests=0 + check_bool_arg "$generate" fi if [ "$#" -gt 0 ]; then exe="$1" shift + check_exec_arg "$exe" else exe="$testdir/../bin/$d" fi @@ -88,20 +111,18 @@ fi if [ "$d" = "bc" ]; then if [ "$run_stack_tests" -ne 0 ]; then - options="-lgq" + options="-lgqC" else - options="-lq" + options="-lqC" fi halt="halt" else - options="-x" + options="-xC" halt="q" fi -scriptdir="$testdir/$d/scripts" - name="${f%.*}" # We specifically want to skip this because it is handled specially. @@ -111,7 +132,7 @@ fi # Skip the tests that require extra math if we don't have it. if [ "$run_extra_tests" -eq 0 ]; then - if [ "$f" = "rand.bc" ]; then + if [ "$f" = "rand.bc" ] || [ "$f" = "root.bc" ] || [ "$f" = "i2rand.bc" ]; then printf 'Skipping %s script: %s\n' "$d" "$f" exit 0 fi @@ -154,11 +175,32 @@ elif [ "$generate" -eq 0 ]; then printf 'Skipping %s script %s\n' "$d" "$f" exit 0 else - # This sed, and the script, are to remove an incompatibility with GNU bc, - # where GNU bc is wrong. See the development manual - # (manuals/development.md#script-tests) for more information. + + set +e + + # This is to check that the command exists. If not, we should not try to + # generate the test. Instead, we should just skip. + command -v "$d" 1>/dev/null 2>&1 + err="$?" + + set -e + + if [ "$err" -ne 0 ]; then + printf 'Could not find %s to generate results; skipping %s script %s\n' "$d" "$d" "$f" + exit 0 + fi + printf 'Generating %s results...' "$f" - printf '%s\n' "$halt" | "$d" "$s" | sed -n -f "$testdir/script.sed" > "$results" + + # This particular test needs to be generated straight. + if [ "$d" = "dc" ] && [ "$f" = "stream.dc" ]; then + printf '%s\n' "$halt" 2> /dev/null | "$d" "$s" > "$results" + else + # This sed, and the script, are to remove an incompatibility with GNU + # bc, where GNU bc is wrong. See the development manual + # (manuals/development.md#script-tests) for more information. + printf '%s\n' "$halt" 2> /dev/null | "$d" "$s" | sed -n -f "$testdir/script.sed" > "$results" + fi printf 'done\n' res="$results" fi @@ -170,11 +212,11 @@ printf 'Running %s script %s...' "$d" "$f" # Yes this is poor timing, but it works. if [ "$time_tests" -ne 0 ]; then printf '\n' - printf '%s\n' "$halt" | /usr/bin/time -p "$exe" "$@" $options "$s" > "$out" + printf '%s\n' "$halt" 2> /dev/null | /usr/bin/time -p "$exe" "$@" $options "$s" > "$out" err="$?" printf '\n' else - printf '%s\n' "$halt" | "$exe" "$@" $options "$s" > "$out" + printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" $options "$s" > "$out" err="$?" fi diff --git a/contrib/bc/tests/scripts.sh b/contrib/bc/tests/scripts.sh index 46aa7e76117..2c8af6c06df 100755 --- a/contrib/bc/tests/scripts.sh +++ b/contrib/bc/tests/scripts.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -31,6 +31,19 @@ script="$0" testdir=$(dirname "${script}") +. "$testdir/../scripts/functions.sh" + +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi + printf 'usage: %s [-n] dir [run_extra_tests] [run_stack_tests] [generate_tests] [time_tests] [exec args...]\n' "$script" + exit 1 +} + pids="" # We need to figure out if we should run stuff in parallel. @@ -39,54 +52,65 @@ pll=1 while getopts "n" opt; do case "$opt" in - n) pll=0 ; shift ; set -e ;; + n) pll=0 ; set -e ;; ?) usage "Invalid option: $opt" ;; esac done +shift $(($OPTIND - 1)) # Command-line processing. if [ "$#" -eq 0 ]; then - printf 'usage: %s [-n] dir [run_extra_tests] [run_stack_tests] [generate_tests] [time_tests] [exec args...]\n' "$script" - exit 1 + usage "Need at least 1 argument" else d="$1" shift + check_d_arg "$d" fi if [ "$#" -gt 0 ]; then run_extra_tests="$1" shift + check_bool_arg "$run_extra_tests" else run_extra_tests=1 + check_bool_arg "$run_extra_tests" fi if [ "$#" -gt 0 ]; then run_stack_tests="$1" shift + check_bool_arg "$run_stack_tests" else run_stack_tests=1 + check_bool_arg "$run_stack_tests" fi if [ "$#" -gt 0 ]; then generate="$1" shift + check_bool_arg "$generate" else generate=1 + check_bool_arg "$generate" fi if [ "$#" -gt 0 ]; then time_tests="$1" shift + check_bool_arg "$time_tests" else time_tests=0 + check_bool_arg "$time_tests" fi if [ "$#" -gt 0 ]; then exe="$1" shift + check_exec_arg "$exe" else exe="$testdir/../bin/$d" + check_exec_arg "$exe" fi scriptdir="$testdir/$d/scripts" diff --git a/contrib/bc/tests/stdin.sh b/contrib/bc/tests/stdin.sh index 69e6f2cabf3..7061e950367 100755 --- a/contrib/bc/tests/stdin.sh +++ b/contrib/bc/tests/stdin.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -37,24 +37,37 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} -# Command-line processing. -if [ "$#" -lt 1 ]; then +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi printf 'usage: %s dir [exe [args...]]\n' "$0" printf 'valid dirs are:\n' printf '\n' cat "$testdir/all.txt" printf '\n' exit 1 +} + +# Command-line processing. +if [ "$#" -lt 1 ]; then + usage "Not enough arguments" fi d="$1" shift +check_d_arg "$d" if [ "$#" -gt 0 ]; then exe="$1" shift + check_exec_arg "$exe" else exe="$testdir/../bin/$d" + check_exec_arg "$exe" fi out="$outputdir/${d}_outputs/stdin_results.txt" diff --git a/contrib/bc/tests/test.sh b/contrib/bc/tests/test.sh index 9d557a715dc..7b5916f0299 100755 --- a/contrib/bc/tests/test.sh +++ b/contrib/bc/tests/test.sh @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: BSD-2-Clause # -# Copyright (c) 2018-2021 Gavin D. Howard and contributors. +# Copyright (c) 2018-2024 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: @@ -37,19 +37,32 @@ testdir=$(dirname "$script") outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} -# Command-line processing. -if [ "$#" -lt 2 ]; then +# Just print the usage and exit with an error. This can receive a message to +# print. +# @param 1 A message to print. +usage() { + if [ $# -eq 1 ]; then + printf '%s\n\n' "$1" + fi printf 'usage: %s dir test [generate_tests] [time_tests] [exe [args...]]\n' "$0" printf 'valid dirs are:\n' printf '\n' cat "$testdir/all.txt" printf '\n' exit 1 +} + +# Command-line processing. +if [ "$#" -lt 2 ]; then + usage "Need at least 2 arguments" fi d="$1" shift +check_d_arg "$d" +# We don't use check_file_arg on the test or the result because they might be +# generated. t="$1" name="$testdir/$d/$t.txt" results="$testdir/$d/${t}_results.txt" @@ -58,22 +71,28 @@ shift if [ "$#" -gt 0 ]; then generate_tests="$1" shift + check_bool_arg "$generate_tests" else generate_tests=1 + check_bool_arg "$generate_tests" fi if [ "$#" -gt 0 ]; then time_tests="$1" shift + check_bool_arg "$time_tests" else time_tests=0 + check_bool_arg "$time_tests" fi if [ "$#" -gt 0 ]; then exe="$1" shift + check_exec_arg "$exe" else exe="$testdir/../bin/$d" + check_exec_arg "$exe" fi out="$outputdir/${d}_outputs/${t}_results.txt" @@ -119,13 +138,15 @@ fi # If the results do not exist, generate.. if [ ! -f "$results" ]; then printf 'Generating %s %s results...' "$d" "$t" - printf '%s\n' "$halt" | "$d" $options "$name" > "$results" + printf '%s\n' "$halt" 2> /dev/null | "$d" $options "$name" > "$results" printf 'done\n' fi -# We set this here because GNU dc does not have it. -if [ "$d" = "dc" ]; then - options="-x" +# We set this here because GNU bc and dc does not have these options. +if [ "$d" = "bc" ]; then + options="-lqc" +else + options="-xc" fi export $var=string @@ -136,11 +157,11 @@ printf 'Running %s %s...' "$d" "$t" if [ "$time_tests" -ne 0 ]; then printf '\n' - printf '%s\n' "$halt" | /usr/bin/time -p "$exe" "$@" $options "$name" > "$out" + printf '%s\n' "$halt" 2> /dev/null | /usr/bin/time -p "$exe" "$@" $options "$name" > "$out" err="$?" printf '\n' else - printf '%s\n' "$halt" | "$exe" "$@" $options "$name" > "$out" + printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" $options "$name" > "$out" err="$?" fi