From 07a893c8cf3a95ea21fc21c0702596fb83051e61 Mon Sep 17 00:00:00 2001 From: se Date: Tue, 7 Jul 2020 07:02:33 +0000 Subject: [PATCH] Update to release 3.1.1 This release fixes a regression from traditional bc behavior in FreeBSD with regard to "-e quit" being passed on the command line and add Spanish message catalogs. --- .gitignore | 6 + LICENSE.md | 4 - Makefile.in | 16 +- NEWS.md | 62 +- README.md | 15 +- TODO.md | 5 - configure.sh | 31 +- functions.sh | 4 +- gen/bc_help.txt | 9 +- gen/dc_help.txt | 4 +- gen/lib.bc | 4 +- gen/lib2.bc | 4 +- gen/strgen.c | 4 +- gen/strgen.sh | 4 +- include/args.h | 4 +- include/bc.h | 10 +- include/dc.h | 8 +- include/file.h | 4 +- include/history.h | 6 +- include/lang.h | 23 +- include/lex.h | 35 +- include/num.h | 16 +- include/opt.h | 4 +- include/parse.h | 5 +- include/program.h | 12 +- include/rand.h | 12 +- include/read.h | 11 +- include/status.h | 4 +- include/vector.h | 4 +- include/vm.h | 59 +- install.sh | 4 +- karatsuba.py | 7 +- link.sh | 4 +- locale_install.sh | 4 +- locale_uninstall.sh | 4 +- locales/de_DE.ISO8859-1.msg | 28 + locales/de_DE.UTF-8.msg | 28 + locales/en_US.msg | 4 +- locales/es_ES.ISO8859-1.msg | 108 ++ locales/es_ES.ISO8859-15.msg | 1 + locales/es_ES.UTF-8.msg | 4 +- locales/fr_FR.ISO8859-1.msg | 4 +- locales/fr_FR.UTF-8.msg | 4 +- locales/ja_JP.UTF-8.msg | 28 + locales/ja_JP.eucJP.msg | 28 + locales/nl_NL.ISO8859-1.msg | 28 + locales/nl_NL.UTF-8.msg | 28 + locales/pl_PL.ISO8859-2.msg | 28 + locales/pl_PL.UTF-8.msg | 28 + locales/pt_PT.ISO8859-1.msg | 4 +- locales/pt_PT.UTF-8.msg | 4 +- locales/ru_RU.CP1251.msg | 28 + locales/ru_RU.CP866.msg | 28 + locales/ru_RU.ISO8859-5.msg | 28 + locales/ru_RU.KOI8-R.msg | 28 + locales/ru_RU.UTF-8.msg | 28 + locales/zh_CN.GB18030.msg | 4 +- locales/zh_CN.GB2312.msg | 4 +- locales/zh_CN.GBK.msg | 4 +- locales/zh_CN.UTF-8.msg | 4 +- locales/zh_CN.eucCN.msg | 4 +- manpage.sh | 83 +- manuals/bc.1 | 1566 ------------------------- manuals/bc.1.md.in | 1814 +++++++++++++++++++++++++++++ manuals/bc.1.ronn | 1556 ------------------------- manuals/bc.md | 1 - manuals/bc/A.1 | 2099 ++++++++++++++++++++++++++++++++++ manuals/bc/A.1.md | 1697 +++++++++++++++++++++++++++ manuals/bc/E.1 | 1341 ++++++++++++++++++++++ manuals/bc/E.1.md | 1091 ++++++++++++++++++ manuals/bc/EH.1 | 1323 +++++++++++++++++++++ manuals/bc/EH.1.md | 1075 +++++++++++++++++ manuals/bc/EHN.1 | 1316 +++++++++++++++++++++ manuals/bc/EHN.1.md | 1067 +++++++++++++++++ manuals/bc/EHNP.1 | 1309 +++++++++++++++++++++ manuals/bc/EHNP.1.md | 1061 +++++++++++++++++ manuals/bc/EHP.1 | 1316 +++++++++++++++++++++ manuals/bc/EHP.1.md | 1069 +++++++++++++++++ manuals/bc/EN.1 | 1334 +++++++++++++++++++++ manuals/bc/EN.1.md | 1083 ++++++++++++++++++ manuals/bc/ENP.1 | 1327 +++++++++++++++++++++ manuals/bc/ENP.1.md | 1077 +++++++++++++++++ manuals/bc/EP.1 | 1334 +++++++++++++++++++++ manuals/bc/EP.1.md | 1085 ++++++++++++++++++ manuals/bc/H.1 | 2079 +++++++++++++++++++++++++++++++++ manuals/bc/H.1.md | 1680 +++++++++++++++++++++++++++ manuals/bc/HN.1 | 2072 +++++++++++++++++++++++++++++++++ manuals/bc/HN.1.md | 1672 +++++++++++++++++++++++++++ manuals/bc/HNP.1 | 2065 +++++++++++++++++++++++++++++++++ manuals/bc/HNP.1.md | 1666 +++++++++++++++++++++++++++ manuals/bc/HP.1 | 2072 +++++++++++++++++++++++++++++++++ manuals/bc/HP.1.md | 1674 +++++++++++++++++++++++++++ manuals/bc/N.1 | 2092 +++++++++++++++++++++++++++++++++ manuals/bc/N.1.md | 1689 +++++++++++++++++++++++++++ manuals/bc/NP.1 | 2085 +++++++++++++++++++++++++++++++++ manuals/bc/NP.1.md | 1683 +++++++++++++++++++++++++++ manuals/bc/P.1 | 2092 +++++++++++++++++++++++++++++++++ manuals/bc/P.1.md | 1691 +++++++++++++++++++++++++++ manuals/build.md | 5 +- manuals/dc.1 | 951 --------------- manuals/dc.1.md.in | 1257 ++++++++++++++++++++ manuals/dc.1.ronn | 1103 ------------------ manuals/dc.md | 1 - manuals/dc/A.1 | 1406 +++++++++++++++++++++++ manuals/dc/A.1.md | 1194 +++++++++++++++++++ manuals/dc/E.1 | 1202 +++++++++++++++++++ manuals/dc/E.1.md | 1030 +++++++++++++++++ manuals/dc/EH.1 | 1187 +++++++++++++++++++ manuals/dc/EH.1.md | 1017 ++++++++++++++++ manuals/dc/EHN.1 | 1183 +++++++++++++++++++ manuals/dc/EHN.1.md | 1012 ++++++++++++++++ manuals/dc/EHNP.1 | 1176 +++++++++++++++++++ manuals/dc/EHNP.1.md | 1007 ++++++++++++++++ manuals/dc/EHP.1 | 1180 +++++++++++++++++++ manuals/dc/EHP.1.md | 1012 ++++++++++++++++ manuals/dc/EN.1 | 1198 +++++++++++++++++++ manuals/dc/EN.1.md | 1025 +++++++++++++++++ manuals/dc/ENP.1 | 1191 +++++++++++++++++++ manuals/dc/ENP.1.md | 1020 +++++++++++++++++ manuals/dc/EP.1 | 1195 +++++++++++++++++++ manuals/dc/EP.1.md | 1025 +++++++++++++++++ manuals/dc/H.1 | 1391 ++++++++++++++++++++++ manuals/dc/H.1.md | 1181 +++++++++++++++++++ manuals/dc/HN.1 | 1387 ++++++++++++++++++++++ manuals/dc/HN.1.md | 1176 +++++++++++++++++++ manuals/dc/HNP.1 | 1380 ++++++++++++++++++++++ manuals/dc/HNP.1.md | 1171 +++++++++++++++++++ manuals/dc/HP.1 | 1384 ++++++++++++++++++++++ manuals/dc/HP.1.md | 1176 +++++++++++++++++++ manuals/dc/N.1 | 1402 +++++++++++++++++++++++ manuals/dc/N.1.md | 1189 +++++++++++++++++++ manuals/dc/NP.1 | 1395 ++++++++++++++++++++++ manuals/dc/NP.1.md | 1184 +++++++++++++++++++ manuals/dc/P.1 | 1399 ++++++++++++++++++++++ manuals/dc/P.1.md | 1189 +++++++++++++++++++ release.sh | 9 +- src/args.c | 8 +- src/bc/bc.c | 4 +- src/bc/lex.c | 4 +- src/bc/parse.c | 56 +- src/data.c | 81 +- src/dc/dc.c | 4 +- src/dc/lex.c | 4 +- src/dc/parse.c | 6 +- src/file.c | 4 +- src/history/history.c | 12 +- src/lang.c | 41 +- src/lex.c | 4 +- src/main.c | 4 +- src/num.c | 9 +- src/opt.c | 8 +- src/parse.c | 25 +- src/program.c | 218 ++-- src/rand/rand.c | 10 +- src/read.c | 29 +- src/vector.c | 74 +- src/vm.c | 123 +- tests/afl.py | 4 +- tests/all.sh | 8 +- tests/bc/errors/23.txt | Bin 0 -> 5141 bytes tests/bc/errors/24.txt | 9 + tests/bc/misc2.txt | 1 + tests/bc/misc2_results.txt | 5 + tests/bc/timeconst.sh | 2 - tests/dc/errors/25.txt | 7 + tests/dc/errors/26.txt | 222 ++++ tests/dc/errors/27.txt | 2 + tests/dc/errors/28.txt | 2 + tests/dc/errors/29.txt | 20 + tests/dc/stdin.txt | 1002 ++++++++++++++++ tests/dc/stdin_results.txt | 1001 ++++++++++++++++ tests/errors.sh | 4 +- tests/radamsa.sh | 4 +- tests/randmath.py | 4 +- tests/read.sh | 4 +- tests/script.sh | 4 +- tests/scripts.sh | 4 +- tests/stdin.sh | 4 +- tests/test.sh | 4 +- 179 files changed, 94227 insertions(+), 5673 deletions(-) delete mode 100644 TODO.md create mode 100644 locales/es_ES.ISO8859-1.msg create mode 120000 locales/es_ES.ISO8859-15.msg delete mode 100644 manuals/bc.1 create mode 100644 manuals/bc.1.md.in delete mode 100644 manuals/bc.1.ronn delete mode 120000 manuals/bc.md create mode 100644 manuals/bc/A.1 create mode 100644 manuals/bc/A.1.md create mode 100644 manuals/bc/E.1 create mode 100644 manuals/bc/E.1.md create mode 100644 manuals/bc/EH.1 create mode 100644 manuals/bc/EH.1.md create mode 100644 manuals/bc/EHN.1 create mode 100644 manuals/bc/EHN.1.md create mode 100644 manuals/bc/EHNP.1 create mode 100644 manuals/bc/EHNP.1.md create mode 100644 manuals/bc/EHP.1 create mode 100644 manuals/bc/EHP.1.md create mode 100644 manuals/bc/EN.1 create mode 100644 manuals/bc/EN.1.md create mode 100644 manuals/bc/ENP.1 create mode 100644 manuals/bc/ENP.1.md create mode 100644 manuals/bc/EP.1 create mode 100644 manuals/bc/EP.1.md create mode 100644 manuals/bc/H.1 create mode 100644 manuals/bc/H.1.md create mode 100644 manuals/bc/HN.1 create mode 100644 manuals/bc/HN.1.md create mode 100644 manuals/bc/HNP.1 create mode 100644 manuals/bc/HNP.1.md create mode 100644 manuals/bc/HP.1 create mode 100644 manuals/bc/HP.1.md create mode 100644 manuals/bc/N.1 create mode 100644 manuals/bc/N.1.md create mode 100644 manuals/bc/NP.1 create mode 100644 manuals/bc/NP.1.md create mode 100644 manuals/bc/P.1 create mode 100644 manuals/bc/P.1.md delete mode 100644 manuals/dc.1 create mode 100644 manuals/dc.1.md.in delete mode 100644 manuals/dc.1.ronn delete mode 120000 manuals/dc.md create mode 100644 manuals/dc/A.1 create mode 100644 manuals/dc/A.1.md create mode 100644 manuals/dc/E.1 create mode 100644 manuals/dc/E.1.md create mode 100644 manuals/dc/EH.1 create mode 100644 manuals/dc/EH.1.md create mode 100644 manuals/dc/EHN.1 create mode 100644 manuals/dc/EHN.1.md create mode 100644 manuals/dc/EHNP.1 create mode 100644 manuals/dc/EHNP.1.md create mode 100644 manuals/dc/EHP.1 create mode 100644 manuals/dc/EHP.1.md create mode 100644 manuals/dc/EN.1 create mode 100644 manuals/dc/EN.1.md create mode 100644 manuals/dc/ENP.1 create mode 100644 manuals/dc/ENP.1.md create mode 100644 manuals/dc/EP.1 create mode 100644 manuals/dc/EP.1.md create mode 100644 manuals/dc/H.1 create mode 100644 manuals/dc/H.1.md create mode 100644 manuals/dc/HN.1 create mode 100644 manuals/dc/HN.1.md create mode 100644 manuals/dc/HNP.1 create mode 100644 manuals/dc/HNP.1.md create mode 100644 manuals/dc/HP.1 create mode 100644 manuals/dc/HP.1.md create mode 100644 manuals/dc/N.1 create mode 100644 manuals/dc/N.1.md create mode 100644 manuals/dc/NP.1 create mode 100644 manuals/dc/NP.1.md create mode 100644 manuals/dc/P.1 create mode 100644 manuals/dc/P.1.md create mode 100644 tests/bc/errors/23.txt create mode 100644 tests/bc/errors/24.txt create mode 100644 tests/dc/errors/25.txt create mode 100644 tests/dc/errors/26.txt create mode 100644 tests/dc/errors/27.txt create mode 100644 tests/dc/errors/28.txt create mode 100644 tests/dc/errors/29.txt diff --git a/.gitignore b/.gitignore index e63cd78d13b0..85681bf6b48e 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,12 @@ bc.old .math.txt .results.txt .ops.txt +manuals/bc.1 +manuals/bc.1.ronn +manuals/bc.1.md +manuals/dc.1 +manuals/dc.1.ronn +manuals/dc.1.md gen/strgen lib.c lib2.c diff --git a/LICENSE.md b/LICENSE.md index 07daaa9dda22..1681a053e0de 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -2,8 +2,6 @@ Copyright (c) 2018-2020 Gavin D. Howard -All rights reserved. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -35,8 +33,6 @@ Copyright (c) 2010-2013, Pieter Noordhuis
Copyright (c) 2018 rain-1
Copyright (c) 2018-2020, Gavin D. Howard -All rights reserved. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/Makefile.in b/Makefile.in index 47e94d9533b3..38a3d5ea964d 100644 --- a/Makefile.in +++ b/Makefile.in @@ -1,8 +1,8 @@ # +# SPDX-License-Identifier: BSD-2-Clause +# # Copyright (c) 2018-2020 Gavin D. Howard and contributors. # -# All rights reserved. -# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # @@ -29,7 +29,7 @@ # .POSIX: -VERSION = 3.0.2 +VERSION = 3.1.1 SRC = %%SRC%% OBJ = %%OBJ%% @@ -105,10 +105,10 @@ DC_EXEC = $(BIN)/$(EXEC_PREFIX)$(DC) MANUALS = manuals BC_MANPAGE_NAME = $(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX).1 BC_MANPAGE = $(MANUALS)/$(BC).1 -BC_RONN = $(BC_MANPAGE).ronn +BC_MD = $(BC_MANPAGE).md DC_MANPAGE_NAME = $(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX).1 DC_MANPAGE = $(MANUALS)/$(DC).1 -DC_RONN = $(DC_MANPAGE).ronn +DC_MD = $(DC_MANPAGE).md MANPAGE_INSTALL_ARGS = -Dm644 @@ -270,8 +270,8 @@ extra_math: @printf '%s' "$(BC_ENABLE_EXTRA_MATH)" manpages: - $(MANPAGE) $(BC_RONN) $(BC_MANPAGE) - $(MANPAGE) $(DC_RONN) $(DC_MANPAGE) + $(MANPAGE) bc + $(MANPAGE) dc clean_gen: @$(RM) -f $(GEN_EXEC) @@ -295,6 +295,8 @@ clean:%%CLEAN_PREREQS%% clean_config: clean @printf 'Cleaning config...\n' @$(RM) -f Makefile + @$(RM) -f $(BC_MD) $(DC_MD) + @$(RM) -f $(BC_MANPAGE) $(DC_MANPAGE) clean_coverage: @printf 'Cleaning coverage files...\n' diff --git a/NEWS.md b/NEWS.md index 55b14c4e49b8..ef106b0460f0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,54 @@ # News +## 3.1.1 + +This is a production release that adds two Spanish locales. Users do ***NOT*** +need to upgrade, unless they want those locales. + +## 3.1.0 + +This is a production release that adjusts one behavior, fixes eight bugs, and +improves manpages for FreeBSD. Because this release fixes bugs, **users and +package maintainers should update to this version as soon as possible**. + +The behavior that was adjusted was how code from the `-e` and `-f` arguments +(and equivalents) were executed. They used to be executed as one big chunk, but +in this release, they are now executed line-by-line. + +The first bug fix in how output to `stdout` was handled in `SIGINT`. If a +`SIGINT` came in, the `stdout` buffer was not correctly flushed. In fact, a +clean-up function was not getting called. This release fixes that bug. + +The second bug is in how `dc` handled input from `stdin`. This affected `bc` as +well since it was a mishandling of the `stdin` buffer. + +The third fixed bug was that `bc` and `dc` could `abort()` (in debug mode) when +receiving a `SIGTERM`. This one was a race condition with pushing and popping +items onto and out of vectors. + +The fourth bug fixed was that `bc` could leave extra items on the stack and +thus, not properly clean up some memory. (The memory would still get +`free()`'ed, but it would not be `free()`'ed when it could have been.) + +The next two bugs were bugs in `bc`'s parser that caused crashes when executing +the resulting code. + +The last two bugs were crashes in `dc` that resulted from mishandling of +strings. + +The manpage improvement was done by switching from [ronn][20] to [Pandoc][21] to +generate manpages. Pandoc generates much cleaner manpages and doesn't leave +blank lines where they shouldn't be. + +## 3.0.3 + +This is a production release that adds one new feature: specific manpages. + +Before this release, `bc` and `dc` only used one manpage each that referred to +various build options. This release changes it so there is one manpage set per +relevant build type. Each manual only has information about its particular +build, and `configure.sh` selects the correct set for install. + ## 3.0.2 This is a production release that adds `utf8` locale symlinks and removes an @@ -32,8 +81,9 @@ global ones that are already installed, so it will use the previous ones while running tests during install. **If `bc` segfaults while running arg tests when updating, it is because the global locale files have not been replaced. Make sure to either prevent the test suite from running on update or remove the old -locale files before updating.** Once this is done, `bc` should install without -problems.* +locale files before updating.** (Removing the locale files can be done with +`make uninstall` or by running the `locale_uninstall.sh` script.) Once this is +done, `bc` should install without problems.* *Second, **the option to build without signal support has been removed**. See below for the reasons why.* @@ -811,14 +861,16 @@ not thoroughly tested. [6]: ./configure.sh [7]: https://github.com/rain-1/linenoise-mob [8]: https://github.com/antirez/linenoise -[9]: ./manuals/bc.1.ronn -[10]: ./manuals/dc.1.ronn +[9]: ./manuals/bc/A.1.md +[10]: ./manuals/dc/A.1.md [11]: https://scan.coverity.com/projects/gavinhoward-bc [12]: ./locale_install.sh [13]: ./manuals/build.md [14]: https://github.com/stesser [15]: https://github.com/bugcrazy -[16]: ./manuals/bc.1.ronn#extended-library +[16]: ./manuals/bc/A.1.md#extended-library [17]: https://github.com/skeeto/optparse [18]: https://www.deepl.com/translator [19]: ./manuals/benchmarks.md +[20]: https://github.com/apjanke/ronn-ng +[21]: https://pandoc.org/ diff --git a/README.md b/README.md index 955774dc79cc..f2165e554221 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This is an implementation of the [POSIX `bc` calculator][12] that implements [GNU `bc`][1] extensions, as well as the period (`.`) extension for the BSD flavor of `bc`. -For more information, see this `bc`'s [full manual][2]. +For more information, see this `bc`'s full manual. This `bc` also includes an implementation of `dc` in the same binary, accessible via a symbolic link, which implements all FreeBSD and GNU extensions. (If a @@ -19,7 +19,7 @@ standalone `dc` binary is desired, `bc` can be copied and renamed to `dc`.) The `!` command is omitted; I believe this poses security concerns and that such functionality is unnecessary. -For more information, see the `dc`'s [full manual][3]. +For more information, see the `dc`'s full manual. This `bc` is Free and Open Source Software (FOSS). It is offered under the BSD 2-clause License. Full license text may be found in the [`LICENSE.md`][4] file. @@ -39,7 +39,7 @@ Systems that are known to work: * OpenBSD * NetBSD * Mac OSX -* Solaris +* Solaris* (as long as the Solaris version supports POSIX 2008) * AIX Please submit bug reports if this `bc` does not build out of the box on any @@ -261,6 +261,10 @@ Other projects based on this bc are: * [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, and the maintainers of the package will contact me if + necessary. + ## Language This `bc` is written in pure ISO C99, using POSIX 2008 APIs. @@ -293,7 +297,7 @@ Files: locale_install.sh A script to install locales, if desired. locale_uninstall.sh A script to uninstall locales. Makefile.in The Makefile template. - manpage.sh Script to generate man pages from ronn files. + manpage.sh Script to generate man pages from markdown files. NOTICE.md List of contributors and copyright owners. RELEASE.md A checklist for making a release (maintainer use only). release.sh A script to test for release (maintainer use only). @@ -309,8 +313,6 @@ Folders: tests All tests. [1]: https://www.gnu.org/software/bc/ -[2]: ./manuals/bc.md -[3]: ./manuals/dc.md [4]: ./LICENSE.md [5]: ./manuals/build.md [6]: https://pkg.musl.cc/bc/ @@ -330,3 +332,4 @@ Folders: [20]: https://git.yzena.com/gavin/bc [21]: https://gavinhoward.com/2020/04/i-am-moving-away-from-github/ [22]: https://www.deepl.com/translator +[23]: https://github.com/freebsd/freebsd/tree/master/contrib/bc diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 5e9b0617c416..000000000000 --- a/TODO.md +++ /dev/null @@ -1,5 +0,0 @@ -# TODO - -* Rerun benchmarks. -* Redo executable size (with static binaries). -* Redo Karatsuba number and update NEWS if necessary. diff --git a/configure.sh b/configure.sh index 095fef57ca2b..431af61583a7 100755 --- a/configure.sh +++ b/configure.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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: @@ -808,6 +808,28 @@ else fi fi +manpage_args="" + +if [ "$extra_math" -eq 0 ]; then + manpage_args="E" +fi + +if [ "$hist" -eq 0 ]; then + manpage_args="${manpage_args}H" +fi + +if [ "$nls" -eq 0 ]; then + manpage_args="${manpage_args}N" +fi + +if [ "$prompt" -eq 0 ]; then + manpage_args="${manpage_args}P" +fi + +if [ "$manpage_args" = "" ]; then + manpage_args="A" +fi + # Print out the values; this is for debugging. if [ "$bc" -ne 0 ]; then printf 'Building bc\n' @@ -924,4 +946,9 @@ printf '%s\n' "$contents" > "$scriptdir/Makefile" cd "$scriptdir" +cp -f manuals/bc/$manpage_args.1.md manuals/bc.1.md +cp -f manuals/bc/$manpage_args.1 manuals/bc.1 +cp -f manuals/dc/$manpage_args.1.md manuals/dc.1.md +cp -f manuals/dc/$manpage_args.1 manuals/dc.1 + make clean > /dev/null diff --git a/functions.sh b/functions.sh index 254e81c5167c..96afb059c951 100755 --- a/functions.sh +++ b/functions.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/gen/bc_help.txt b/gen/bc_help.txt index 648ed2526051..e013251b16bb 100644 --- a/gen/bc_help.txt +++ b/gen/bc_help.txt @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -58,6 +58,8 @@ This bc has three differences to the GNU bc: 3) This bc has many more extensions than the GNU bc does. For details, see the man page. +This bc also implements the dot (.) extension of the BSD bc. + Options: -e expr --expression=expr @@ -94,6 +96,9 @@ Options: e(expr) = raises e to the power of expr j(n, x) = Bessel function of integer order n of x + This bc may load more functions with these options. See the manpage for + details. + -P --no-prompt Disable the prompt in interactive mode. diff --git a/gen/dc_help.txt b/gen/dc_help.txt index 18e990d9f7bb..6a26ece26488 100644 --- a/gen/dc_help.txt +++ b/gen/dc_help.txt @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/gen/lib.bc b/gen/lib.bc index 8b60cb97071d..93ac29546beb 100644 --- a/gen/lib.bc +++ b/gen/lib.bc @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/gen/lib2.bc b/gen/lib2.bc index 6b10af151385..98baffdd30f6 100644 --- a/gen/lib2.bc +++ b/gen/lib2.bc @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/gen/strgen.c b/gen/strgen.c index d741c1a793d0..f4c4b51d1248 100644 --- a/gen/strgen.c +++ b/gen/strgen.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/gen/strgen.sh b/gen/strgen.sh index 24d560991f8d..f389c12c0579 100755 --- a/gen/strgen.sh +++ b/gen/strgen.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/include/args.h b/include/args.h index af851e3092ea..f2bc2d6bab05 100644 --- a/include/args.h +++ b/include/args.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/include/bc.h b/include/bc.h index dd4fa435cf72..ade18c828c28 100644 --- a/include/bc.h +++ b/include/bc.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -130,13 +130,13 @@ void bc_lex_token(BcLex *l); #define BC_PARSE_LEAF(prev, bin_last, rparen) \ (!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev))) -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_INST_VAR(t) \ ((t) >= BC_INST_VAR && (t) <= BC_INST_SEED && (t) != BC_INST_ARRAY) -#else // BC_ENABLE_EXTRA_MATH +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_INST_VAR(t) \ ((t) >= BC_INST_VAR && (t) <= BC_INST_SCALE && (t) != BC_INST_ARRAY) -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_PREV_PREFIX(p) \ ((p) >= BC_INST_NEG && (p) <= BC_INST_BOOL_NOT) diff --git a/include/dc.h b/include/dc.h index 1155307d5c43..07af135bc38f 100644 --- a/include/dc.h +++ b/include/dc.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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,10 +36,6 @@ #ifndef BC_DC_H #define BC_DC_H -#ifndef DC_ENABLE_RAND -#define DC_ENABLE_RAND (1) -#endif // DC_ENABLE_RAND - #if DC_ENABLED #include diff --git a/include/file.h b/include/file.h index 948262b89e5f..0ba8caa80c98 100644 --- a/include/file.h +++ b/include/file.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/include/history.h b/include/history.h index 9eac69bc9db0..c632bc81a2a0 100644 --- a/include/history.h +++ b/include/history.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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,8 +47,6 @@ * Copyright (c) 2010-2016, Salvatore Sanfilippo * Copyright (c) 2010-2013, Pieter Noordhuis * - * All rights reserved. - * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: diff --git a/include/lang.h b/include/lang.h index c1b9606b8f0d..a8ab08ad9bf4 100644 --- a/include/lang.h +++ b/include/lang.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -129,6 +129,7 @@ typedef enum BcInst { BC_INST_ARRAY, #endif // BC_ENABLED + BC_INST_ZERO, BC_INST_ONE, #if BC_ENABLED @@ -137,26 +138,26 @@ typedef enum BcInst { BC_INST_IBASE, BC_INST_OBASE, BC_INST_SCALE, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_SEED, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_LENGTH, BC_INST_SCALE_FUNC, BC_INST_SQRT, BC_INST_ABS, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_IRAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_READ, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_RAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_MAXIBASE, BC_INST_MAXOBASE, BC_INST_MAXSCALE, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_MAXRAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_PRINT, BC_INST_PRINT_POP, @@ -252,9 +253,9 @@ typedef enum BcResultType { BC_RESULT_STR, - BC_RESULT_CONSTANT, BC_RESULT_TEMP, + BC_RESULT_ZERO, BC_RESULT_ONE, #if BC_ENABLED diff --git a/include/lex.h b/include/lex.h index fcc30ae53b9a..68b72a7f59bb 100644 --- a/include/lex.h +++ b/include/lex.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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,8 +46,23 @@ #define bc_lex_err(l, e) (bc_vm_error((e), (l)->line)) #define bc_lex_verr(l, e, ...) (bc_vm_error((e), (l)->line, __VA_ARGS__)) +#if BC_ENABLED + +#if DC_ENABLED #define BC_LEX_NEG_CHAR (BC_IS_BC ? '-' : '_') #define BC_LEX_LAST_NUM_CHAR (BC_IS_BC ? 'Z' : 'F') +#else // DC_ENABLED +#define BC_LEX_NEG_CHAR ('-') +#define BC_LEX_LAST_NUM_CHAR ('Z') +#endif // DC_ENABLED + +#else // BC_ENABLED + +#define BC_LEX_NEG_CHAR ('_') +#define BC_LEX_LAST_NUM_CHAR ('F') + +#endif // BC_ENABLED + #define BC_LEX_NUM_CHAR(c, pt, int_only) \ (isdigit(c) || ((c) >= 'A' && (c) <= BC_LEX_LAST_NUM_CHAR) || \ ((c) == '.' && !(pt) && !(int_only))) @@ -142,27 +157,27 @@ typedef enum BcLexType { BC_LEX_KW_IBASE, BC_LEX_KW_OBASE, BC_LEX_KW_SCALE, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_SEED, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_LENGTH, BC_LEX_KW_PRINT, BC_LEX_KW_SQRT, BC_LEX_KW_ABS, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_IRAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_QUIT, BC_LEX_KW_READ, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_RAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_MAXIBASE, BC_LEX_KW_MAXOBASE, BC_LEX_KW_MAXSCALE, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_MAXRAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ELSE, #if DC_ENABLED diff --git a/include/num.h b/include/num.h index 0b16ef844036..239daf908834 100644 --- a/include/num.h +++ b/include/num.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -110,8 +110,16 @@ typedef struct BcNum { } BcNum; #if BC_ENABLE_EXTRA_MATH + +#ifndef BC_ENABLE_RAND +#define BC_ENABLE_RAND (1) +#endif // BC_ENABLE_RAND + +#if BC_ENABLE_RAND // Forward declaration struct BcRNG; +#endif // BC_ENABLE_RAND + #endif // BC_ENABLE_EXTRA_MATH #define BC_NUM_MIN_BASE (BC_NUM_BIGDIG_C(2)) @@ -173,12 +181,12 @@ void bc_num_bigdig(const BcNum *restrict n, BcBigDig *result); void bc_num_bigdig2(const BcNum *restrict n, BcBigDig *result); void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val); -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND void bc_num_irand(const BcNum *restrict a, BcNum *restrict b, struct BcRNG *restrict rng); void bc_num_rng(const BcNum *restrict n, struct BcRNG *rng); void bc_num_createFromRNG(BcNum *restrict n, struct BcRNG *rng); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale); void bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale); diff --git a/include/opt.h b/include/opt.h index f57238571889..eb3d5959adc0 100644 --- a/include/opt.h +++ b/include/opt.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/include/parse.h b/include/parse.h index e83a3c4acf96..a568fab13e64 100644 --- a/include/parse.h +++ b/include/parse.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -110,6 +110,7 @@ void bc_parse_updateFunc(BcParse *p, size_t fidx); void bc_parse_pushName(const BcParse* p, char *name, bool var); void bc_parse_text(BcParse *p, const char *text); +extern const char bc_parse_zero[]; extern const char bc_parse_one[]; #endif // BC_PARSE_H diff --git a/include/program.h b/include/program.h index c998a5038c69..a9805fbfb316 100644 --- a/include/program.h +++ b/include/program.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -61,9 +61,9 @@ typedef struct BcProgram { BcBigDig globals[BC_PROG_GLOBALS_LEN]; BcVec globals_v[BC_PROG_GLOBALS_LEN]; -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BcRNG rng; -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BcVec results; BcVec stack; @@ -81,12 +81,15 @@ typedef struct BcProgram { BcVec arr_map; #if DC_ENABLED + BcVec strs_v; + BcVec tail_calls; BcBigDig strm; BcNum strmb; #endif // DC_ENABLED + BcNum zero; BcNum one; #if BC_ENABLED @@ -99,6 +102,7 @@ typedef struct BcProgram { BcDig strmb_num[BC_NUM_BIGDIG_LOG10]; #endif // DC_ENABLED + BcDig zero_num[BC_PROG_ONE_CAP]; BcDig one_num[BC_PROG_ONE_CAP]; } BcProgram; diff --git a/include/rand.h b/include/rand.h index fa17507276fb..3c8aafd62ade 100644 --- a/include/rand.h +++ b/include/rand.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2019 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2019 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: @@ -69,14 +69,16 @@ #ifndef BC_RAND_H #define BC_RAND_H -#if BC_ENABLE_EXTRA_MATH - #include #include #include #include +#if BC_ENABLE_EXTRA_MATH + +#if BC_ENABLE_RAND + typedef ulong (*BcRandUlong)(void*); #if BC_LONG_BIT >= 64 @@ -224,6 +226,8 @@ void bc_rand_getRands(BcRNG *r, BcRand *s1, BcRand *s2, BcRand *i1, BcRand *i2); extern const BcRandState bc_rand_multiplier; +#endif // BC_ENABLE_RAND + #endif // BC_ENABLE_EXTRA_MATH #endif // BC_RAND_H diff --git a/include/read.h b/include/read.h index 369540ede3a8..664ff983e522 100644 --- a/include/read.h +++ b/include/read.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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,8 +33,8 @@ * */ -#ifndef BC_IO_H -#define BC_IO_H +#ifndef BC_READ_H +#define BC_READ_H #include @@ -55,5 +55,6 @@ BcStatus bc_read_line(BcVec *vec, const char *prompt); void bc_read_file(const char *path, char **buf); BcStatus bc_read_chars(BcVec *vec, const char *prompt); +bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len); -#endif // BC_IO_H +#endif // BC_READ_H diff --git a/include/status.h b/include/status.h index 12155cef459d..279edfef8710 100644 --- a/include/status.h +++ b/include/status.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/include/vector.h b/include/vector.h index 3fa599b585d9..bad178eede30 100644 --- a/include/vector.h +++ b/include/vector.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/include/vm.h b/include/vm.h index 0ca20047b824..7f4359c640d3 100644 --- a/include/vm.h +++ b/include/vm.h @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -91,28 +91,64 @@ #define isatty _isatty #endif // _WIN32 +#if DC_ENABLED #define DC_FLAG_X (UINTMAX_C(1)<<0) +#endif // DC_ENABLED + +#if BC_ENABLED #define BC_FLAG_W (UINTMAX_C(1)<<1) #define BC_FLAG_S (UINTMAX_C(1)<<2) -#define BC_FLAG_Q (UINTMAX_C(1)<<3) -#define BC_FLAG_L (UINTMAX_C(1)<<4) -#define BC_FLAG_I (UINTMAX_C(1)<<5) -#define BC_FLAG_G (UINTMAX_C(1)<<6) +#define BC_FLAG_L (UINTMAX_C(1)<<3) +#define BC_FLAG_G (UINTMAX_C(1)<<4) +#endif // BC_ENABLED + +#define BC_FLAG_Q (UINTMAX_C(1)<<5) +#define BC_FLAG_I (UINTMAX_C(1)<<6) #define BC_FLAG_P (UINTMAX_C(1)<<7) #define BC_FLAG_TTYIN (UINTMAX_C(1)<<8) #define BC_FLAG_TTY (UINTMAX_C(1)<<9) #define BC_TTYIN (vm.flags & BC_FLAG_TTYIN) #define BC_TTY (vm.flags & BC_FLAG_TTY) +#if BC_ENABLED + #define BC_S (BC_ENABLED && (vm.flags & BC_FLAG_S)) #define BC_W (BC_ENABLED && (vm.flags & BC_FLAG_W)) #define BC_L (BC_ENABLED && (vm.flags & BC_FLAG_L)) -#define BC_I (vm.flags & BC_FLAG_I) #define BC_G (BC_ENABLED && (vm.flags & BC_FLAG_G)) -#define DC_X (DC_ENABLED && (vm.flags & DC_FLAG_X)) + +#endif // BC_ENABLED + +#if DC_ENABLED +#define DC_X (vm.flags & DC_FLAG_X) +#endif // DC_ENABLED + +#define BC_I (vm.flags & BC_FLAG_I) #define BC_P (vm.flags & BC_FLAG_P) +#if BC_ENABLED + +#define BC_IS_POSIX (BC_S || BC_W) + +#if DC_ENABLED +#define BC_IS_BC (vm.name[0] != 'd') +#define BC_IS_DC (vm.name[0] == 'd') +#else // DC_ENABLED +#define BC_IS_BC (1) +#define BC_IS_DC (0) +#endif // DC_ENABLED + +#else // BC_ENABLED +#define BC_IS_POSIX (0) +#define BC_IS_BC (0) +#define BC_IS_DC (1) +#endif // BC_ENABLED + +#if BC_ENABLED #define BC_USE_PROMPT (!BC_P && BC_TTY && !BC_IS_POSIX) +#else // BC_ENABLED +#define BC_USE_PROMPT (!BC_P && BC_TTY) +#endif // BC_ENABLED #define BC_MAX(a, b) ((a) > (b) ? (a) : (b)) #define BC_MIN(a, b) ((a) < (b) ? (a) : (b)) @@ -131,9 +167,6 @@ #define BC_MAX_EXP ((ulong) (BC_NUM_BIGDIG_MAX)) #define BC_MAX_VARS ((ulong) (SIZE_MAX - 1)) -#define BC_IS_BC (BC_ENABLED && (!DC_ENABLED || vm.name[0] != 'd')) -#define BC_IS_POSIX (BC_S || BC_W) - #if BC_DEBUG_CODE #define BC_VM_JMP bc_vm_jmp(__func__) #else // BC_DEBUG_CODE @@ -234,7 +267,9 @@ #define BC_VM_BUF_SIZE (1<<12) #define BC_VM_STDOUT_BUF_SIZE (1<<11) #define BC_VM_STDERR_BUF_SIZE (1<<10) -#define BC_VM_STDIN_BUF_SIZE BC_VM_STDERR_BUF_SIZE +#define BC_VM_STDIN_BUF_SIZE (BC_VM_STDERR_BUF_SIZE - 1) + +#define BC_VM_SAFE_RESULT(r) ((r)->t >= BC_RESULT_TEMP) #define bc_vm_err(e) (bc_vm_error((e), 0)) #define bc_vm_verr(e, ...) (bc_vm_error((e), 0, __VA_ARGS__)) diff --git a/install.sh b/install.sh index 15e6ba240307..6d1600330ba9 100755 --- a/install.sh +++ b/install.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/karatsuba.py b/karatsuba.py index 9e09d755e691..a3cc8e6eed40 100755 --- a/karatsuba.py +++ b/karatsuba.py @@ -1,8 +1,8 @@ #! /usr/bin/python3 -B # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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,6 +44,9 @@ def run(cmd, env=None): script = sys.argv[0] testdir = os.path.dirname(script) +if testdir == "": + testdir = os.getcwd() + 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,") diff --git a/link.sh b/link.sh index 4d9b46cf7029..6f235c0920da 100755 --- a/link.sh +++ b/link.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/locale_install.sh b/locale_install.sh index 007aca3adcae..cdd41ef37ff8 100755 --- a/locale_install.sh +++ b/locale_install.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/locale_uninstall.sh b/locale_uninstall.sh index 5f2700fa08e6..43facb33cd90 100755 --- a/locale_uninstall.sh +++ b/locale_uninstall.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/locales/de_DE.ISO8859-1.msg b/locales/de_DE.ISO8859-1.msg index d058b56258d2..518ddf0cf473 100644 --- a/locales/de_DE.ISO8859-1.msg +++ b/locales/de_DE.ISO8859-1.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Headers for printing errors/warnings. diff --git a/locales/de_DE.UTF-8.msg b/locales/de_DE.UTF-8.msg index 4177c1c0c8b3..2e3cd675b451 100644 --- a/locales/de_DE.UTF-8.msg +++ b/locales/de_DE.UTF-8.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Headers for printing errors/warnings. diff --git a/locales/en_US.msg b/locales/en_US.msg index e7bc257916ed..3d0ca99ac8cc 100644 --- a/locales/en_US.msg +++ b/locales/en_US.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/es_ES.ISO8859-1.msg b/locales/es_ES.ISO8859-1.msg new file mode 100644 index 000000000000..5a66561e9758 --- /dev/null +++ b/locales/es_ES.ISO8859-1.msg @@ -0,0 +1,108 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + +$quote " + +$ Miscellaneous messages. +$set 1 + +1 "Función:" + +$ Error types. +$set 2 + +1 "Error de matemática:" +2 "Error de syntaxis:" +3 "Error de ejecución:" +4 "Error fatal:" +5 "Advertencia:" + +$ Math errors. +$set 3 + +1 "número negativo" +2 "número no es entero" +3 "desbordamiento de enteros: no se puede encajar el el hardware" +4 "división por cero" + +$ Parse errors. +$set 4 + +1 "fin de archivo" +2 "no válido '%c'" +3 "no puede encontrar el fine de la cadena" +4 "no puede encontrar el fine del comentario" +5 "el token no es válido" +6 "la expresión no es válida" +7 "la expresión es vacía" +8 "la expresión de print no es válida" +9 "la definición de función no es válida" +10 "la asignación no es valida: en la izquierda debe ser scale, ibase, obase, last, var, o un elemento de matriz" +11 "no se encontró ninguna variable automática" +12 "ya hay un parámetro de función o variable automatica que se llama \"%s%s\"" +13 "no se puede encontrar el final de del bloque de código" +14 "no puede haber un valor de retorno de una función \"void\": %s()" +15 "var no puede ser una referencia: %s" +16 "POSIX no permite nombres de más de 1 carácter: %s" +17 "POSIX no permite '#' script comentarios" +18 "POSIX no permite este palabra clave %s" +19 "POSIX no permite un punto ('.') como un atajo del resultado previoso" +20 "POSIX requieres paréntesis en el expresión del \"return\"" +21 "POSIX no permite este operador: %s" +22 "POSIX no permite operadores de comparación aparte de \"if\" expresión o bucles" +23 "POSIX requiere 0 o 1 operadores de comparisón para cada condición" +24 "POSIX requiere todos 3 partes de una bucla que no esta vacío" +25 "POSIX no permite una notación exponencial" +26 "POSIX no permite una referencia a una matriz como un parámetro de función" +27 "POSIX requiere el llave de la izquierda que sea en la misma línea que los parámetros de la función" + +$ Runtime errors. +$set 5 + +1 "\"ibase\" no es válido: debe ser [%lu, %lu]" +2 "\"obase\" no es válido: debe ser [%lu, %lu]" +3 "\"scale\" no es válido: debe ser [%lu, %lu]" +4 "read() expresión no es válido" +5 "recursion en la invocación de read()" +6 "variable o elemento del matriz de tipo equivocado" +7 "la pila no ha demaciado elementos" +8 "la función no tiene un número de argumentos correcto; necessita %zu, tiene %zu" +9 "la función no esta definida: %s()" +10 "no puede utilizar un valor vacío en una expresión" + +$ Fatal errors. +$set 6 + +1 "error en la asignación de memoria" +2 "error de I/O" +3 "no puede abrir el archivo: %s" +4 "el archivo no es ASCII: %s" +5 "el ruta es un directorio: %s" +6 "una opción de línea de comandos no es válida: \"%s\"" +7 "una opción requiere un argumento: '%c' (\"%s\")" +8 "una opción no tiene argumento: '%c' (\"%s\")" diff --git a/locales/es_ES.ISO8859-15.msg b/locales/es_ES.ISO8859-15.msg new file mode 120000 index 000000000000..0eb18677652d --- /dev/null +++ b/locales/es_ES.ISO8859-15.msg @@ -0,0 +1 @@ +es_ES.ISO8859-1.msg \ No newline at end of file diff --git a/locales/es_ES.UTF-8.msg b/locales/es_ES.UTF-8.msg index 9bca468c458f..ab33b973f675 100644 --- a/locales/es_ES.UTF-8.msg +++ b/locales/es_ES.UTF-8.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/fr_FR.ISO8859-1.msg b/locales/fr_FR.ISO8859-1.msg index c272a051e80b..42c3f26ca5b7 100644 --- a/locales/fr_FR.ISO8859-1.msg +++ b/locales/fr_FR.ISO8859-1.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/fr_FR.UTF-8.msg b/locales/fr_FR.UTF-8.msg index c272a051e80b..42c3f26ca5b7 100644 --- a/locales/fr_FR.UTF-8.msg +++ b/locales/fr_FR.UTF-8.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/ja_JP.UTF-8.msg b/locales/ja_JP.UTF-8.msg index 766fcf417521..587c84413aab 100644 --- a/locales/ja_JP.UTF-8.msg +++ b/locales/ja_JP.UTF-8.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ ãã®ä»–ã®ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã€‚ diff --git a/locales/ja_JP.eucJP.msg b/locales/ja_JP.eucJP.msg index 926840e9b740..8229c8f5a665 100644 --- a/locales/ja_JP.eucJP.msg +++ b/locales/ja_JP.eucJP.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ ¤½¤Î¾¤Î¥á¥Ã¥»¡¼¥¸¡£ diff --git a/locales/nl_NL.ISO8859-1.msg b/locales/nl_NL.ISO8859-1.msg index f7bf7f337a20..a291baa53963 100644 --- a/locales/nl_NL.ISO8859-1.msg +++ b/locales/nl_NL.ISO8859-1.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Diversen berichten. diff --git a/locales/nl_NL.UTF-8.msg b/locales/nl_NL.UTF-8.msg index 4ab8bcb169d6..07fdbf248815 100644 --- a/locales/nl_NL.UTF-8.msg +++ b/locales/nl_NL.UTF-8.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Diversen berichten. diff --git a/locales/pl_PL.ISO8859-2.msg b/locales/pl_PL.ISO8859-2.msg index bd9281555ef8..b1bbca8054e9 100644 --- a/locales/pl_PL.ISO8859-2.msg +++ b/locales/pl_PL.ISO8859-2.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Ró¿ne wiadomo¶ci. diff --git a/locales/pl_PL.UTF-8.msg b/locales/pl_PL.UTF-8.msg index 608f7a6b289f..58eee21267d1 100644 --- a/locales/pl_PL.UTF-8.msg +++ b/locales/pl_PL.UTF-8.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Różne wiadomoÅ›ci. diff --git a/locales/pt_PT.ISO8859-1.msg b/locales/pt_PT.ISO8859-1.msg index c278adc88b5e..055a8f48d47e 100644 --- a/locales/pt_PT.ISO8859-1.msg +++ b/locales/pt_PT.ISO8859-1.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/pt_PT.UTF-8.msg b/locales/pt_PT.UTF-8.msg index 573de6aa9162..b07e58228eb3 100644 --- a/locales/pt_PT.UTF-8.msg +++ b/locales/pt_PT.UTF-8.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/ru_RU.CP1251.msg b/locales/ru_RU.CP1251.msg index 16ff7b359cc0..d54a7bf51fda 100644 --- a/locales/ru_RU.CP1251.msg +++ b/locales/ru_RU.CP1251.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Ðàçíûå ñîîáùåíèÿ. diff --git a/locales/ru_RU.CP866.msg b/locales/ru_RU.CP866.msg index dcb9d0237cd3..44325a832dcd 100644 --- a/locales/ru_RU.CP866.msg +++ b/locales/ru_RU.CP866.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $  §­ë¥ á®®¡é¥­¨ï. diff --git a/locales/ru_RU.ISO8859-5.msg b/locales/ru_RU.ISO8859-5.msg index a9e7ad0b2fa9..c4f314c5c32b 100644 --- a/locales/ru_RU.ISO8859-5.msg +++ b/locales/ru_RU.ISO8859-5.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ ÀÐ×ÝëÕ áÞÞÑéÕÝØï. diff --git a/locales/ru_RU.KOI8-R.msg b/locales/ru_RU.KOI8-R.msg index e0a5f5b74dac..991845680d49 100644 --- a/locales/ru_RU.KOI8-R.msg +++ b/locales/ru_RU.KOI8-R.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ òÁÚÎÙÅ ÓÏÏÂÝÅÎÉÑ. diff --git a/locales/ru_RU.UTF-8.msg b/locales/ru_RU.UTF-8.msg index 86b2eac252c4..b0d8165554b2 100644 --- a/locales/ru_RU.UTF-8.msg +++ b/locales/ru_RU.UTF-8.msg @@ -1,3 +1,31 @@ +$ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ +$ Copyright (c) 2018-2020 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. +$ $ + $quote " $ Разные ÑообщениÑ. diff --git a/locales/zh_CN.GB18030.msg b/locales/zh_CN.GB18030.msg index c04e324c38af..e305f0d93471 100644 --- a/locales/zh_CN.GB18030.msg +++ b/locales/zh_CN.GB18030.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/zh_CN.GB2312.msg b/locales/zh_CN.GB2312.msg index c04e324c38af..e305f0d93471 100644 --- a/locales/zh_CN.GB2312.msg +++ b/locales/zh_CN.GB2312.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/zh_CN.GBK.msg b/locales/zh_CN.GBK.msg index c04e324c38af..e305f0d93471 100644 --- a/locales/zh_CN.GBK.msg +++ b/locales/zh_CN.GBK.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/zh_CN.UTF-8.msg b/locales/zh_CN.UTF-8.msg index 08b5a9d4f825..b2d0389f9fd6 100644 --- a/locales/zh_CN.UTF-8.msg +++ b/locales/zh_CN.UTF-8.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/locales/zh_CN.eucCN.msg b/locales/zh_CN.eucCN.msg index c04e324c38af..e305f0d93471 100644 --- a/locales/zh_CN.eucCN.msg +++ b/locales/zh_CN.eucCN.msg @@ -1,8 +1,8 @@ $ $ +$ SPDX-License-Identifier: BSD-2-Clause +$ $ $ Copyright (c) 2018-2020 Gavin D. Howard and contributors. $ $ -$ All rights reserved. -$ $ $ Redistribution and use in source and binary forms, with or without $ modification, are permitted provided that the following conditions are met: $ $ diff --git a/manpage.sh b/manpage.sh index 9a7be4a745f1..631d162d51c3 100755 --- a/manpage.sh +++ b/manpage.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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,21 +28,86 @@ # usage() { - printf "usage: %s ronn_file output_file\n" "$0" 1>&2 + printf "usage: %s manpage\n" "$0" 1>&2 exit 1 } +gen_manpage() { + + _gen_manpage_args="$1" + shift + + _gen_manpage_status="$ALL" + _gen_manpage_out="$manualsdir/$manpage/$_gen_manpage_args.1" + _gen_manpage_md="$manualsdir/$manpage/$_gen_manpage_args.1.md" + _gen_manpage_temp="$manualsdir/temp.1.md" + _gen_manpage_ifs="$IFS" + + rm -rf "$_gen_manpage_out" "$_gen_manpage_md" + + while IFS= read -r line; do + + if [ "$line" = "{{ end }}" ]; then + + if [ "$_gen_manpage_status" -eq "$ALL" ]; then + err_exit "{{ end }} tag without corresponding start tag" 2 + fi + + _gen_manpage_status="$ALL" + + elif [ "${line#\{\{* $_gen_manpage_args *\}\}}" != "$line" ]; then + + if [ "$_gen_manpage_status" -ne "$ALL" ]; then + err_exit "start tag nested in start tag" 3 + fi + + _gen_manpage_status="$NOSKIP" + + elif [ "${line#\{\{*\}\}}" != "$line" ]; then + + if [ "$_gen_manpage_status" -ne "$ALL" ]; then + err_exit "start tag nested in start tag" 3 + fi + + _gen_manpage_status="$SKIP" + + else + if [ "$_gen_manpage_status" -ne "$SKIP" ]; then + printf '%s\n' "$line" >> "$_gen_manpage_temp" + fi + fi + + done < "$manualsdir/${manpage}.1.md.in" + + uniq "$_gen_manpage_temp" "$_gen_manpage_md" + rm -rf "$_gen_manpage_temp" + + IFS="$_gen_manpage_ifs" + + cat "$manualsdir/header.txt" > "$_gen_manpage_out" + cat "$manualsdir/header_${manpage}.txt" >> "$_gen_manpage_out" + + pandoc -f markdown -t man "$_gen_manpage_md" >> "$_gen_manpage_out" +} + set -e script="$0" scriptdir=$(dirname "$script") +manualsdir="$scriptdir/manuals" -test "$#" -ge 2 || usage +. "$scriptdir/functions.sh" -ronn_file="$1" +ARGS="A E H N P EH EN EP HN HP NP EHN EHP ENP HNP EHNP" +ALL=0 +NOSKIP=1 +SKIP=2 + +test "$#" -eq 1 || usage + +manpage="$1" shift -output_file="$1" -shift - -ronn --pipe --roff --organization="Gavin D. Howard" --manual="General Commands Manual" $ronn_file | sed 's|\\fB\\'"'"'\\fR|\\fB'"'"'\\fR|g' > $output_file +for a in $ARGS; do + gen_manpage "$a" +done diff --git a/manuals/bc.1 b/manuals/bc.1 deleted file mode 100644 index 5b4868398a25..000000000000 --- a/manuals/bc.1 +++ /dev/null @@ -1,1566 +0,0 @@ -.\" generated with Ronn/v0.7.3 -.\" http://github.com/rtomayko/ronn/tree/0.7.3 -. -.TH "BC" "1" "June 2020" "Gavin D. Howard" "General Commands Manual" -. -.SH "NAME" -\fBbc\fR \- arbitrary\-precision arithmetic language and calculator -. -.SH "SYNOPSIS" -\fBbc\fR [\fB\-ghilPqsvVw\fR] [\fB\-\-global\-stacks\fR] [\fB\-\-help\fR] [\fB\-\-interactive\fR] [\fB\-\-mathlib\fR] [\fB\-\-no\-prompt\fR] [\fB\-\-quiet\fR] [\fB\-\-standard\fR] [\fB\-\-warn\fR] [\fB\-\-version\fR] [\fB\-e\fR \fIexpr\fR] [\fB\-\-expression=\fR\fIexpr\fR\.\.\.] [\fB\-f\fR \fIfile\fR\.\.\.] [\fB\-file=\fR\fIfile\fR\.\.\.] [\fIfile\fR\.\.\.] -. -.SH "DESCRIPTION" -bc(1) is an interactive processor for a language first standardized in 1991 by POSIX\. (The current standard is here \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR\.) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences\. Such differences will be noted in this document\. -. -.P -After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \fBstdin\fR\. -. -.P -With all build options, except for extra math, enabled this bc(1) is a drop\-in replacement for \fB\fIany\fR\fR bc(1), including (and especially) the GNU bc(1)\. It is also a drop\-in replacement for any bc(1) if extra math is enabled, but it will have extra features not found in other bc(1) implementations\. -. -.SH "OPTIONS" -The following are the options that bc(1) accepts\. -. -.TP -\fB\-g\fR, \fB\-\-global\-stacks\fR -Turns the globals \fBibase\fR, \fBobase\fR, and \fBscale\fR into stacks\. This includes \fBseed\fR if bc(1) was built with the extra math option\. -. -.IP -This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns\. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions\. Thus, \fBoutput(x,b)\fR (in the \fIextended library\fR) could have been written like this: -. -.IP -\fBdefine void output(x, b) { obase=b; x }\fR -. -.IP -instead of like this: -. -.IP -\fBdefine void output(x, b) { auto c; c=obase; obase=b; x; obase=c }\fR -. -.IP -This makes writing functions much easier\. -. -.IP -However, since using this flag means that functions cannot set \fBibase\fR, \fBobase\fR, or \fBscale\fR globally, functions that are made to do so cannot work anymore\. There are two possible use cases for that, and each has a solution\. -. -.IP -First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases\. Examples: -. -.IP -\fBalias d2o="bc \-e ibase=A \-e obase=8"; alias h2b="bc \-e ibase=G \-e obase=2"\fR -. -.IP -Second, if the purpose of a function is to set \fBibase\fR, \fBobase\fR, or \fBscale\fR globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global\. -. -.IP -For functions that set \fBseed\fR, the value assigned to \fBseed\fR is not propagated to parent functions\. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees\. This is only the case once \fBseed\fR has been set\. -. -.IP -If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \fBseed\fR, it can use the following line: -. -.IP -\fBseed = seed\fR -. -.IP -If the behavior of this option is desired for every run of bc(1), then users could make sure to define \fBBC_ENV_ARGS\fR and include this option (see the ENVIRONMENT VARIABLES section for more details)\. -. -.IP -If \fB\-s\fR, \fB\-w\fR, or any equivalents are used, this option is ignored\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-h\fR, \fB\-\-help\fR -Prints a usage message and quits\. -. -.TP -\fB\-i\fR, \fB\-\-interactive\fR -Forces interactive mode\. (See the INTERACTIVE MODE section\.) -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-l\fR, \fB\-\-mathlib\fR -Sets \fBscale\fR (see the Scale section) to \fB20\fR and loads the included math library before running any code, including any expressions or files specified on the command line\. -. -.IP -To learn what is in the library, see the LIBRARY section\. -. -.TP -\fB\-P\fR, \fB\-\-no\-prompt\fR -Disables the prompt in interactive mode\. This is mostly for those users that do not want a prompt or are not used to having them in \fBbc\fR\. Most of those users would want to put this option in \fBBC_ENV_ARGS\fR\. -. -.IP -If the prompt has been disabled while building bc(1), this option is a no\-op\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-q\fR, \fB\-\-quiet\fR -Do not print copyright header\. bc(1) will also suppress the header in non\-interactive mode\. -. -.IP -This is mostly for compatibility with the GNU bc(1) \fIhttps://www\.gnu\.org/software/bc/\fR\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-s\fR, \fB\-\-standard\fR -Process exactly the language defined by the standard \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR and error if any extensions are used\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-v\fR, \fB\-V\fR, \fB\-\-version\fR -Print the version information (copyright header) and exit\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-w\fR, \fB\-\-warn\fR -Like \fB\-s\fR and \fB\-\-standard\fR, except that warnings (and not errors) are given for non\-standard extensions\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-e\fR \fIexpr\fR, \fB\-\-expression\fR=\fIexpr\fR -Evaluates \fBexpr\fR\. If multiple expressions are given, they are evaluated in order\. If files are given as well (see below), the expressions and files are evaluated in the order given\. This means that if a file is given before an expression, the file is read in and evaluated first\. -. -.IP -In other bc(1) implementations, this option causes the program to execute the expressions and then exit\. This bc(1) does not, unless the \fBBC_EXPR_EXIT\fR is defined (see the ENVIRONMENT VARIABLES section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-f\fR \fIfile\fR, \fB\-\-file\fR=\fIfile\fR -Reads in \fBfile\fR and evaluates it\. If expressions are also given (see above), the expressions are evaluated in the order given\. -. -.IP -In other bc(1) implementations, this option causes the program to execute the files and then exit\. This bc(1) does not, unless the \fBBC_EXPR_EXIT\fR is defined (see the ENVIRONMENT VARIABLES section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.P -\fBNote\fR: long options are only accepted if bc(1) is built with them enabled\. -. -.SH "STDOUT" -Any non\-error output is written to \fBstdout\fR\. -. -.P -\fBNote\fR: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the EXIT STATUS section) if it cannot write to \fBstdout\fR, so if \fBstdout\fR is closed, as in \fBbc >&\-\fR, it will quit with an error\. This is done so that bc(1) can report problems when \fBstdout\fR is redirected to a file\. -. -.P -If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \fBstdout\fR to \fB/dev/null\fR\. -. -.SH "STDERR" -Any error output is written to \fBstderr\fR\. -. -.P -\fBNote\fR: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the EXIT STATUS section) if it cannot write to \fBstderr\fR, so if \fBstderr\fR is closed, as in \fBbc 2>&\-\fR, it will quit with an error\. This is done so that bc(1) can report problems when \fBstderr\fR is redirected to a file\. -. -.P -If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \fBstderr\fR to \fB/dev/null\fR\. -. -.SH "SYNTAX" -The syntax for bc(1) programs is mostly C\-like, with some differences\. This bc(1) follows the POSIX standard \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR, 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 \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR\. -. -.P -In the sections below, \fBE\fR means expression, \fBS\fR means statement, and \fBI\fR means identifier\. -. -.P -Identifiers (\fBI\fR) start with a lowercase letter and can be followed by any number (up to \fBBC_NAME_MAX\-1\fR) of lowercase letters (\fBa\-z\fR), digits (\fB0\-9\fR), and underscores (\fB_\fR)\. The regex is \fB[a\-z][a\-z0\-9_]*\fR Identifiers with more than one character (letter) are a \fBnon\-portable extension\fR\. -. -.P -\fBibase\fR is a global variable determining how to interpret constant numbers\. It is the "input" base, or the number base used for interpreting input numbers\. \fBibase\fR is initially \fB10\fR\. If the \fB\-s\fR (\fB\-\-standard\fR) and \fB\-w\fR (\fB\-\-warn\fR) flags were not given on the command line, the max allowable value for \fBibase\fR is \fB36\fR\. Otherwise, it is \fB16\fR\. The min allowable value for \fBibase\fR is \fB2\fR\. The max allowable value for \fBibase\fR can be queried in bc(1) programs with the \fBmaxibase()\fR built in function\. -. -.P -\fBobase\fR is a global variable determining how to output results\. It is the "output" base, or the number base used for outputting numbers\. \fBobase\fR is initially \fB10\fR\. The max allowable value for \fBobase\fR is \fBBC_BASE_MAX\fR\. The min allowable value for \fBobase\fR is \fB2\fR, unless bc(1) was built with the extra math option\. If it was, then the min allowable value is \fB0\fR\. In this case, if \fBobase\fR is \fB0\fR, values are output in scientific notation, and if \fBobase\fR is \fB1\fR, values are output in engineering notation\. (Outputting in scientific or engineering notation are \fBnon\-portable extensions\fR\.) The max allowable value for \fBobase\fR can be queried in bc(1) programs with the \fBmaxobase()\fR built in function\. -. -.P -The \fBscale\fR of an expression is the number of digits in the result of the expression right of the decimal point, and \fBscale\fR is a global variable that sets the precision of any operations, with exceptions\. \fBscale\fR is initially \fB0\fR\. \fBscale\fR cannot be negative\. The max allowable value for \fBscale\fR can be queried in bc(1) programs with the \fBmaxscale()\fR built in function\. -. -.P -bc(1) has both \fBglobal\fR variables and \fBlocal\fR variables\. All \fBlocal\fR variables are local to the function; they are parameters or are introduced in the \fBauto\fR list of a function (see FUNCTIONS)\. If a variable is accessed which is not a parameter or in the \fBauto\fR list, it is assumed to be \fBglobal\fR\. If a parent function has a \fBlocal\fR variable version of a \fBglobal\fR variable that is accessed by a function that it calls, the value of that \fBglobal\fR variable in the child function is the value of the variable in the parent function, not the value of the actual \fBglobal\fR variable\. -. -.P -All of the above applies to arrays as well\. -. -.P -The value of a statement that is an expression (i\.e\., any of the \fINamed Expressions\fR or \fIOperands\fR) is printed unless the lowest precedence operator is an \fI\fBassignment\fR\fR operator \fB\fIand\fR\fR the expression is not surrounded by parentheses\. -. -.P -The value that is printed is also assigned to the special variable \fBlast\fR\. A single dot (\fB\.\fR) may also be used as a synonym for \fBlast\fR\. These are \fBnon\-portable extensions\fR\. -. -.P -Either semicolons or newlines may separate statements\. -. -.SS "Comments" -There are two kinds of comments: -. -.IP "1." 4 -Block comments are enclosed in \fB/*\fR and \fB*/\fR\. -. -.IP "2." 4 -Line comments go from \fB#\fR until, and not including, the next newline\. This is a \fBnon\-portable extension\fR\. -. -.IP "" 0 -. -.P - \fI\fR -. -.SS "Named Expressions" -The following are named expressions in bc(1): -. -.IP "1." 4 -Variables: \fBI\fR -. -.IP "2." 4 -Array Elements: \fBI[E]\fR -. -.IP "3." 4 -\fBibase\fR -. -.IP "4." 4 -\fBobase\fR -. -.IP "5." 4 -\fBscale\fR -. -.IP "6." 4 -\fBlast\fR or a single dot (\fB\.\fR) -. -.IP "" 0 -. -.P -Number 6 is a \fBnon\-portable extension\fR\. -. -.P -If bc(1) was built with the extra math option, the following is also a named expression: -. -.IP "1." 4 -\fBseed\fR -. -.IP "" 0 -. -.P -The meaning of \fBseed\fR is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions\. -. -.P -The \fBscale\fR of the value may be significant\. -. -.P -If a previously used \fBseed\fR value is assigned to \fBseed\fR and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \fBseed\fR value was previously used\. -. -.P -The exact value assigned to \fBseed\fR is not guaranteed to be returned if \fBseed\fR is queried again immediately\. However, if \fBseed\fR \fIdoes\fR return a different value, both values, when assigned to \fBseed\fR, are guaranteed to produce the same sequence of pseudo\-random numbers\. This means that certain values assigned to \fBseed\fR will not produce unique sequences of pseudo\-random numbers\. The value of \fBseed\fR will change after any use of the \fBrand()\fR and \fBirand(E)\fR operands, except if the parameter passed to \fBirand(E)\fR is \fB0\fR or \fB1\fR\. -. -.P -There is no limit to the length (number of significant decimal digits) or \fIscale\fR of the value that can be assigned to \fBseed\fR\. -. -.P -This command is only available if bc(1) was built with the extra math option\. -. -.P -This is a \fBnon\-portable extension\fR\. -. -.P -Variables and arrays do not interfere; users can have arrays named the same as variables\. This also applies to functions (see the FUNCTIONS section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other\. -. -.P -Named expressions are required as the operand of \fI\fBincrement\fR/\fBdecrement\fR operators\fR and as the left side of \fI\fBassignment\fR operators\fR\. -. -.P - \fI\fR -. -.SS "Operands" -The following are valid operands in bc(1): -. -.IP "1." 4 -Numbers (see \fINumbers\fR below)\. -. -.IP "2." 4 -Array indices (\fBI[E]\fR)\. -. -.IP "3." 4 -\fB(E)\fR: The value of \fBE\fR (used to change precedence)\. -. -.IP "4." 4 -\fBsqrt(E)\fR: The square root of \fBE\fR\. \fBE\fR must be non\-negative\. -. -.IP "5." 4 -\fBlength(E)\fR: The number of significant decimal digits in \fBE\fR\. -. -.IP "6." 4 -\fBlength(I[])\fR: The number of elements in the array \fBI\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "7." 4 -\fBscale(E)\fR: The \fBscale\fR of \fBE\fR\. -. -.IP "8." 4 -\fBabs(E)\fR: The absolute value of \fBE\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "9." 4 -\fBI()\fR, \fBI(E)\fR, \fBI(E, E)\fR, and so on, where \fBI\fR is an identifier for a non\-\fIvoid function\fR\. The \fBE\fR parameters may also be arrays, which will automatically be turned into \fIarray references\fR if the corresponding parameter is an array reference\. -. -.IP "10." 4 -\fBread()\fR: Reads a line from \fBstdin\fR and uses that as an expression\. The result of that expression is the result of the \fBread()\fR operand\. This is a \fBnon\-portable extension\fR\. -. -.IP "11." 4 -\fBmaxibase()\fR: The max allowable \fBibase\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "12." 4 -\fBmaxobase()\fR: The max allowable \fBobase\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "13." 4 -\fBmaxscale()\fR: The max allowable \fBscale\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "" 0 -. -.P -If bc(1) was built with the extra math option, the following are also valid operands: -. -.IP "1." 4 -\fBrand()\fR: A pseudo\-random integer between \fB0\fR (inclusive) and \fBBC_RAND_MAX\fR (inclusive)\. Using this operand will change the value of \fBseed\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "2." 4 -\fBirand(E)\fR: A pseudo\-random integer between \fB0\fR (inclusive) and the value of \fBE\fR (exclusive)\. If \fBE\fR is negative or is a non\-integer (\fBscale\fR is not \fB0\fR), an error is raised, and bc(1) resets (see the RESET section)\. If \fBE\fR is larger than \fBBC_RAND_MAX\fR, the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \fBBC_RAND_MAX + 1\fR, and adding them together\. Thus, the size of integer that can be generated with this operand is unbounded\. Using this operand will change the value of \fBseed\fR\. If \fBE\fR is \fB0\fR or \fB1\fR, then \fB0\fR is returned, and \fBseed\fR is not changed\. This is a \fBnon\-portable extension\fR\. -. -.IP "3." 4 -\fBmaxrand()\fR: The max integer returned by \fBrand()\fR\. This is a \fBnon\-portable extension\fR\. -. -.IP "" 0 -. -.P -The integers generated by \fBrand()\fR and \fBirand(E)\fR are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator\. -. -.P -\fBNote\fR: The values returned by the pseudo\-random number generator with \fBrand()\fR and \fBirand(E)\fR are guaranteed to \fBNOT\fR be cryptographically\-secure\. This is a consequence of using a seeded pseudo\-random number generator\. However, they \fBare\fR guaranteed to be reproducible with identical \fBseed\fR values\. -. -.P - \fI\fR -. -.SS "Numbers" -Numbers are strings made up of digits, uppercase letters, and at most \fB1\fR period for a radix\. Numbers can have up to \fBBC_NUM_MAX\fR digits\. Uppercase letters equal \fB9\fR + their position in the alphabet (i\.e\., \fBA\fR equals \fB10\fR, or \fB9 + 1\fR)\. If a digit or letter makes no sense with the current value of \fBibase\fR, they are set to the value of the highest valid digit in \fBibase\fR\. -. -.P -Single\-character numbers (i\.e\., \fBA\fR) take the value that they would have if they were valid digits, regardless of the value of \fBibase\fR\. This means that \fBA\fR always equals decimal \fB10\fR and \fBZ\fR always equals decimal \fB35\fR\. -. -.P -In addition, if bc(1) was built with the extra math option, it accepts numbers in scientific notation\. For bc(1), an example is \fB1\.89237e9\fR, which is equal to \fB1892370000\fR\. Negative exponents are also allowed, so \fB4\.2890e\-3\fR is equal to \fB0\.0042890\fR\. -. -.P -Using scientific notation is an error or warning if the \fB\-s\fR or \fB\-w\fR, respectively, command\-line options (or equivalents) are given\. -. -.P -\fBWARNING\fR: Both the number and the exponent in scientific notation are interpreted according to the current \fBibase\fR, but the number is still multiplied by \fB10^exponent\fR regardless of the current \fBibase\fR\. For example, if \fBibase\fR is \fB16\fR and bc(1) is given the number string \fB"FFeA"\fR, the resulting decimal number will be \fB2550000000000\fR, and if bc(1) is given the number string \fB"10e\-4"\fR, the resulting decimal number will be \fB0\.0016\fR\. -. -.P -Accepting input as scientific notation is a \fBnon\-portable extension\fR\. -. -.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 -\fB++\fR \fB\-\-\fR -Type: Prefix and Postfix -. -.IP -Associativity: None -. -.IP -Description: \fBincrement\fR, \fBdecrement\fR -. -.TP -\fB\-\fR \fB!\fR -Type: Prefix -. -.IP -Associativity: None -. -.IP -Description: \fBnegation\fR, \fBboolean not\fR -. -.TP -\fB$\fR -Type: Postfix -. -.IP -Associativity: None -. -.IP -Description: \fBtruncation\fR -. -.TP -\fB@\fR -Type: Binary -. -.IP -Associativity: Right -. -.IP -Description: \fBset precision\fR -. -.TP -\fB^\fR -Type: Binary -. -.IP -Associativity: Right -. -.IP -Description: \fBpower\fR -. -.TP -\fB*\fR \fB/\fR \fB%\fR -Type: Binary -. -.IP -Associativity: Left -. -.IP -Description: \fBmultiply\fR, \fBdivide\fR, \fBmodulus\fR -. -.TP -\fB+\fR \fB\-\fR -Type: Binary -. -.IP -Associativity: Left -. -.IP -Description: \fBadd\fR, \fBsubtract\fR -. -.TP -\fB<<\fR \fB>>\fR -Type: Binary -. -.IP -Associativity: Left -. -.IP -Description: \fBshift left\fR, \fBshift right\fR -. -.TP -\fB=\fR \fB<<=\fR \fB>>=\fR \fB+=\fR \fB\-=\fR \fB*=\fR \fB/=\fR \fB%=\fR \fB^=\fR \fB@=\fR -Type: Binary -. -.IP -Associativity: Right -. -.IP -Description: \fBassignment\fR -. -.TP -\fB==\fR \fB<=\fR \fB>=\fR \fB!=\fR \fB<\fR \fB>\fR -Type: Binary -. -.IP -Associativity: Left -. -.IP -Description: \fBrelational\fR -. -.TP -\fB&&\fR -Type: Binary -. -.IP -Associativity: Left -. -.IP -Description: \fBboolean and\fR -. -.TP -\fB||\fR -Type: Binary -. -.IP -Associativity: Left -. -.IP -Description: \fBboolean or\fR -. -.P -The operators will be described in more detail below\. -. -.P - \fI\fR -. -.TP -\fB++\fR \fB\-\-\fR -The prefix and postfix \fBincrement\fR and \fBdecrement\fR operators behave exactly like they would in C\. They require a \fInamed expression\fR as an operand\. -. -.IP -The prefix versions of these operators are more efficient; use them where possible\. -. -.TP -\fB\-\fR -The \fBnegation\fR operator returns \fB0\fR if a user attempts to negate any expression with the value \fB0\fR\. Otherwise, a copy of the expression with its sign flipped is returned\. -. -.TP -\fB!\fR -The \fBboolean not\fR operator returns \fB1\fR if the expression is \fB0\fR, or \fB0\fR otherwise\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB$\fR -The \fBtruncation\fR operator returns a copy of the given expression with all of its \fBscale\fR removed\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.IP -This is only available if bc(1) has been compiled with the extra math option enabled\. -. -.TP -\fB@\fR -The \fBset precision\fR operator takes two expressions and returns a copy of the first with its \fBscale\fR equal to the value of the second expression\. That could either mean that the number is returned without change (if the \fBscale\fR of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more)\. -. -.IP -The second expression must be an integer (no \fBscale\fR) and non\-negative\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.IP -This is only available if bc(1) has been compiled with the extra math option enabled\. -. -.TP -\fB^\fR -The \fBpower\fR operator (not the \fBexclusive or\fR operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second\. -. -.IP -The second expression must be an integer (no \fBscale\fR), and if it is negative, the first value must be non\-zero\. -. -.TP -\fB*\fR -The \fBmultiply\fR operator takes two expressions, multiplies them, and returns the product\. If \fBa\fR is the \fBscale\fR of the first expression and \fBb\fR is the \fBscale\fR of the second expression, the scale of the result is equal to \fBmin(a+b,max(scale,a,b))\fR where \fBmin\fR and \fBmax\fR return the obvious values\. -. -.TP -\fB/\fR -The \fBdivide\fR operator takes two expressions, divides them, and returns the quotient\. The scale of the result shall be the value of \fBscale\fR\. -. -.IP -The second expression must be non\-zero\. -. -.TP -\fB%\fR -The \fBmodulus\fR operator takes two expressions, \fBa\fR and \fBb\fR, and evaluates them by 1) Computing \fBa/b\fR to current \fBscale\fR and 2) Using the result of step 1 to calculate \fBa\-(a/b)*b\fR to scale \fBmax(scale+scale(b),scale(a))\fR\. -. -.IP -The second expression must be non\-zero\. -. -.TP -\fB+\fR -The \fBadd\fR operator takes two expressions, \fBa\fR and \fBb\fR, and returns the sum, with a \fBscale\fR equal to the max of the \fBscale\fRs of \fBa\fR and \fBb\fR\. -. -.TP -\fB\-\fR -The \fBsubtract\fR operator takes two expressions, \fBa\fR and \fBb\fR, and returns the difference, with a \fBscale\fR equal to the max of the \fBscale\fRs of \fBa\fR and \fBb\fR\. -. -.TP -\fB<<\fR -The \fBleft shift\fR operator takes two expressions, \fBa\fR and \fBb\fR, and returns a copy of the value of \fBa\fR with its decimal point moved \fBb\fR places to the right\. -. -.IP -The second expression must be an integer (no \fBscale\fR) and non\-negative\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.IP -This is only available if bc(1) has been compiled with the extra math option enabled\. -. -.TP -\fB>>\fR -The \fBright shift\fR operator takes two expressions, \fBa\fR and \fBb\fR, and returns a copy of the value of \fBa\fR with its decimal point moved \fBb\fR places to the left\. -. -.IP -The second expression must be an integer (no \fBscale\fR) and non\-negative\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.IP -This is only available if bc(1) has been compiled with the extra math option enabled\. -. -.P - \fI\fR -. -.TP -\fB=\fR \fB<<=\fR \fB>>=\fR \fB+=\fR \fB\-=\fR \fB*=\fR \fB/=\fR \fB%=\fR \fB^=\fR \fB@=\fR -The \fBassignment\fR operators take two expressions, \fBa\fR and \fBb\fR where \fBa\fR is a \fInamed expression\fR\. -. -.IP -For \fB=\fR, \fBb\fR is copied and the result is assigned to \fBa\fR\. For all others, \fBa\fR and \fBb\fR are applied as operands to the corresponding arithmetic operator and the result is assigned to \fBa\fR\. -. -.IP -The \fBassignment\fR operators that correspond to operators that are extensions are themselves extensions\. -. -.IP -Also, those \fBassignment\fR operators that are extensions are only available if bc(1) has been compiled with the extra math option enabled\. -. -.TP -\fB==\fR \fB<=\fR \fB>=\fR \fB!=\fR \fB<\fR \fB>\fR -The \fBrelational\fR operators compare two expressions, \fBa\fR and \fBb\fR, and if the relation holds, according to C language semantics, the result is \fB1\fR\. Otherwise, it is \fB0\fR\. -. -.IP -Note that unlike in C, these operators have a lower precedence than the \fBassignment\fR operators, which means that \fBa=b>c\fR is interpreted as \fB(a=b)>c\fR\. -. -.IP -Also, unlike the standard \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR requires, these operators can appear anywhere any other expressions can be used\. This allowance is a \fBnon\-portable extension\fR\. -. -.TP -\fB&&\fR -The \fBboolean and\fR operator takes two expressions and returns \fB1\fR if both expressions are non\-zero, \fB0\fR otherwise\. -. -.IP -This is \fB\fInot\fR\fR a short\-circuit operator\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB||\fR -The \fBboolean or\fR operator takes two expressions and returns \fB1\fR if one of the expressions is non\-zero, \fB0\fR otherwise\. -. -.IP -This is \fB\fInot\fR\fR a short\-circuit operator\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.SS "Statements" -The following items are statements: -. -.IP "1." 4 -\fBE\fR -. -.IP "2." 4 -\fB{\fR \fBS\fR \fB;\fR \.\.\. \fB;\fR \fBS\fR \fB}\fR -. -.IP "3." 4 -\fBif\fR \fB(\fR \fBE\fR \fB)\fR \fBS\fR -. -.IP "4." 4 -\fBif\fR \fB(\fR \fBE\fR \fB)\fR \fBS\fR \fBelse\fR \fBS\fR -. -.IP "5." 4 -\fBwhile\fR \fB(\fR \fBE\fR \fB)\fR \fBS\fR -. -.IP "6." 4 -\fBfor\fR \fB(\fR \fBE\fR \fB;\fR \fBE\fR \fB;\fR \fBE\fR \fB)\fR \fBS\fR -. -.IP "7." 4 -An empty statement -. -.IP "8." 4 -\fBbreak\fR -. -.IP "9." 4 -\fBcontinue\fR -. -.IP "10." 4 -\fBquit\fR -. -.IP "11." 4 -\fBhalt\fR -. -.IP "12." 4 -\fBlimits\fR -. -.IP "13." 4 -A string of characters, enclosed in double quotes -. -.IP "14." 4 -\fBprint\fR \fBE\fR \fB,\fR \.\.\. \fB,\fR \fBE\fR -. -.IP "15." 4 -\fBI()\fR, \fBI(E)\fR, \fBI(E, E)\fR, and so on, where \fBI\fR is an identifier for a \fIvoid function\fR\. The \fBE\fR parameters may also be arrays, which will automatically be turned into \fIarray references\fR if the corresponding parameter is an array reference\. -. -.IP "" 0 -. -.P -Numbers 4, 9, 11, 12, 14, and 15 are \fBnon\-portable extensions\fR\. -. -.P -Also, as a \fBnon\-portable extension\fR, 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 \fB1\fR\. -. -.P -The \fBbreak\fR statement causes a loop to stop iterating and resume execution immediately following a loop\. This is only allowed in loops\. -. -.P -The \fBcontinue\fR statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition\. This is only allowed in loops\. -. -.P -The \fBif\fR \fBelse\fR statement does the same thing as in C\. -. -.P -The \fBquit\fR statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command)\. -. -.P -The \fBhalt\fR statement causes bc(1) to quit, if it is executed\. (Unlike \fBquit\fR if it is on a branch of an \fBif\fR statement that is not executed, bc(1) does not quit\.) -. -.P -The \fBlimits\fR statement prints the limits that this bc(1) is subject to\. This is like the \fBquit\fR statement in that it is a compile\-time command\. -. -.P -An expression by itself is evaluated and printed, followed by a newline\. If bc(1) has been built with the extra math option enabled, both scientific notation and engineering notation are available for printing the results of expressions\. Scientific notation is activated by assigning \fB0\fR to \fBobase\fR (in any other context, an \fBobase\fR of \fB0\fR is invalid), and engineering notation is activated by assigning \fB1\fR to \fBobase\fR (which is also invalid in any other context)\. To deactivate them, just assign a different value to \fBobase\fR\. -. -.P -Scientific notation and engineering notation are disabled if bc(1) is run with either the \fB\-s\fR or \fB\-w\fR command\-line options (or equivalents)\. -. -.P -Printing numbers in scientific notation and/or engineering notation is a \fBnon\-portable extension\fR\. -. -.SS "Print Statement" -The "expressions" in a \fBprint\fR statement may also be strings\. If they are, there are backslash escape sequences that are interpreted specially\. What those sequences are, and what they cause to be printed, are shown below: -. -.TP -\fB\ea\fR -\fB\ea\fR -. -.TP -\fB\eb\fR -\fB\eb\fR -. -.TP -\fB\e\e\fR -\fB\e\fR -. -.TP -\fB\ee\fR -\fB\e\fR -. -.TP -\fB\ef\fR -\fB\ef\fR -. -.TP -\fB\en\fR -\fB\en\fR -. -.TP -\fB\eq\fR -\fB"\fR -. -.TP -\fB\er\fR -\fB\er\fR -. -.TP -\fB\et\fR -\fB\et\fR -. -.P -Any other character following a backslash causes the backslash and character to be printed as\-is\. -. -.P -Any non\-string expression in a print statement shall be assigned to \fBlast\fR, like any other expression that is printed\. -. -.SS "Order of Evaluation" -All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations\. This means, for example, that in the expression \fBi = 0; a[i++] = i++\fR, the first (or 0th) element of \fBa\fR is set to \fB1\fR, and \fBi\fR is equal to \fB2\fR at the end of the expression\. -. -.P -This includes function arguments\. Thus, this means that in the expression \fBi = 0; x(i++, i++)\fR, the first argument passed to \fBx()\fR is \fB0\fR, and the second argument is \fB1\fR, while \fBi\fR is equal to \fB2\fR before the function starts executing\. -. -.SH "FUNCTIONS" -Function definitions are as follows: -. -.IP "" 4 -. -.nf - -define I(I,\.\.\.,I){ - auto I,\.\.\.,I - S;\.\.\.;S - return(E) -} -. -.fi -. -.IP "" 0 -. -.P -Any \fBI\fR in the parameter list or \fBauto\fR list may be replaced with \fBI[]\fR to make a parameter or \fBauto\fR var an array, and any \fBI\fR in the parameter list may be replaced with \fB*I[]\fR to make a parameter an array reference\. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \fBI[]\fR like normal array parameters and will be automatically converted into references\. -. -.P -As a \fBnon\-portable extension\fR, the opening brace of a \fBdefine\fR statement may appear on the next line\. -. -.P -The return statement may also be in the following forms: -. -.IP "1." 4 -\fBreturn\fR -. -.IP "2." 4 -\fBreturn\fR \fB(\fR \fB)\fR -. -.IP "3." 4 -\fBreturn\fR \fBE\fR -. -.IP "" 0 -. -.P -The first two, or not specifying a \fBreturn\fR statement, is equivalent to \fBreturn (0)\fR, unless the function is a \fIvoid function\fR\. -. -.P - \fI\fR -. -.SS "Void Functions" -Functions can also be void functions, defined as follows: -. -.IP "" 4 -. -.nf - -define void I(I,\.\.\.,I){ - auto I,\.\.\.,I - S;\.\.\.;S - return -} -. -.fi -. -.IP "" 0 -. -.P -They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement\. -. -.P -Void functions can only use the first two \fBreturn\fR statements listed above\. They can also omit the return statement entirely\. -. -.P -The word \fBvoid\fR is not treated as a keyword; it is still possible to have variables, arrays, and functions named \fBvoid\fR\. The word \fBvoid\fR is only treated specially right after the \fBdefine\fR keyword\. -. -.P -This is a \fBnon\-portable extension\fR\. -. -.P - \fI\fR -. -.SS "Array References" -For any array in the parameter list, if the array is declared in the form -. -.IP "" 4 -. -.nf - -*I[] -. -.fi -. -.IP "" 0 -. -.P -it is a \fBreference\fR\. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in\. -. -.P -Other than this, all function arguments are passed by value\. -. -.P -This is a \fBnon\-portable extension\fR\. -. -.SH "LIBRARY" -All of the functions below, including the functions in the \fIextended library\fR if bc(1) has been compiled with the extra math option enabled, are available when the \fB\-l\fR or \fB\-\-mathlib\fR command\-line flags are given\. -. -.P - \fI\fR -. -.SS "Standard Library" -The standard \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR defines the following functions for the math library: -. -.TP -\fBs(x)\fR -Returns the sine of \fBx\fR, which is assumed to be in radians\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBc(x)\fR -Returns the cosine of \fBx\fR, which is assumed to be in radians\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBa(x)\fR -Returns the arctangent of \fBx\fR, in radians\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBl(x)\fR -Returns the natural logarithm of \fBx\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBe(x)\fR -Returns the mathematical constant \fBe\fR raised to the power of \fBx\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBj(x, n)\fR -Returns the bessel integer order \fBn\fR (truncated) of \fBx\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.P - \fI\fR -. -.SS "Extended Library" -In addition to the \fIstandard library\fR, if bc(1) has been built with the extra math option, the following functions are available when either the \fB\-l\fR or \fB\-\-mathlib\fR options are given\. -. -.P -However, the extended library is \fB\fInot\fR\fR loaded when the \fB\-s\fR/\fB\-\-standard\fR or \fB\-w\fR/\fB\-\-warn\fR options are given since they are not part of the library defined by the standard \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR\. -. -.P -The extended library is a \fBnon\-portable extension\fR\. -. -.TP -\fBp(x, y)\fR -Calculates \fBx\fR to the power of \fBy\fR, even if \fBy\fR is not an integer, and returns the result to the current \fBscale\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBr(x, p)\fR -Returns \fBx\fR rounded to \fBp\fR decimal places according to the rounding mode round half away from \fB0\fR \fIhttps://en\.wikipedia\.org/wiki/Rounding#Round_half_away_from_zero\fR\. -. -.TP -\fBceil(x, p)\fR -Returns \fBx\fR rounded to \fBp\fR decimal places according to the rounding mode round away from \fB0\fR \fIhttps://en\.wikipedia\.org/wiki/Rounding#Rounding_away_from_zero\fR\. -. -.TP -\fBf(x)\fR -Returns the factorial of the truncated absolute value of \fBx\fR\. -. -.TP -\fBperm(n, k)\fR -Returns the permutation of the truncated absolute value of \fBn\fR of the truncated absolute value of \fBk\fR, if \fBk <= n\fR\. If not, it returns \fB0\fR\. -. -.TP -\fBcomb(n, k)\fR -Returns the combination of the truncated absolute value of \fBn\fR of the truncated absolute value of \fBk\fR, if \fBk <= n\fR\. If not, it returns \fB0\fR\. -. -.TP -\fBl2(x)\fR -Returns the logarithm base \fB2\fR of \fBx\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBl10(x)\fR -Returns the logarithm base \fB10\fR of \fBx\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBlog(x, b)\fR -Returns the logarithm base \fBb\fR of \fBx\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBcbrt(x)\fR -Returns the cube root of \fBx\fR\. -. -.TP -\fBroot(x, n)\fR -Calculates the truncated value of \fBn\fR, \fBr\fR, and returns the \fBr\fRth root of \fBx\fR to the current \fBscale\fR\. -. -.IP -If \fBr\fR is \fB0\fR or negative, this raises an error and causes bc(1) to reset (see the RESET section)\. It also raises an error and causes bc(1) to reset if \fBr\fR is even and \fBx\fR is negative\. -. -.TP -\fBpi(p)\fR -Returns \fBpi\fR to \fBp\fR decimal places\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBt(x)\fR -Returns the tangent of \fBx\fR, which is assumed to be in radians\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBa2(y, x)\fR -Returns the arctangent of \fBy/x\fR, in radians\. If both \fBy\fR and \fBx\fR are equal to \fB0\fR, it raises an error and causes bc(1) to reset (see the RESET section)\. Otherwise, if \fBx\fR is greater than \fB0\fR, it returns \fBa(y/x)\fR\. If \fBx\fR is less than \fB0\fR, and \fBy\fR is greater than or equal to \fB0\fR, it returns \fBa(y/x) + pi\fR\. If \fBx\fR is less than \fB0\fR, and \fBy\fR is less than \fB0\fR, it returns \fBa(y/x) \- pi\fR\. If \fBx\fR is equal to \fB0\fR, and \fBy\fR is greater than \fB0\fR, it returns \fBpi/2\fR\. If \fBx\fR is equal to \fB0\fR, and \fBy\fR is less than \fB0\fR, it returns \fB\-pi/2\fR\. -. -.IP -This function is the same as the \fBatan2()\fR function in many programming languages\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBsin(x)\fR -Returns the sine of \fBx\fR, which is assumed to be in radians\. -. -.IP -This is an alias of \fBs(x)\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBcos(x)\fR -Returns the cosine of \fBx\fR, which is assumed to be in radians\. -. -.IP -This is an alias of \fBc(x)\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBtan(x)\fR -Returns the tangent of \fBx\fR, which is assumed to be in radians\. -. -.IP -If \fBx\fR is equal to \fB1\fR or \fB\-1\fR, this raises an error and causes bc(1) to reset (see the RESET section)\. -. -.IP -This is an alias of \fBt(x)\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBatan(x)\fR -Returns the arctangent of \fBx\fR, in radians\. -. -.IP -This is an alias of \fBa(x)\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBatan2(y, x)\fR -Returns the arctangent of \fBy/x\fR, in radians\. If both \fBy\fR and \fBx\fR are equal to \fB0\fR, it raises an error and causes bc(1) to reset (see the RESET section)\. Otherwise, if \fBx\fR is greater than \fB0\fR, it returns \fBa(y/x)\fR\. If \fBx\fR is less than \fB0\fR, and \fBy\fR is greater than or equal to \fB0\fR, it returns \fBa(y/x) + pi\fR\. If \fBx\fR is less than \fB0\fR, and \fBy\fR is less than \fB0\fR, it returns \fBa(y/x) \- pi\fR\. If \fBx\fR is equal to \fB0\fR, and \fBy\fR is greater than \fB0\fR, it returns \fBpi/2\fR\. If \fBx\fR is equal to \fB0\fR, and \fBy\fR is less than \fB0\fR, it returns \fB\-pi/2\fR\. -. -.IP -This function is the same as the \fBatan2()\fR function in many programming languages\. -. -.IP -This is an alias of \fBa2(y, x)\fR\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBr2d(x)\fR -Converts \fBx\fR from radians to degrees and returns the result\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBd2r(x)\fR -Converts \fBx\fR from degrees to radians and returns the result\. -. -.IP -This is a \fItranscendental function\fR\. -. -.TP -\fBfrand(p)\fR -Generates a pseudo\-random number between \fB0\fR (inclusive) and \fB1\fR (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \fBp\fR\. If \fBp\fR is not \fB0\fR, then calling this function will change the value of \fBseed\fR\. If \fBp\fR is \fB0\fR, then \fB0\fR is returned, and \fBseed\fR is not changed\. -. -.TP -\fBifrand(i, p)\fR -Generates a pseudo\-random number that is between \fB0\fR (inclusive) and the truncated absolute value of \fBi\fR (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \fBp\fR\. If the absolute value of \fBi\fR is greater than or equal to \fB2\fR, and \fBp\fR is not \fB0\fR, then calling this function will change the value of \fBseed\fR, otherwise, \fB0\fR is returned and \fBseed\fR is not changed\. -. -.TP -\fBsrand(x)\fR -Returns \fBx\fR with its sign flipped with probability \fB0\.5\fR\. In other words, it randomizes the sign of \fBx\fR\. -. -.TP -\fBbrand()\fR -Returns a random boolean value (either \fB0\fR or \fB1\fR)\. -. -.TP -\fBubytes(x)\fR -Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \fBx\fR\. -. -.TP -\fBsbytes(x)\fR -Returns the numbers of signed, two\'s\-complement integer bytes required to hold the truncated value of \fBx\fR\. -. -.TP -\fBhex(x)\fR -Outputs the hexadecimal (base \fB16\fR) representation of \fBx\fR\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBbinary(x)\fR -Outputs the binary (base \fB2\fR) representation of \fBx\fR\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBoutput(x, b)\fR -Outputs the base \fBb\fR representation of \fBx\fR\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBuint(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as an unsigned integer in as few power of two bytes as possible\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBint(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as a signed, two\'s\-complement integer in as few power of two bytes as possible\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBuintn(x, n)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as an unsigned integer in \fBn\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer, is negative, or cannot fit into \fBn\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBintn(x, n)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as a signed, two\'s\-complement integer in \fBn\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer or cannot fit into \fBn\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBuint8(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as an unsigned integer in \fB1\fR byte\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer, is negative, or cannot fit into \fB1\fR byte, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBint8(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as a signed, two\'s\-complement integer in \fB1\fR byte\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer or cannot fit into \fB1\fR byte, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBuint16(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as an unsigned integer in \fB2\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer, is negative, or cannot fit into \fB2\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBint16(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as a signed, two\'s\-complement integer in \fB2\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer or cannot fit into \fB2\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBuint32(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as an unsigned integer in \fB4\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer, is negative, or cannot fit into \fB4\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBint32(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as a signed, two\'s\-complement integer in \fB4\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer or cannot fit into \fB4\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBuint64(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as an unsigned integer in \fB8\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer, is negative, or cannot fit into \fB8\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBint64(x)\fR -Outputs the representation, in binary and hexadecimal, of \fBx\fR as a signed, two\'s\-complement integer in \fB8\fR bytes\. Both outputs are split into bytes separated by spaces\. -. -.IP -If \fBx\fR is not an integer or cannot fit into \fB8\fR bytes, an error message is printed instead, but bc(1) is not reset (see the RESET section)\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBhex_uint(x, n)\fR -Outputs the representation of the truncated absolute value of \fBx\fR as an unsigned integer in hexadecimal using \fBn\fR bytes\. Not all of the value will be output if \fBn\fR is too small\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBbinary_uint(x, n)\fR -Outputs the representation of the truncated absolute value of \fBx\fR as an unsigned integer in binary using \fBn\fR bytes\. Not all of the value will be output if \fBn\fR is too small\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBoutput_uint(x, n)\fR -Outputs the representation of the truncated absolute value of \fBx\fR as an unsigned integer in the current \fI\fBobase\fR\fR using \fBn\fR bytes\. Not all of the value will be output if \fBn\fR is too small\. -. -.IP -This is a \fIvoid function\fR\. -. -.TP -\fBoutput_byte(x, i)\fR -Outputs byte \fBi\fR of the truncated absolute value of \fBx\fR, where \fB0\fR is the least significant byte and \fBnumber_of_bytes \- 1\fR is the most significant byte\. -. -.IP -This is a \fIvoid function\fR\. -. -.P - \fI\fR -. -.SS "Transcendental Functions" -All transcendental functions can return slightly inaccurate results (up to 1 ULP \fIhttps://en\.wikipedia\.org/wiki/Unit_in_the_last_place\fR)\. This is unavoidable, and this article \fIhttps://people\.eecs\.berkeley\.edu/~wkahan/LOG10HAF\.TXT\fR explains why it is impossible and unnecessary to calculate exact results for the transcendental functions\. -. -.P -Because of the possible inaccuracy, I recommend that users call those functions with the precision (\fBscale\fR) set to at least 1 higher than is necessary\. If exact results are \fIabsolutely\fR required, users can double the precision (\fBscale\fR) and then truncate\. -. -.P -The transcendental functions in the standard math library are: -. -.IP "\(bu" 4 -\fBs(x)\fR -. -.IP "\(bu" 4 -\fBc(x)\fR -. -.IP "\(bu" 4 -\fBa(x)\fR -. -.IP "\(bu" 4 -\fBl(x)\fR -. -.IP "\(bu" 4 -\fBe(x)\fR -. -.IP "\(bu" 4 -\fBj(x, n)\fR -. -.IP "" 0 -. -.P -The transcendental functions in the extended math library are: -. -.IP "\(bu" 4 -\fBl2(x)\fR -. -.IP "\(bu" 4 -\fBl10(x)\fR -. -.IP "\(bu" 4 -\fBlog(x, b)\fR -. -.IP "\(bu" 4 -\fBpi(p)\fR -. -.IP "\(bu" 4 -\fBt(x)\fR -. -.IP "\(bu" 4 -\fBa2(y, x)\fR -. -.IP "\(bu" 4 -\fBsin(x)\fR -. -.IP "\(bu" 4 -\fBcos(x)\fR -. -.IP "\(bu" 4 -\fBtan(x)\fR -. -.IP "\(bu" 4 -\fBatan(x)\fR -. -.IP "\(bu" 4 -\fBatan2(y, x)\fR -. -.IP "\(bu" 4 -\fBr2d(x)\fR -. -.IP "\(bu" 4 -\fBd2r(x)\fR -. -.IP "" 0 -. -.SH "RESET" -When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets\. This means that several things happen\. -. -.P -First, any functions that are executing are stopped and popped off the stack\. The behavior is not unlike that of exceptions in programming languages\. Then the execution point is set so that any code waiting to execute (after all functions returned) is skipped\. -. -.P -Thus, when bc(1) resets, it skips any remaining code waiting to be executed\. Then, if it is interactive mode, and the error was not a fatal error (see the EXIT STATUS section), it asks for more input; otherwise, it exits with the appropriate return code\. -. -.P -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" -Most bc(1) implementations use \fBchar\fR types to calculate the value of \fB1\fR decimal digit at a time, but that can be slow\. This bc(1) does something different\. -. -.P -It uses large integers to calculate more than \fB1\fR decimal digit at a time\. If built in a environment where \fBBC_LONG_BIT\fR (see the LIMITS section) is \fB64\fR, then each integer has \fB9\fR decimal digits\. If built in an environment where \fBBC_LONG_BIT\fR is \fB32\fR then each integer has \fB4\fR decimal digits\. This value (the number of decimal digits per large integer) is called \fBBC_BASE_DIGS\fR\. -. -.P -In addition, this bc(1) uses an even larger integer for overflow checking\. This integer type depends on the value of \fBBC_LONG_BIT\fR, but is always at least twice as large as the integer type used to store digits\. -. -.SH "LIMITS" -The following are the limits on bc(1): -. -.TP -\fBBC_LONG_BIT\fR -The number of bits in the \fBlong\fR type in the environment where bc(1) was built\. This determines how many decimal digits can be stored in a single large integer (see the PERFORMANCE section)\. -. -.TP -\fBBC_BASE_DIGS\fR -The number of decimal digits per large integer (see the PERFORMANCE section)\. Depends on \fBBC_LONG_BIT\fR\. -. -.TP -\fBBC_BASE_POW\fR -The max decimal number that each large integer can store (see \fBBC_BASE_DIGS\fR) plus \fB1\fR\. Depends on \fBBC_BASE_DIGS\fR\. -. -.TP -\fBBC_OVERFLOW_MAX\fR -The max number that the overflow type (see the PERFORMANCE section) can hold\. Depends on \fBBC_LONG_BIT\fR\. -. -.TP -\fBBC_BASE_MAX\fR -The maximum output base\. Set at \fBBC_BASE_POW\fR\. -. -.TP -\fBBC_DIM_MAX\fR -The maximum size of arrays\. Set at \fBSIZE_MAX\-1\fR\. -. -.TP -\fBBC_SCALE_MAX\fR -The maximum \fBscale\fR\. Set at \fBBC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBBC_STRING_MAX\fR -The maximum length of strings\. Set at \fBBC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBBC_NAME_MAX\fR -The maximum length of identifiers\. Set at \fBBC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBBC_NUM_MAX\fR -The maximum length of a number (in decimal digits), which includes digits after the decimal point\. Set at \fBBC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBBC_RAND_MAX\fR -The maximum integer (inclusive) returned by the \fBrand()\fR operand, if bc(1) has been built with the extra math option\. Set at \fB2^BC_LONG_BIT\-1\fR\. -. -.TP -Exponent -The maximum allowable exponent (positive or negative)\. Set at \fBBC_OVERFLOW_MAX\fR\. -. -.TP -Number of vars -The maximum number of vars/arrays\. Set at \fBSIZE_MAX\-1\fR\. -. -.P -Actual values can be queried with the \fBlimits\fR statement\. -. -.P -These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem\. In fact, memory should be exhausted before these limits should be hit\. -. -.SH "ENVIRONMENT VARIABLES" -bc(1) recognizes the following environment variables: -. -.TP -\fBPOSIXLY_CORRECT\fR -If this variable exists (no matter the contents), bc(1) behaves as if the \fB\-s\fR option was given\. -. -.TP -\fBBC_ENV_ARGS\fR -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 \fBBC_ENV_ARGS\fR will be processed before arguments and files given on the command\-line\. This gives the user the ability to set up "standard" options and files to be used at every invocation\. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs\. -. -.IP -The code that parses \fBBC_ENV_ARGS\fR will correctly handle quoted arguments, but it does not understand escape sequences\. For example, the string \fB"/home/gavin/some bc file\.bc"\fR will be correctly parsed, but the string \fB"/home/gavin/some \e"bc\e" file\.bc"\fR will include the backslashes\. -. -.IP -The quote parsing will handle either kind of quotes, \fB'\fR or \fB"\fR\. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \fB"some \'bc\' file\.bc"\fR, and vice versa if you have a file with double quotes\. However, handling a file with both kinds of quotes in \fBBC_ENV_ARGS\fR is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell\. -. -.TP -\fBBC_LINE_LENGTH\fR -If this environment variable exists and contains an integer that is greater than \fB1\fR and is less than \fBUINT16_MAX\fR (\fB2^16\-1\fR), bc(1) will output lines to that length, including the backslash (\fB\e\fR)\. The default line length is \fB70\fR\. -. -.TP -\fBBC_EXPR_EXIT\fR -If this variable exists (no matter the contents), bc(1) will exit immediately after executing expressions and files given by the \fB\-e\fR and/or \fB\-f\fR command\-line options (and any equivalents)\. -. -.SH "EXIT STATUS" -bc(1) returns the following exit statuses: -. -.TP -\fB0\fR -No error\. -. -.TP -\fB1\fR -A math error occurred\. This follows standard practice of using \fB1\fR for expected errors, since math errors will happen in the process of normal execution\. -. -.IP -Math errors include divide by \fB0\fR, taking the square root of a negative number, using a negative number as a bound for the pseudo\-random number generator, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required\. -. -.IP -Converting to a hardware integer happens for the second operand of the power (\fB^\fR), places (\fB@\fR), left shift (\fB<<\fR), and right shift (\fB>>\fR) operators and their corresponding assignment operators\. -. -.TP -\fB2\fR -A parse error occurred\. -. -.IP -Parse errors include unexpected \fBEOF\fR, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a \fInamed expression\fR, giving an invalid \fBauto\fR list, having a duplicate \fBauto\fR/function parameter, failing to find the end of a code block, attempting to return a value from a \fBvoid\fR function, attempting to use a variable as a reference, and using any extensions when the option \fB\-s\fR or any equivalents were given\. -. -.TP -\fB3\fR -A runtime error occurred\. -. -.IP -Runtime errors include assigning an invalid number to \fBibase\fR, \fBobase\fR, or \fBscale\fR; give a bad expression to a \fBread()\fR call, calling \fBread()\fR inside of a \fBread()\fR call, type errors, passing the wrong number of parameters to functions, attempting to call an undefined function, and attempting to use a \fBvoid\fR function call as a value in an expression\. -. -.TP -\fB4\fR -A fatal error occurred\. -. -.IP -Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options\. -. -.P -The exit status \fB4\fR is special; when a fatal error occurs, bc(1) always exits and returns \fB4\fR, no matter what mode bc(1) is in\. -. -.P -The other statuses will only be returned when bc(1) is not in interactive mode (see the INTERACTIVE MODE section), since bc(1) resets its state (see the RESET section) and accepts more input when one of those errors occurs in interactive mode\. This is also the case when interactive mode is forced by the \fB\-i\fR flag or \fB\-\-interactive\fR option\. -. -.P -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 \fB\-i\fR flag or \fB\-\-interactive\fR option\. -. -.SH "INTERACTIVE MODE" -Per the standard \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR, bc(1) has an interactive mode and a non\-interactive mode\. Interactive mode is turned on automatically when both \fBstdin\fR and \fBstdout\fR are hooked to a terminal, but the \fB\-i\fR flag and \fB\-\-interactive\fR option can turn it on in other cases\. -. -.P -In interactive mode, bc(1) attempts to recover from errors (see the RESET section), and in normal execution, flushes \fBstdout\fR as soon as execution is done for the current input\. -. -.SH "TTY MODE" -If \fBstdin\fR, \fBstdout\fR, and \fBstderr\fR are all connected to a TTY, bc(1) turns on "TTY mode\." -. -.P -TTY mode is required for history to be enabled (see the COMMAND LINE HISTORY section)\. It is also required to enable special handling for \fBSIGINT\fR signals\. -. -.P -TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR, and interactive mode requires only \fBstdin\fR and \fBstdout\fR to be connected to a terminal\. -. -.SH "SIGNAL HANDLING" -Sending a \fBSIGINT\fR will cause bc(1) to stop execution of the current input\. If bc(1) is in TTY mode (see the TTY MODE section), it will reset (see the RESET section)\. Otherwise, it will clean up and exit\. -. -.P -Note that "current input" can mean one of two things\. If bc(1) is processing input from \fBstdin\fR in TTY mode, it will ask for more input\. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \fBstdin\fR if no other file exists\. -. -.P -This means that if a \fBSIGINT\fR is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file\. This is by design; most files that users execute when interacting with bc(1) have function definitions, which are quick to parse\. If a file takes a long time to execute, there may be a bug in that file\. The rest of the files could still be executed without problem, allowing the user to continue\. -. -.P -\fBSIGTERM\fR and \fBSIGQUIT\fR cause bc(1) to clean up and exit, and it uses the default handler for all other signals\. The one exception is \fBSIGHUP\fR, if bc(1) was built with history support; in that case, when bc(1) is in TTY mode, a \fBSIGHUP\fR will cause bc(1) to clean up and exit\. -. -.SH "COMMAND LINE HISTORY" -bc(1) supports interactive command\-line editing, if compiled with the history option enabled\. If bc(1) is in TTY mode (see the TTY MODE section), history is enabled\. Previous lines can be recalled and edited with the arrow keys\. -. -.P -\fBNote\fR: when bc(1) is built with history support, tabs are converted to 8 spaces\. -. -.SH "LOCALES" -This bc(1) ships with support for adding error messages for different locales\. -. -.SH "SEE ALSO" -dc(1) -. -.SH "STANDARDS" -bc(1) is compliant with the IEEE Std 1003\.1\-2017 (“POSIX\.1\-2017â€) \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR specification\. The flags \fB\-efghiqsvVw\fR, all long options, and the extensions noted above are extensions to that specification\. -. -.P -Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\fB\.\fR) as a radix point, regardless of the value of \fBLC_NUMERIC\fR\. -. -.P -This bc(1) ships with support for adding error messages for different locales, so it supports \fBLC_MESSAGES\fR\. -. -.SH "AUTHOR" -This bc(1) was made from scratch by Gavin D\. Howard\. -. -.SH "BUGS" -None are known\. Report bugs at https://git\.yzena\.com/gavin/bc\. diff --git a/manuals/bc.1.md.in b/manuals/bc.1.md.in new file mode 100644 index 000000000000..ed2fa8beae7b --- /dev/null +++ b/manuals/bc.1.md.in @@ -0,0 +1,1814 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +{{ A N P NP }} +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. +{{ end }} +{{ E EN EP ENP }} +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). +{{ end }} + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +{{ A H N P HN HP NP HNP }} +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed +{{ end }} + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + +{{ A H N P HN HP NP HNP }} + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. +{{ end }} + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + +{{ A H N P HN HP NP HNP }} + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. +{{ end }} + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included +{{ A H N P HN HP NP HNP }} + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. +{{ end }} + +**-P**, **--no-prompt** + +{{ A E H N EH EN HN EHN }} +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). +{{ end }} +{{ P EP HP NP EHP ENP HNP EHNP }} +: This option is a no-op. +{{ end }} + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +{{ A H N P HN HP NP HNP }} +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +min allowable value for **obase** is **2**. Values are output in the specified +base. +{{ end }} + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +{{ A H N P HN HP NP HNP }} +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. +{{ end }} + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +{{ A H N P HN HP NP HNP }} +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. +{{ end }} + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +{{ A H N P HN HP NP HNP }} +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. +{{ end }} + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +{{ A H N P HN HP NP HNP }} +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** +{{ end }} + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +{{ A H N P HN HP NP HNP }} +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** +{{ end }} + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +{{ A H N P HN HP NP HNP }} +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. +{{ end }} + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +{{ A H N P HN HP NP HNP }} +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. +{{ end }} + +{{ A H N P HN HP NP HNP }} +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** +{{ end }} + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +{{ A H N P HN HP NP HNP }} + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. +{{ end }} + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +{{ A H N P HN HP NP HNP }} +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. +{{ end }} + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +{{ A H N P HN HP NP HNP }} +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. +{{ end }} + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +{{ A H N P HN HP NP HNP }} +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). +{{ end }} + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +{{ A H N P HN HP NP HNP }} +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** +{{ end }} + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +{{ A H N P HN HP NP HNP }} +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. +{{ end }} + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + +{{ A H N P HN HP NP HNP }} + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. +{{ end }} + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +{{ A E N P EN EP NP ENP }} +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. +{{ end }} + +{{ A E H N EH EN HN EHN }} +The prompt is enabled in TTY mode. +{{ end }} + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +{{ A E N P EN EP NP ENP }} +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. +{{ end }} +{{ H EH HN HP EHN EHP HNP EHNP }} +default handler for all other signals. +{{ end }} + +{{ A E N P EN EP NP ENP }} +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. +{{ end }} + +{{ A E H P EH EP HP EHP }} +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. +{{ end }} + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +{{ A E H P EH EP HP EHP }} +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. +{{ end }} + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc.1.ronn b/manuals/bc.1.ronn deleted file mode 100644 index 3f62333e73e7..000000000000 --- a/manuals/bc.1.ronn +++ /dev/null @@ -1,1556 +0,0 @@ -bc(1) -- arbitrary-precision arithmetic language and calculator -=============================================================== - -SYNOPSIS --------- - -`bc` [`-ghilPqsvVw`] [`--global-stacks`] [`--help`] [`--interactive`] -[`--mathlib`] [`--no-prompt`] [`--quiet`] [`--standard`] [`--warn`] -[`--version`] [`-e` *expr*] [`--expression=`*expr*...] [`-f` *file*...] -[`-file=`*file*...] [*file*...] - -DESCRIPTION ------------ - -bc(1) is an interactive processor for a language first standardized in 1991 by -POSIX. (The current standard is [here][1].) The language provides unlimited -precision decimal arithmetic and is somewhat C-like, but there are differences. -Such differences will be noted in this document. - -After parsing and handling options, this bc(1) reads any files given on the -command line and executes them before reading from `stdin`. - -With all build options, except for extra math, enabled this bc(1) is a drop-in -replacement for ***any*** bc(1), including (and especially) the GNU bc(1). It is -also a drop-in replacement for any bc(1) if extra math is enabled, but it will -have extra features not found in other bc(1) implementations. - -OPTIONS -------- - -The following are the options that bc(1) accepts. - - * `-g`, `--global-stacks`: - Turns the globals `ibase`, `obase`, and `scale` into stacks. This includes - `seed` if bc(1) was built with the extra math option. - - This has the effect that a copy of the current value of all three are pushed - onto a stack for every function call, as well as popped when every function - returns. This means that functions can assign to any and all of those - globals without worrying that the change will affect other functions. - Thus, `output(x,b)` (in the [extended library](#extended-library)) could - have been written like this: - - `define void output(x, b) { obase=b; x }` - - instead of like this: - - `define void output(x, b) { auto c; c=obase; obase=b; x; obase=c }` - - This makes writing functions much easier. - - However, since using this flag means that functions cannot set `ibase`, - `obase`, or `scale` globally, functions that are made to do so cannot work - anymore. There are two possible use cases for that, and each has a solution. - - First, if a function is called on startup to turn bc(1) into a number - converter, it is possible to replace that capability with various shell - aliases. Examples: - - `alias d2o="bc -e ibase=A -e obase=8"; alias h2b="bc -e ibase=G -e obase=2"` - - Second, if the purpose of a function is to set `ibase`, `obase`, or `scale` - globally for any other purpose, it could be split into one to three - functions (based on how many globals it sets) and each of those functions - could return the desired value for a global. - - For functions that set `seed`, the value assigned to `seed` is not - propagated to parent functions. This means that the sequence of - pseudo-random numbers that they see will not be the same sequence of - pseudo-random numbers that any parent sees. This is only the case once - `seed` has been set. - - If a function desires to not affect the sequence of pseudo-random numbers - of its parents, but wants to use the same `seed`, it can use the following - line: - - `seed = seed` - - If the behavior of this option is desired for every run of bc(1), then users - could make sure to define `BC_ENV_ARGS` and include this option (see the - ENVIRONMENT VARIABLES section for more details). - - If `-s`, `-w`, or any equivalents are used, this option is ignored. - - This is a **non-portable extension**. - - * `-h`, `--help`: - Prints a usage message and quits. - - * `-i`, `--interactive`: - Forces interactive mode. (See the INTERACTIVE MODE section.) - - This is a **non-portable extension**. - - * `-l`, `--mathlib`: - Sets `scale` (see the Scale section) to `20` and loads the included math - library before running any code, including any expressions or files - specified on the command line. - - To learn what is in the library, see the LIBRARY section. - - * `-P`, `--no-prompt`: - Disables the prompt in interactive mode. This is mostly for those users that - do not want a prompt or are not used to having them in `bc`. Most of those - users would want to put this option in `BC_ENV_ARGS`. - - If the prompt has been disabled while building bc(1), this option is a - no-op. - - This is a **non-portable extension**. - - * `-q`, `--quiet`: - Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. - - This is mostly for compatibility with the [GNU bc(1)][2]. - - This is a **non-portable extension**. - - * `-s`, `--standard`: - Process exactly the language defined by the [standard][1] and error if any - extensions are used. - - This is a **non-portable extension**. - - * `-v`, `-V`, `--version`: - Print the version information (copyright header) and exit. - - This is a **non-portable extension**. - - * `-w`, `--warn`: - Like `-s` and `--standard`, except that warnings (and not errors) are given - for non-standard extensions. - - 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. - - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - `BC_EXPR_EXIT` is defined (see the ENVIRONMENT VARIABLES section). - - This is a **non-portable extension**. - - * `-f` *file*, `--file`=*file*: - Reads in `file` and evaluates it. If expressions are also given (see above), - the expressions are evaluated in the order given. - - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - `BC_EXPR_EXIT` is defined (see the ENVIRONMENT VARIABLES section). - - This is a **non-portable extension**. - -**Note**: long options are only accepted if bc(1) is built with them enabled. - -STDOUT ------- - -Any non-error output is written to `stdout`. - -**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal -error (see the EXIT STATUS section) if it cannot write to `stdout`, so if -`stdout` is closed, as in `bc >&-`, it will quit with an error. This is -done so that bc(1) can report problems when `stdout` is redirected to a file. - -If there are scripts that depend on the behavior of other bc(1) implementations, -it is recommended that those scripts be changed to redirect `stdout` to -`/dev/null`. - -STDERR ------- - -Any error output is written to `stderr`. - -**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal -error (see the EXIT STATUS section) if it cannot write to `stderr`, so if -`stderr` is closed, as in `bc 2>&-`, it will quit with an error. This is -done so that bc(1) can report problems when `stderr` is redirected to a file. - -If there are scripts that depend on the behavior of other bc(1) implementations, -it is recommended that those scripts be changed to redirect `stderr` to -`/dev/null`. - -SYNTAX ------- - -The syntax for bc(1) programs is mostly C-like, with some differences. This -bc(1) follows the [POSIX standard][1], which is a much more thorough resource -for the language this bc(1) accepts. This section is meant to be a summary and a -listing of all the extensions to the [standard][1]. - -In the sections below, `E` means expression, `S` means statement, and `I` means -identifier. - -Identifiers (`I`) start with a lowercase letter and can be followed by any -number (up to `BC_NAME_MAX-1`) of lowercase letters (`a-z`), digits (`0-9`), and -underscores (`_`). The regex is `[a-z][a-z0-9_]*` Identifiers with more than one -character (letter) are a **non-portable extension**. - -`ibase` is a global variable determining how to interpret constant numbers. It -is the "input" base, or the number base used for interpreting input numbers. -`ibase` is initially `10`. If the `-s` (`--standard`) and `-w` (`--warn`) flags -were not given on the command line, the max allowable value for `ibase` is `36`. -Otherwise, it is `16`. The min allowable value for `ibase` is `2`. The max -allowable value for `ibase` can be queried in bc(1) programs with the -`maxibase()` built in function. - -`obase` is a global variable determining how to output results. It is the -"output" base, or the number base used for outputting numbers. `obase` is -initially `10`. The max allowable value for `obase` is `BC_BASE_MAX`. The min -allowable value for `obase` is `2`, unless bc(1) was built with the extra math -option. If it was, then the min allowable value is `0`. In this case, if `obase` -is `0`, values are output in scientific notation, and if `obase` is `1`, values -are output in engineering notation. (Outputting in scientific or engineering -notation are **non-portable extensions**.) The max allowable value for `obase` -can be queried in bc(1) programs with the `maxobase()` built in function. - -The **scale** of an expression is the number of digits in the result of the -expression right of the decimal point, and `scale` is a global variable that -sets the precision of any operations, with exceptions. `scale` is initially `0`. -`scale` cannot be negative. The max allowable value for `scale` can be queried -in bc(1) programs with the `maxscale()` built in function. - -bc(1) has both **global** variables and **local** variables. All **local** -variables are local to the function; they are parameters or are introduced in -the `auto` list of a function (see FUNCTIONS). If a variable is accessed which -is not a parameter or in the `auto` list, it is assumed to be **global**. If a -parent function has a **local** variable version of a **global** variable that -is accessed by a function that it calls, the value of that **global** variable -in the child function is the value of the variable in the parent function, not -the value of the actual **global** variable. - -All of the above applies to arrays as well. - -The value of a statement that is an expression (i.e., any of the -[Named Expressions](#bc-named-expressions) or [Operands](#bc-operands)) is -printed unless the lowest precedence operator is an -[`assignment`](#bc-assignment) operator ***and*** the expression is not -surrounded by parentheses. - -The value that is printed is also assigned to the special variable `last`. A -single dot (`.`) may also be used as a synonym for `last`. These are -**non-portable extensions**. - -Either semicolons or newlines may separate statements. - -### Comments - -There are two kinds of comments: - -1. Block comments are enclosed in `/*` and `*/`. -2. Line comments go from `#` until, and not including, the next newline. This - is a **non-portable extension**. - - - -### Named Expressions - -The following are named expressions in bc(1): - -1. Variables: `I` -2. Array Elements: `I[E]` -3. `ibase` -4. `obase` -5. `scale` -6. `last` or a single dot (`.`) - -Number 6 is a **non-portable extension**. - -If bc(1) was built with the extra math option, the following is also a named -expression: - -1. `seed` - -The meaning of `seed` is dependent on the current pseudo-random number generator -but is guaranteed to not change except for new major versions. - -The **scale** of the value may be significant. - -If a previously used `seed` value is assigned to `seed` and used again, the -pseudo-random number generator is guaranteed to produce the same sequence of -pseudo-random numbers as it did when the `seed` value was previously used. - -The exact value assigned to `seed` is not guaranteed to be returned if `seed` is -queried again immediately. However, if `seed` *does* return a different value, -both values, when assigned to `seed`, are guaranteed to produce the same -sequence of pseudo-random numbers. This means that certain values assigned to -`seed` will not produce unique sequences of pseudo-random numbers. The value of -`seed` will change after any use of the `rand()` and `irand(E)` operands, except -if the parameter passed to `irand(E)` is `0` or `1`. - -There is no limit to the length (number of significant decimal digits) or -*scale* of the value that can be assigned to `seed`. - -This command is only available if bc(1) was built with the extra math option. - -This is a **non-portable extension**. - -Variables and arrays do not interfere; users can have arrays named the same as -variables. This also applies to functions (see the FUNCTIONS section), so a user -can have a variable, array, and function that all have the same name, and they -will not shadow each other. - -Named expressions are required as the operand of -[`increment`/`decrement` operators](#bc-increment-decrement) and as the left -side of [`assignment` operators](#bc-assignment). - - - -### Operands - -The following are valid operands in bc(1): - -1. Numbers (see [Numbers](#bc-numbers) below). -2. Array indices (`I[E]`). -3. `(E)`: The value of `E` (used to change precedence). -4. `sqrt(E)`: The square root of `E`. `E` must be non-negative. -5. `length(E)`: The number of significant decimal digits in `E`. -6. `length(I[])`: The number of elements in the array `I`. This is a - **non-portable extension**. -7. `scale(E)`: The **scale** of `E`. -8. `abs(E)`: The absolute value of `E`. This is a **non-portable extension**. -9. `I()`, `I(E)`, `I(E, E)`, and so on, where `I` is an identifier for a - non-[void function](#void-functions). The `E` parameters may also be arrays, - which will automatically be turned into [array - references](#array-references) if the corresponding parameter is an array - reference. -10. `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**. -11. `maxibase()`: The max allowable `ibase`. This is a **non-portable - extension**. -12. `maxobase()`: The max allowable `obase`. This is a **non-portable - extension**. -13. `maxscale()`: The max allowable `scale`. This is a **non-portable - extension**. - -If bc(1) was built with the extra math option, the following are also valid -operands: - -1. `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**. -2. `irand(E)`: A pseudo-random integer between `0` (inclusive) and the - value of `E` (exclusive). If `E` is negative or is a non-integer (**scale** - is not `0`), an error is raised, and bc(1) resets (see the RESET section). - If `E` is larger than `BC_RAND_MAX`, the higher bound is honored by - generating several pseudo-random integers, multiplying them by appropriate - powers of `BC_RAND_MAX + 1`, and adding them together. Thus, the size of - integer that can be generated with this operand is unbounded. Using this - operand will change the value of `seed`. If `E` is `0` or `1`, then `0` is - returned, and `seed` is not changed. This is a **non-portable extension**. -3. `maxrand()`: The max integer returned by `rand()`. This is a **non-portable - extension**. - -The integers generated by `rand()` and `irand(E)` are guaranteed to be as -unbiased as possible, subject to the limitations of the pseudo-random number -generator. - -**Note**: The values returned by the pseudo-random number generator with -`rand()` and `irand(E)` are guaranteed to **NOT** be cryptographically-secure. -This is a consequence of using a seeded pseudo-random number generator. However, -they **are** guaranteed to be reproducible with identical `seed` values. - - - -### Numbers - -Numbers are strings made up of digits, uppercase letters, and at most `1` period -for a radix. Numbers can have up to `BC_NUM_MAX` digits. Uppercase letters -equal `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`) take the value that they would have if they -were valid digits, regardless of the value of `ibase`. This means that `A` -always equals decimal `10` and `Z` always equals decimal `35`. - -In addition, if bc(1) was built with the extra math option, it accepts numbers -in scientific notation. For bc(1), an example is `1.89237e9`, which is equal to -`1892370000`. Negative exponents are also allowed, so `4.2890e-3` is equal to -`0.0042890`. - -Using scientific notation is an error or warning if the `-s` or `-w`, -respectively, command-line options (or equivalents) are given. - -**WARNING**: Both the number and the exponent in scientific notation are -interpreted according to the current `ibase`, but the number is still multiplied -by `10^exponent` regardless of the current `ibase`. For example, if `ibase` is -`16` and bc(1) is given the number string `"FFeA"`, the resulting decimal number -will be `2550000000000`, and if bc(1) is given the number string `"10e-4"`, the -resulting decimal number will be `0.0016`. - -Accepting input as scientific notation is a **non-portable extension**. - -### Operators - -The following arithmetic and logical operators can be used. They are listed in -order of decreasing precedence. Operators in the same group have the same -precedence. - - * `++` `--`: - Type: Prefix and Postfix - - Associativity: None - - Description: `increment`, `decrement` - - * `-` `!`: - Type: Prefix - - Associativity: None - - Description: `negation`, `boolean not` - - * `$`: - Type: Postfix - - Associativity: None - - Description: `truncation` - - * `@`: - Type: Binary - - Associativity: Right - - Description: `set precision` - - * `^`: - Type: Binary - - Associativity: Right - - Description: `power` - - * `*` `/` `%`: - Type: Binary - - Associativity: Left - - Description: `multiply`, `divide`, `modulus` - - * `+` `-`: - Type: Binary - - Associativity: Left - - Description: `add`, `subtract` - - * `<<` `>>`: - Type: Binary - - Associativity: Left - - Description: `shift left`, `shift right` - - * `=` `<<=` `>>=` `+=` `-=` `*=` `/=` `%=` `^=` `@=`: - Type: Binary - - Associativity: Right - - Description: `assignment` - - * `==` `<=` `>=` `!=` `<` `>`: - Type: Binary - - Associativity: Left - - Description: `relational` - - * `&&`: - Type: Binary - - Associativity: Left - - Description: `boolean and` - - * `||`: - Type: Binary - - Associativity: Left - - Description: `boolean or` - -The operators will be described in more detail below. - - - - * `++` `--`: - The prefix and postfix `increment` and `decrement` operators behave exactly - like they would in C. They require a [named expression](#named-expressions) - as an operand. - - The prefix versions of these operators are more efficient; use them where - possible. - - * `-`: - The `negation` operator returns `0` if a user attempts to negate any - expression with the value `0`. Otherwise, a copy of the expression with its - sign flipped is returned. - - * `!`: - The `boolean not` operator returns `1` if the expression is `0`, or `0` - otherwise. - - This is a **non-portable extension**. - - * `$`: - The `truncation` operator returns a copy of the given expression with all of - its **scale** removed. - - This is a **non-portable extension**. - - This is only available if bc(1) has been compiled with the extra math option - enabled. - - * `@`: - The `set precision` operator takes two expressions and returns a copy of the - first with its **scale** equal to the value of the second expression. That - could either mean that the number is returned without change (if the - **scale** of the first expression matches the value of the second - expression), extended (if it is less), or truncated (if it is more). - - The second expression must be an integer (no **scale**) and non-negative. - - This is a **non-portable extension**. - - This is only available if bc(1) has been compiled with the extra math option - enabled. - - * `^`: - The `power` operator (not the `exclusive or` operator, as it would be in C) - takes two expressions and raises the first to the power of the value of the - second. - - The second expression must be an integer (no **scale**), and if it is - negative, the first value must be non-zero. - - * `*`: - The `multiply` operator takes two expressions, multiplies them, and returns - the product. If `a` is the **scale** of the first expression and `b` is the - **scale** of the second expression, the scale of the result is equal to - `min(a+b,max(scale,a,b))` where `min` and `max` return the obvious values. - - * `/`: - The `divide` operator takes two expressions, divides them, and returns the - quotient. The scale of the result shall be the value of `scale`. - - The second expression must be non-zero. - - * `%`: - The `modulus` operator takes two expressions, `a` and `b`, and evaluates - them by 1) Computing `a/b` to current `scale` and 2) Using the result of - step 1 to calculate `a-(a/b)*b` to scale `max(scale+scale(b),scale(a))`. - - The second expression must be non-zero. - - * `+`: - The `add` operator takes two expressions, `a` and `b`, and returns the sum, - with a **scale** equal to the max of the **scale**s of `a` and `b`. - - * `-`: - The `subtract` operator takes two expressions, `a` and `b`, and returns the - difference, with a **scale** equal to the max of the **scale**s of `a` and - `b`. - - * `<<`: - The `left shift` operator takes two expressions, `a` and `b`, and returns a - copy of the value of `a` with its decimal point moved `b` places to the - right. - - The second expression must be an integer (no **scale**) and non-negative. - - This is a **non-portable extension**. - - This is only available if bc(1) has been compiled with the extra math option - enabled. - - * `>>`: - The `right shift` operator takes two expressions, `a` and `b`, and returns a - copy of the value of `a` with its decimal point moved `b` places to the - left. - - The second expression must be an integer (no **scale**) and non-negative. - - This is a **non-portable extension**. - - This is only available if bc(1) has been compiled with the extra math option - enabled. - - - - * `=` `<<=` `>>=` `+=` `-=` `*=` `/=` `%=` `^=` `@=`: - The `assignment` operators take two expressions, `a` and `b` where `a` is a - [named expression](#bc-named-expressions). - - For `=`, `b` is copied and the result is assigned to `a`. For all others, - `a` and `b` are applied as operands to the corresponding arithmetic - operator and the result is assigned to `a`. - - The `assignment` operators that correspond to operators that are extensions - are themselves extensions. - - Also, those `assignment` operators that are extensions are only available if - bc(1) has been compiled with the extra math option enabled. - - * `==` `<=` `>=` `!=` `<` `>`: - The `relational` operators compare two expressions, `a` and `b`, and if the - relation holds, according to C language semantics, the result is `1`. - Otherwise, it is `0`. - - Note that unlike in C, these operators have a lower precedence than the - `assignment` operators, which means that `a=b>c` is interpreted as - `(a=b)>c`. - - Also, unlike the [standard][1] requires, these operators can appear anywhere - any other expressions can be used. This allowance is a - **non-portable extension**. - - * `&&`: - The `boolean and` operator takes two expressions and returns `1` if both - expressions are non-zero, `0` otherwise. - - This is ***not*** a short-circuit operator. - - This is a **non-portable extension**. - - * `||`: - The `boolean or` operator takes two expressions and returns `1` if one of - the expressions is non-zero, `0` otherwise. - - This is ***not*** a short-circuit operator. - - This is a **non-portable extension**. - -### Statements - -The following items are statements: - -1. `E` -2. `{` `S` `;` ... `;` `S` `}` -3. `if` `(` `E` `)` `S` -4. `if` `(` `E` `)` `S` `else` `S` -5. `while` `(` `E` `)` `S` -6. `for` `(` `E` `;` `E` `;` `E` `)` `S` -7. An empty statement -8. `break` -9. `continue` -10. `quit` -11. `halt` -12. `limits` -13. A string of characters, enclosed in double quotes -14. `print` `E` `,` ... `,` `E` -15. `I()`, `I(E)`, `I(E, E)`, and so on, where `I` is an identifier for a - [void function](#void-functions). The `E` parameters may also be arrays, - which will automatically be turned into [array - references](#array-references) if the corresponding parameter is an array - reference. - -Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. - -Also, as a **non-portable extension**, any or all of the expressions in the -header of a for loop may be omitted. If the condition (second expression) is -omitted, it is assumed to be a constant `1`. - -The `break` statement causes a loop to stop iterating and resume execution -immediately following a loop. This is only allowed in loops. - -The `continue` statement causes a loop iteration to stop early and returns to -the start of the loop, including testing the loop condition. This is only -allowed in loops. - -The `if` `else` statement does the same thing as in C. - -The `quit` statement causes bc(1) to quit, even if it is on a branch that will -not be executed (it is a compile-time command). - -The `halt` statement causes bc(1) to quit, if it is executed. (Unlike `quit` if -it is on a branch of an `if` statement that is not executed, bc(1) does not -quit.) - -The `limits` statement prints the limits that this bc(1) is subject to. This is -like the `quit` statement in that it is a compile-time command. - -An expression by itself is evaluated and printed, followed by a newline. If -bc(1) has been built with the extra math option enabled, both scientific -notation and engineering notation are available for printing the results of -expressions. Scientific notation is activated by assigning `0` to `obase` (in -any other context, an `obase` of `0` is invalid), and engineering notation is -activated by assigning `1` to `obase` (which is also invalid in any other -context). To deactivate them, just assign a different value to `obase`. - -Scientific notation and engineering notation are disabled if bc(1) is run with -either the `-s` or `-w` command-line options (or equivalents). - -Printing numbers in scientific notation and/or engineering notation is a -**non-portable extension**. - -### Print Statement - -The "expressions" in a `print` statement may also be strings. If they are, there -are backslash escape sequences that are interpreted specially. What those -sequences are, and what they cause to be printed, are shown below: - - * `\a`: - `\a` - - * `\b`: - `\b` - - * `\\`: - `\` - - * `\e`: - `\` - - * `\f`: - `\f` - - * `\n`: - `\n` - - * `\q`: - `"` - - * `\r`: - `\r` - - * `\t`: - `\t` - -Any other character following a backslash causes the backslash and character to -be printed as-is. - -Any non-string expression in a print statement shall be assigned to `last`, like -any other expression that is printed. - -### Order of Evaluation - -All expressions in a statment are evaluated left to right, except as necessary -to maintain order of operations. This means, for example, that in the expression -`i = 0; a[i++] = i++`, the first (or 0th) element of `a` is set to `1`, and `i` -is equal to `2` at the end of the expression. - -This includes function arguments. Thus, this means that in the expression -`i = 0; x(i++, i++)`, the first argument passed to `x()` is `0`, and the second -argument is `1`, while `i` is equal to `2` before the function starts executing. - -FUNCTIONS ---------- - -Function definitions are as follows: - -``` -define I(I,...,I){ - auto I,...,I - S;...;S - return(E) -} -``` - -Any `I` in the parameter list or `auto` list may be replaced with `I[]` to make -a parameter or `auto` var an array, and any `I` in the parameter list may be -replaced with `*I[]` to make a parameter an array reference. Callers of -functions that take array references should not put an asterisk in the call; -they must be called with just `I[]` like normal array parameters and will be -automatically converted into references. - -As a **non-portable extension**, the opening brace of a `define` statement may -appear on the next line. - -The return statement may also be in the following forms: - -1. `return` -2. `return` `(` `)` -3. `return` `E` - -The first two, or not specifying a `return` statement, is equivalent to -`return (0)`, unless the function is a [void function](#void-functions). - - - -### Void Functions - -Functions can also be void functions, defined as follows: - -``` -define void I(I,...,I){ - auto I,...,I - S;...;S - return -} -``` - -They can only be used as standalone expressions, where such an expression would -be printed alone, except in a print statement. - -Void functions can only use the first two `return` statements listed above. They -can also omit the return statement entirely. - -The word `void` is not treated as a keyword; it is still possible to have -variables, arrays, and functions named `void`. The word `void` is only treated -specially right after the `define` keyword. - -This is a **non-portable extension**. - - - -### Array References - -For any array in the parameter list, if the array is declared in the form - -``` -*I[] -``` - -it is a **reference**. Any changes to the array in the function are reflected, -when the function returns, to the array that was passed in. - -Other than this, all function arguments are passed by value. - -This is a **non-portable extension**. - -LIBRARY -------- - -All of the functions below, including the functions in the -[extended library](#extended-library) if bc(1) has been compiled with the extra -math option enabled, are available when the `-l` or `--mathlib` command-line -flags are given. - - - -### Standard Library - -The [standard][1] defines the following functions for the math library: - - * `s(x)`: - Returns the sine of `x`, which is assumed to be in radians. - - This is a [transcendental function][5]. - - * `c(x)`: - Returns the cosine of `x`, which is assumed to be in radians. - - This is a [transcendental function][5]. - - * `a(x)`: - Returns the arctangent of `x`, in radians. - - This is a [transcendental function][5]. - - * `l(x)`: - Returns the natural logarithm of `x`. - - This is a [transcendental function][5]. - - * `e(x)`: - Returns the mathematical constant `e` raised to the power of `x`. - - This is a [transcendental function][5]. - - * `j(x, n)`: - Returns the bessel integer order `n` (truncated) of `x`. - - This is a [transcendental function][5]. - - - -### Extended Library - -In addition to the [standard library](#standard-library), if bc(1) has been -built with the extra math option, the following functions are available when -either the `-l` or `--mathlib` options are given. - -However, the extended library is ***not*** loaded when the `-s`/`--standard` or -`-w`/`--warn` options are given since they are not part of the library defined -by the [standard][1]. - -The extended library is a **non-portable extension**. - - * `p(x, y)`: - Calculates `x` to the power of `y`, even if `y` is not an integer, and - returns the result to the current `scale`. - - This is a [transcendental function][5]. - - * `r(x, p)`: - Returns `x` rounded to `p` decimal places according to the rounding mode - [round half away from `0`][3]. - - * `ceil(x, p)`: - Returns `x` rounded to `p` decimal places according to the rounding mode - [round away from `0`][7]. - - * `f(x)`: - Returns the factorial of the truncated absolute value of `x`. - - * `perm(n, k)`: - Returns the permutation of the truncated absolute value of `n` of the - truncated absolute value of `k`, if `k <= n`. If not, it returns `0`. - - * `comb(n, k)`: - Returns the combination of the truncated absolute value of `n` of the - truncated absolute value of `k`, if `k <= n`. If not, it returns `0`. - - * `l2(x)`: - Returns the logarithm base `2` of `x`. - - This is a [transcendental function][5]. - - * `l10(x)`: - Returns the logarithm base `10` of `x`. - - This is a [transcendental function][5]. - - * `log(x, b)`: - Returns the logarithm base `b` of `x`. - - This is a [transcendental function][5]. - - * `cbrt(x)`: - Returns the cube root of `x`. - - * `root(x, n)`: - Calculates the truncated value of `n`, `r`, and returns the `r`th root of - `x` to the current `scale`. - - If `r` is `0` or negative, this raises an error and causes bc(1) to reset - (see the RESET section). It also raises an error and causes bc(1) to reset - if `r` is even and `x` is negative. - - * `pi(p)`: - Returns `pi` to `p` decimal places. - - This is a [transcendental function][5]. - - * `t(x)`: - Returns the tangent of `x`, which is assumed to be in radians. - - This is a [transcendental function][5]. - - * `a2(y, x)`: - Returns the arctangent of `y/x`, in radians. If both `y` and `x` are equal - to `0`, it raises an error and causes bc(1) to reset (see the RESET - section). Otherwise, if `x` is greater than `0`, it returns `a(y/x)`. If `x` - is less than `0`, and `y` is greater than or equal to `0`, it returns - `a(y/x) + pi`. If `x` is less than `0`, and `y` is less than `0`, it returns - `a(y/x) - pi`. If `x` is equal to `0`, and `y` is greater than `0`, it - returns `pi/2`. If `x` is equal to `0`, and `y` is less than `0`, it returns - `-pi/2`. - - This function is the same as the `atan2()` function in many programming - languages. - - This is a [transcendental function][5]. - - * `sin(x)`: - Returns the sine of `x`, which is assumed to be in radians. - - This is an alias of `s(x)`. - - This is a [transcendental function][5]. - - * `cos(x)`: - Returns the cosine of `x`, which is assumed to be in radians. - - This is an alias of `c(x)`. - - This is a [transcendental function][5]. - - * `tan(x)`: - Returns the tangent of `x`, which is assumed to be in radians. - - If `x` is equal to `1` or `-1`, this raises an error and causes bc(1) to - reset (see the RESET section). - - This is an alias of `t(x)`. - - This is a [transcendental function][5]. - - * `atan(x)`: - Returns the arctangent of `x`, in radians. - - This is an alias of `a(x)`. - - This is a [transcendental function][5]. - - * `atan2(y, x)`: - Returns the arctangent of `y/x`, in radians. If both `y` and `x` are equal - to `0`, it raises an error and causes bc(1) to reset (see the RESET - section). Otherwise, if `x` is greater than `0`, it returns `a(y/x)`. If `x` - is less than `0`, and `y` is greater than or equal to `0`, it returns - `a(y/x) + pi`. If `x` is less than `0`, and `y` is less than `0`, it returns - `a(y/x) - pi`. If `x` is equal to `0`, and `y` is greater than `0`, it - returns `pi/2`. If `x` is equal to `0`, and `y` is less than `0`, it returns - `-pi/2`. - - This function is the same as the `atan2()` function in many programming - languages. - - This is an alias of `a2(y, x)`. - - This is a [transcendental function][5]. - - * `r2d(x)`: - Converts `x` from radians to degrees and returns the result. - - This is a [transcendental function][5]. - - * `d2r(x)`: - Converts `x` from degrees to radians and returns the result. - - This is a [transcendental function][5]. - - * `frand(p)`: - Generates a pseudo-random number between `0` (inclusive) and `1` (exclusive) - with the number of decimal digits after the decimal point equal to the - truncated absolute value of `p`. If `p` is not `0`, then calling this - function will change the value of `seed`. If `p` is `0`, then `0` is - returned, and `seed` is not changed. - - * `ifrand(i, p)`: - Generates a pseudo-random number that is between `0` (inclusive) and the - truncated absolute value of `i` (exclusive) with the number of decimal - digits after the decimal point equal to the truncated absolute value of `p`. - If the absolute value of `i` is greater than or equal to `2`, and `p` is not - `0`, then calling this function will change the value of `seed`, otherwise, - `0` is returned and `seed` is not changed. - - * `srand(x)`: - Returns `x` with its sign flipped with probability `0.5`. In other words, it - randomizes the sign of `x`. - - * `brand()`: - Returns a random boolean value (either `0` or `1`). - - * `ubytes(x)`: - Returns the numbers of unsigned integer bytes required to hold the truncated - absolute value of `x`. - - * `sbytes(x)`: - Returns the numbers of signed, two's-complement integer bytes required to - hold the truncated value of `x`. - - * `hex(x)`: - Outputs the hexadecimal (base `16`) representation of `x`. - - This is a [void function](#void-functions). - - * `binary(x)`: - Outputs the binary (base `2`) representation of `x`. - - This is a [void function](#void-functions). - - * `output(x, b)`: - Outputs the base `b` representation of `x`. - - This is a [void function](#void-functions). - - * `uint(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as an unsigned - integer in as few power of two bytes as possible. Both outputs are split - into bytes separated by spaces. - - If `x` is not an integer or is negative, an error message is printed - instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `int(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as a signed, - two's-complement integer in as few power of two bytes as possible. Both - outputs are split into bytes separated by spaces. - - If `x` is not an integer, an error message is printed instead, but bc(1) is - not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `uintn(x, n)`: - Outputs the representation, in binary and hexadecimal, of `x` as an unsigned - integer in `n` bytes. Both outputs are split into bytes separated by spaces. - - If `x` is not an integer, is negative, or cannot fit into `n` bytes, an - error message is printed instead, but bc(1) is not reset (see the RESET - section). - - This is a [void function](#void-functions). - - * `intn(x, n)`: - Outputs the representation, in binary and hexadecimal, of `x` as a signed, - two's-complement integer in `n` bytes. Both outputs are split into bytes - separated by spaces. - - If `x` is not an integer or cannot fit into `n` bytes, an error message is - printed instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `uint8(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as an unsigned - integer in `1` byte. Both outputs are split into bytes separated by spaces. - - If `x` is not an integer, is negative, or cannot fit into `1` byte, an error - message is printed instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `int8(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as a signed, - two's-complement integer in `1` byte. Both outputs are split into bytes - separated by spaces. - - If `x` is not an integer or cannot fit into `1` byte, an error message is - printed instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `uint16(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as an unsigned - integer in `2` bytes. Both outputs are split into bytes separated by spaces. - - If `x` is not an integer, is negative, or cannot fit into `2` bytes, an - error message is printed instead, but bc(1) is not reset (see the RESET - section). - - This is a [void function](#void-functions). - - * `int16(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as a signed, - two's-complement integer in `2` bytes. Both outputs are split into bytes - separated by spaces. - - If `x` is not an integer or cannot fit into `2` bytes, an error message is - printed instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `uint32(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as an unsigned - integer in `4` bytes. Both outputs are split into bytes separated by spaces. - - If `x` is not an integer, is negative, or cannot fit into `4` bytes, an - error message is printed instead, but bc(1) is not reset (see the RESET - section). - - This is a [void function](#void-functions). - - * `int32(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as a signed, - two's-complement integer in `4` bytes. Both outputs are split into bytes - separated by spaces. - - If `x` is not an integer or cannot fit into `4` bytes, an error message is - printed instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `uint64(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as an unsigned - integer in `8` bytes. Both outputs are split into bytes separated by spaces. - - If `x` is not an integer, is negative, or cannot fit into `8` bytes, an - error message is printed instead, but bc(1) is not reset (see the RESET - section). - - This is a [void function](#void-functions). - - * `int64(x)`: - Outputs the representation, in binary and hexadecimal, of `x` as a signed, - two's-complement integer in `8` bytes. Both outputs are split into bytes - separated by spaces. - - If `x` is not an integer or cannot fit into `8` bytes, an error message is - printed instead, but bc(1) is not reset (see the RESET section). - - This is a [void function](#void-functions). - - * `hex_uint(x, n)`: - Outputs the representation of the truncated absolute value of `x` as an - unsigned integer in hexadecimal using `n` bytes. Not all of the value will - be output if `n` is too small. - - This is a [void function](#void-functions). - - * `binary_uint(x, n)`: - Outputs the representation of the truncated absolute value of `x` as an - unsigned integer in binary using `n` bytes. Not all of the value will be - output if `n` is too small. - - This is a [void function](#void-functions). - - * `output_uint(x, n)`: - Outputs the representation of the truncated absolute value of `x` as an - unsigned integer in the current [`obase`](#obase) using `n` bytes. Not all - of the value will be output if `n` is too small. - - This is a [void function](#void-functions). - - * `output_byte(x, i)`: - Outputs byte `i` of the truncated absolute value of `x`, where `0` is the - least significant byte and `number_of_bytes - 1` is the most significant - byte. - - This is a [void function](#void-functions). - - - -### Transcendental Functions - -All transcendental functions can return slightly inaccurate results (up to 1 -[ULP][4]). This is unavoidable, and [this article][6] explains why it is -impossible and unnecessary to calculate exact results for the transcendental -functions. - -Because of the possible inaccuracy, I recommend that users call those functions -with the precision (`scale`) set to at least 1 higher than is necessary. If -exact results are *absolutely* required, users can double the precision -(`scale`) and then truncate. - -The transcendental functions in the standard math library are: - -* `s(x)` -* `c(x)` -* `a(x)` -* `l(x)` -* `e(x)` -* `j(x, n)` - -The transcendental functions in the extended math library are: - -* `l2(x)` -* `l10(x)` -* `log(x, b)` -* `pi(p)` -* `t(x)` -* `a2(y, x)` -* `sin(x)` -* `cos(x)` -* `tan(x)` -* `atan(x)` -* `atan2(y, x)` -* `r2d(x)` -* `d2r(x)` - -RESET ------ - -When bc(1) encounters an error or a signal that it has a non-default handler -for, it resets. This means that several things happen. - -First, any functions that are executing are stopped and popped off the stack. -The behavior is not unlike that of exceptions in programming languages. Then -the execution point is set so that any code waiting to execute (after all -functions returned) is skipped. - -Thus, when bc(1) resets, it skips any remaining code waiting to be executed. -Then, if it is interactive mode, and the error was not a fatal error (see the -EXIT STATUS section), it asks for more input; otherwise, it exits with the -appropriate return code. - -Note that this reset behavior is different from the GNU bc(1), which attempts to -start executing the statement right after the one that caused an error. - -PERFORMANCE ------------ - -Most bc(1) implementations use `char` types to calculate the value of `1` -decimal digit at a time, but that can be slow. This bc(1) does something -different. - -It uses large integers to calculate more than `1` decimal digit at a time. If -built in a environment where `BC_LONG_BIT` (see the LIMITS section) is `64`, -then each integer has `9` decimal digits. If built in an environment where -`BC_LONG_BIT` is `32` then each integer has `4` decimal digits. This value (the -number of decimal digits per large integer) is called `BC_BASE_DIGS`. - -In addition, this bc(1) uses an even larger integer for overflow checking. This -integer type depends on the value of `BC_LONG_BIT`, but is always at least twice -as large as the integer type used to store digits. - -LIMITS ------- - -The following are the limits on bc(1): - - * `BC_LONG_BIT`: - The number of bits in the `long` type in the environment where bc(1) was - built. This determines how many decimal digits can be stored in a single - large integer (see the PERFORMANCE section). - - * `BC_BASE_DIGS`: - The number of decimal digits per large integer (see the PERFORMANCE - section). Depends on `BC_LONG_BIT`. - - * `BC_BASE_POW`: - The max decimal number that each large integer can store (see - `BC_BASE_DIGS`) plus `1`. Depends on `BC_BASE_DIGS`. - - * `BC_OVERFLOW_MAX`: - The max number that the overflow type (see the PERFORMANCE section) can - hold. Depends on `BC_LONG_BIT`. - - * `BC_BASE_MAX`: - The maximum output base. Set at `BC_BASE_POW`. - - * `BC_DIM_MAX`: - The maximum size of arrays. Set at `SIZE_MAX-1`. - - * `BC_SCALE_MAX`: - The maximum `scale`. Set at `BC_OVERFLOW_MAX-1`. - - * `BC_STRING_MAX`: - The maximum length of strings. Set at `BC_OVERFLOW_MAX-1`. - - * `BC_NAME_MAX`: - The maximum length of identifiers. Set at `BC_OVERFLOW_MAX-1`. - - * `BC_NUM_MAX`: - The maximum length of a number (in decimal digits), which includes digits - after the decimal point. Set at `BC_OVERFLOW_MAX-1`. - - * `BC_RAND_MAX`: - The maximum integer (inclusive) returned by the `rand()` operand, if bc(1) - has been built with the extra math option. Set at `2^BC_LONG_BIT-1`. - - * Exponent: - The maximum allowable exponent (positive or negative). Set at - `BC_OVERFLOW_MAX`. - - * Number of vars: - The maximum number of vars/arrays. Set at `SIZE_MAX-1`. - -Actual values can be queried with the `limits` statement. - -These limits are meant to be effectively non-existent; the limits are so large -(at least on 64-bit machines) that there should not be any point at which they -become a problem. In fact, memory should be exhausted before these limits should -be hit. - -ENVIRONMENT VARIABLES ---------------------- - -bc(1) recognizes the following environment variables: - - * `POSIXLY_CORRECT`: - If this variable exists (no matter the contents), bc(1) behaves as if - the `-s` option was given. - - * `BC_ENV_ARGS`: - This is another way to give command-line arguments to bc(1). They should be - in the same format as all other command-line arguments. These are always - processed first, so any files given in `BC_ENV_ARGS` will be processed - before arguments and files given on the command-line. This gives the user - the ability to set up "standard" options and files to be used at every - invocation. The most useful thing for such files to contain would be useful - functions that the user might want every time bc(1) runs. - - The code that parses `BC_ENV_ARGS` will correctly handle quoted arguments, - but it does not understand escape sequences. For example, the string - `"/home/gavin/some bc file.bc"` will be correctly parsed, but the string - `"/home/gavin/some \"bc\" file.bc"` will include the backslashes. - - The quote parsing will handle either kind of quotes, `'` or `"`. Thus, if - you have a file with any number of single quotes in the name, you can use - double quotes as the outside quotes, as in `"some 'bc' file.bc"`, and vice - versa if you have a file with double quotes. However, handling a file with - both kinds of quotes in `BC_ENV_ARGS` is not supported due to the complexity - of the parsing, though such files are still supported on the command-line - where the parsing is done by the shell. - - * `BC_LINE_LENGTH`: - If this environment variable exists and contains an integer that is greater - than `1` and is less than `UINT16_MAX` (`2^16-1`), bc(1) will output lines - to that length, including the backslash (`\`). The default line length is - `70`. - - * `BC_EXPR_EXIT`: - If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the `-e` and/or - `-f` command-line options (and any equivalents). - -EXIT STATUS ------------ - -bc(1) returns the following exit statuses: - - * `0`: - No error. - - * `1`: - A math error occurred. This follows standard practice of using `1` for - expected errors, since math errors will happen in the process of normal - execution. - - Math errors include divide by `0`, taking the square root of a negative - number, using a negative number as a bound for the pseudo-random number - generator, attempting to convert a negative number to a hardware integer, - overflow when converting a number to a hardware integer, and attempting to - use a non-integer where an integer is required. - - Converting to a hardware integer happens for the second operand of the power - (`^`), places (`@`), left shift (`<<`), and right shift (`>>`) operators and - their corresponding assignment operators. - - * `2`: - A parse error occurred. - - Parse errors include unexpected `EOF`, using an invalid character, failing - to find the end of a string or comment, using a token where it is invalid, - giving an invalid expression, giving an invalid print statement, giving an - invalid function definition, attempting to assign to an expression that is - not a [named expression](#bc-named-expressions), giving an invalid `auto` - list, having a duplicate `auto`/function parameter, failing to find the end - of a code block, attempting to return a value from a `void` function, - attempting to use a variable as a reference, and using any extensions when - the option `-s` or any equivalents were given. - - * `3`: - A runtime error occurred. - - Runtime errors include assigning an invalid number to `ibase`, `obase`, or - `scale`; give a bad expression to a `read()` call, calling `read()` inside - of a `read()` call, type errors, passing the wrong number of parameters to - functions, attempting to call an undefined function, and attempting to use a - `void` function call as a value in an expression. - - * `4`: - A fatal error occurred. - - Fatal errors include memory allocation errors, I/O errors, failing to open - files, attempting to use files that do not have only ASCII characters (bc(1) - only accepts ASCII characters), attempting to open a directory as a file, - and giving invalid command-line options. - -The exit status `4` is special; when a fatal error occurs, bc(1) always exits -and returns `4`, no matter what mode bc(1) is in. - -The other statuses will only be returned when bc(1) is not in interactive mode -(see the INTERACTIVE MODE section), since bc(1) resets its state (see the RESET -section) and accepts more input when one of those errors occurs in interactive -mode. This is also the case when interactive mode is forced by the `-i` flag or -`--interactive` option. - -These exit statuses allow bc(1) to be used in shell scripting with error -checking, and its normal behavior can be forced by using the `-i` flag or -`--interactive` option. - -INTERACTIVE MODE ----------------- - -Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. -Interactive mode is turned on automatically when both `stdin` and `stdout` are -hooked to a terminal, but the `-i` flag and `--interactive` option can turn it -on in other cases. - -In interactive mode, bc(1) attempts to recover from errors (see the RESET -section), and in normal execution, flushes `stdout` as soon as execution is done -for the current input. - -TTY MODE --------- - -If `stdin`, `stdout`, and `stderr` are all connected to a TTY, bc(1) turns on -"TTY mode." - -TTY mode is required for history to be enabled (see the COMMAND LINE HISTORY -section). It is also required to enable special handling for `SIGINT` signals. - -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. - -SIGNAL HANDLING ---------------- - -Sending a `SIGINT` will cause bc(1) to stop execution of the current input. If -bc(1) is in TTY mode (see the TTY MODE section), it will reset (see the RESET -section). Otherwise, it will clean up and exit. - -Note that "current input" can mean one of two things. If bc(1) is processing -input from `stdin` in TTY mode, it will ask for more input. If bc(1) is -processing input from a file in TTY mode, it will stop processing the file and -start processing the next file, if one exists, or ask for input from `stdin` if -no other file exists. - -This means that if a `SIGINT` is sent to bc(1) as it is executing a file, it can -seem as though bc(1) did not respond to the signal since it will immediately -start executing the next file. This is by design; most files that users execute -when interacting with bc(1) have function definitions, which are quick to parse. -If a file takes a long time to execute, there may be a bug in that file. The -rest of the files could still be executed without problem, allowing the user to -continue. - -`SIGTERM` and `SIGQUIT` cause bc(1) to clean up and exit, and it uses the -default handler for all other signals. The one exception is `SIGHUP`, if bc(1) -was built with history support; in that case, when bc(1) is in TTY mode, a -`SIGHUP` will cause bc(1) to clean up and exit. - -COMMAND LINE HISTORY --------------------- - -bc(1) supports interactive command-line editing, if compiled with the history -option enabled. If bc(1) is in TTY mode (see the TTY MODE section), history is -enabled. Previous lines can be recalled and edited with the arrow keys. - -**Note**: when bc(1) is built with history support, tabs are converted to 8 -spaces. - -LOCALES -------- - -This bc(1) ships with support for adding error messages for different locales. - -SEE ALSO --------- - -dc(1) - -STANDARDS ---------- - -bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] -specification. The flags `-efghiqsvVw`, all long options, and the extensions -noted above are extensions to that specification. - -Note that the specification explicitly says that bc(1) only accepts numbers that -use a period (`.`) as a radix point, regardless of the value of `LC_NUMERIC`. - -This bc(1) ships with support for adding error messages for different locales, -so it supports `LC_MESSAGES`. - -AUTHOR ------- - -This bc(1) was made from scratch by Gavin D. Howard. - -BUGS ----- - -None are known. Report bugs at https://git.yzena.com/gavin/bc. - -[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]: #transcendental-functions -[6]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT -[7]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc.md b/manuals/bc.md deleted file mode 120000 index 7b8af482cc80..000000000000 --- a/manuals/bc.md +++ /dev/null @@ -1 +0,0 @@ -bc.1.ronn \ No newline at end of file diff --git a/manuals/bc/A.1 b/manuals/bc/A.1 new file mode 100644 index 000000000000..6421238febb6 --- /dev/null +++ b/manuals/bc/A.1 @@ -0,0 +1,2099 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +It also has many extensions and extra features beyond other +implementations. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/A.1.md b/manuals/bc/A.1.md new file mode 100644 index 000000000000..31b491a3bc70 --- /dev/null +++ b/manuals/bc/A.1.md @@ -0,0 +1,1697 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). It also has many extensions and extra features beyond +other implementations. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/E.1 b/manuals/bc/E.1 new file mode 100644 index 000000000000..70afc2b716f4 --- /dev/null +++ b/manuals/bc/E.1 @@ -0,0 +1,1341 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/E.1.md b/manuals/bc/E.1.md new file mode 100644 index 000000000000..4b5b95ab4d27 --- /dev/null +++ b/manuals/bc/E.1.md @@ -0,0 +1,1091 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/EH.1 b/manuals/bc/EH.1 new file mode 100644 index 000000000000..90708661143a --- /dev/null +++ b/manuals/bc/EH.1 @@ -0,0 +1,1323 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/EH.1.md b/manuals/bc/EH.1.md new file mode 100644 index 000000000000..60efac2dd904 --- /dev/null +++ b/manuals/bc/EH.1.md @@ -0,0 +1,1075 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/EHN.1 b/manuals/bc/EHN.1 new file mode 100644 index 000000000000..203cc531e8b7 --- /dev/null +++ b/manuals/bc/EHN.1 @@ -0,0 +1,1316 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/EHN.1.md b/manuals/bc/EHN.1.md new file mode 100644 index 000000000000..6264e7bf5c81 --- /dev/null +++ b/manuals/bc/EHN.1.md @@ -0,0 +1,1067 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/EHNP.1 b/manuals/bc/EHNP.1 new file mode 100644 index 000000000000..da6a25888ce0 --- /dev/null +++ b/manuals/bc/EHNP.1 @@ -0,0 +1,1309 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/EHNP.1.md b/manuals/bc/EHNP.1.md new file mode 100644 index 000000000000..917b7bc6665c --- /dev/null +++ b/manuals/bc/EHNP.1.md @@ -0,0 +1,1061 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/EHP.1 b/manuals/bc/EHP.1 new file mode 100644 index 000000000000..3352c2ee5610 --- /dev/null +++ b/manuals/bc/EHP.1 @@ -0,0 +1,1316 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/EHP.1.md b/manuals/bc/EHP.1.md new file mode 100644 index 000000000000..30e411236e46 --- /dev/null +++ b/manuals/bc/EHP.1.md @@ -0,0 +1,1069 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/EN.1 b/manuals/bc/EN.1 new file mode 100644 index 000000000000..a662d40fdda9 --- /dev/null +++ b/manuals/bc/EN.1 @@ -0,0 +1,1334 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/EN.1.md b/manuals/bc/EN.1.md new file mode 100644 index 000000000000..cefe8630da75 --- /dev/null +++ b/manuals/bc/EN.1.md @@ -0,0 +1,1083 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/ENP.1 b/manuals/bc/ENP.1 new file mode 100644 index 000000000000..b98a2a2ce2fe --- /dev/null +++ b/manuals/bc/ENP.1 @@ -0,0 +1,1327 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/ENP.1.md b/manuals/bc/ENP.1.md new file mode 100644 index 000000000000..6d7194f31cf6 --- /dev/null +++ b/manuals/bc/ENP.1.md @@ -0,0 +1,1077 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/EP.1 b/manuals/bc/EP.1 new file mode 100644 index 000000000000..9c841d8bab4b --- /dev/null +++ b/manuals/bc/EP.1 @@ -0,0 +1,1334 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.PP +\f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +.IP +.nf +\f[C] +Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. + +This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed +onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function +returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those +globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. +Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed +**x**\ in\ base\ **b**\ could\ be\ written\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ } + +instead\ of\ like\ this: + +\ \ \ \ define\ void\ output(x,\ b)\ { +\ \ \ \ \ \ \ \ auto\ c +\ \ \ \ \ \ \ \ c=obase +\ \ \ \ \ \ \ \ obase=b +\ \ \ \ \ \ \ \ x +\ \ \ \ \ \ \ \ obase=c +\ \ \ \ } + +This\ makes\ writing\ functions\ much\ easier. + +However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, +**obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot +work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a +solution. + +First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number +converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell +aliases.\ Examples: + +\ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +\ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" + +Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or +**scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to +three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those +functions\ could\ return\ the\ desired\ value\ for\ a\ global. + +If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users +could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the +**ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). + +If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. + +This\ is\ a\ **non\-portable\ extension**. +\f[] +.fi +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library before running any code, including any +expressions or files specified on the command line. +.RS +.PP +To learn what is in the library, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Number 6 is a \f[B]non\-portable extension\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below are available when the \f[B]\-l\f[] or +\f[B]\-\-mathlib\f[] command\-line flags are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator and the corresponding assignment operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/EP.1.md b/manuals/bc/EP.1.md new file mode 100644 index 000000000000..090b07f0a2d0 --- /dev/null +++ b/manuals/bc/EP.1.md @@ -0,0 +1,1085 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + + Turns the globals **ibase**, **obase**, and **scale** into stacks. + + This has the effect that a copy of the current value of all three are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + However, since using this flag means that functions cannot set **ibase**, + **obase**, or **scale** globally, functions that are made to do so cannot + work anymore. There are two possible use cases for that, and each has a + solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, or + **scale** globally for any other purpose, it could be split into one to + three functions (based on how many globals it sets) and each of those + functions could return the desired value for a global. + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library before running any code, including any expressions or files + specified on the command line. + + To learn what is in the library, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **2**. Values are output in the specified +base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **last** or a single dot (**.**) + +Number 6 is a **non-portable extension**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**=** **+=** **-=** **\*=** **/=** **%=** **\^=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below are available when the **-l** or **--mathlib** +command-line flags are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator and the corresponding assignment operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/H.1 b/manuals/bc/H.1 new file mode 100644 index 000000000000..17a913896886 --- /dev/null +++ b/manuals/bc/H.1 @@ -0,0 +1,2079 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/H.1.md b/manuals/bc/H.1.md new file mode 100644 index 000000000000..089953f9706a --- /dev/null +++ b/manuals/bc/H.1.md @@ -0,0 +1,1680 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/HN.1 b/manuals/bc/HN.1 new file mode 100644 index 000000000000..f275ceaffb9b --- /dev/null +++ b/manuals/bc/HN.1 @@ -0,0 +1,2072 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/HN.1.md b/manuals/bc/HN.1.md new file mode 100644 index 000000000000..2e1935a12539 --- /dev/null +++ b/manuals/bc/HN.1.md @@ -0,0 +1,1672 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/HNP.1 b/manuals/bc/HNP.1 new file mode 100644 index 000000000000..e3583a545c74 --- /dev/null +++ b/manuals/bc/HNP.1 @@ -0,0 +1,2065 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/HNP.1.md b/manuals/bc/HNP.1.md new file mode 100644 index 000000000000..7501316421d6 --- /dev/null +++ b/manuals/bc/HNP.1.md @@ -0,0 +1,1666 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/HP.1 b/manuals/bc/HP.1 new file mode 100644 index 000000000000..9c7d0abab262 --- /dev/null +++ b/manuals/bc/HP.1 @@ -0,0 +1,2072 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/HP.1.md b/manuals/bc/HP.1.md new file mode 100644 index 000000000000..cafab919d324 --- /dev/null +++ b/manuals/bc/HP.1.md @@ -0,0 +1,1674 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/N.1 b/manuals/bc/N.1 new file mode 100644 index 000000000000..83049e7c7b14 --- /dev/null +++ b/manuals/bc/N.1 @@ -0,0 +1,2092 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +It also has many extensions and extra features beyond other +implementations. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/N.1.md b/manuals/bc/N.1.md new file mode 100644 index 000000000000..49aaf0fbbcfd --- /dev/null +++ b/manuals/bc/N.1.md @@ -0,0 +1,1689 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). It also has many extensions and extra features beyond +other implementations. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in bc(1). Most of those users + would want to put this option in **BC_ENV_ARGS** (see the + **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/NP.1 b/manuals/bc/NP.1 new file mode 100644 index 000000000000..a50dfe2dcc17 --- /dev/null +++ b/manuals/bc/NP.1 @@ -0,0 +1,2085 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +It also has many extensions and extra features beyond other +implementations. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/NP.1.md b/manuals/bc/NP.1.md new file mode 100644 index 000000000000..a5aa258659d2 --- /dev/null +++ b/manuals/bc/NP.1.md @@ -0,0 +1,1683 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). It also has many extensions and extra features beyond +other implementations. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/bc/P.1 b/manuals/bc/P.1 new file mode 100644 index 000000000000..4f6b4ece227c --- /dev/null +++ b/manuals/bc/P.1 @@ -0,0 +1,2092 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH NAME +.PP +bc \- arbitrary\-precision arithmetic language and calculator +.SH SYNOPSIS +.PP +\f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] +[\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] +[\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +bc(1) is an interactive processor for a language first standardized in +1991 by POSIX. +(The current standard is +here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) +The language provides unlimited precision decimal arithmetic and is +somewhat C\-like, but there are differences. +Such differences will be noted in this document. +.PP +After parsing and handling options, this bc(1) reads any files given on +the command line and executes them before reading from \f[B]stdin\f[]. +.PP +This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including +(and especially) the GNU bc(1). +It also has many extensions and extra features beyond other +implementations. +.SH OPTIONS +.PP +The following are the options that bc(1) accepts. +.TP +.B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] +Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and +\f[B]seed\f[] into stacks. +.RS +.PP +This has the effect that a copy of the current value of all four are +pushed onto a stack for every function call, as well as popped when +every function returns. +This means that functions can assign to any and all of those globals +without worrying that the change will affect other functions. +Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply +printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ obase=b +\ \ \ \ x +} +\f[] +.fi +.PP +instead of like this: +.IP +.nf +\f[C] +define\ void\ output(x,\ b)\ { +\ \ \ \ auto\ c +\ \ \ \ c=obase +\ \ \ \ obase=b +\ \ \ \ x +\ \ \ \ obase=c +} +\f[] +.fi +.PP +This makes writing functions much easier. +.PP +(\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended +math library. +See the \f[B]LIBRARY\f[] section.) +.PP +However, since using this flag means that functions cannot set +\f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] +globally, functions that are made to do so cannot work anymore. +There are two possible use cases for that, and each has a solution. +.PP +First, if a function is called on startup to turn bc(1) into a number +converter, it is possible to replace that capability with various shell +aliases. +Examples: +.IP +.nf +\f[C] +alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" +alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" +\f[] +.fi +.PP +Second, if the purpose of a function is to set \f[B]ibase\f[], +\f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other +purpose, it could be split into one to four functions (based on how many +globals it sets) and each of those functions could return the desired +value for a global. +.PP +For functions that set \f[B]seed\f[], the value assigned to +\f[B]seed\f[] is not propagated to parent functions. +This means that the sequence of pseudo\-random numbers that they see +will not be the same sequence of pseudo\-random numbers that any parent +sees. +This is only the case once \f[B]seed\f[] has been set. +.PP +If a function desires to not affect the sequence of pseudo\-random +numbers of its parents, but wants to use the same \f[B]seed\f[], it can +use the following line: +.IP +.nf +\f[C] +seed\ =\ seed +\f[] +.fi +.PP +If the behavior of this option is desired for every run of bc(1), then +users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this +option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more +details). +.PP +If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option +is ignored. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] +Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and +loads the included math library and the extended math library before +running any code, including any expressions or files specified on the +command line. +.RS +.PP +To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-q\f[], \f[B]\-\-quiet\f[] +Do not print copyright header. +bc(1) will also suppress the header in non\-interactive mode. +.RS +.PP +This is mostly for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-s\f[], \f[B]\-\-standard\f[] +Process exactly the language defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +and error if any extensions are used. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-w\f[], \f[B]\-\-warn\f[] +Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], 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[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other bc(1) implementations, this option causes the program to +execute the expressions and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other bc(1) implementations, this option causes the program to +execute the files and then exit. +This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc +>&\-\f[], it will quit with an error. +This is done so that bc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc +2>&\-\f[], it will quit with an error. +This is done so that bc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other bc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +The syntax for bc(1) programs is mostly C\-like, with some differences. +This bc(1) follows the POSIX +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +which is a much more thorough resource for the language this bc(1) +accepts. +This section is meant to be a summary and a listing of all the +extensions to the standard. +.PP +In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means +statement, and \f[B]I\f[] means identifier. +.PP +Identifiers (\f[B]I\f[]) start with a lowercase letter and can be +followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase +letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores +(\f[B]_\f[]). +The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. +Identifiers with more than one character (letter) are a +\f[B]non\-portable extension\f[]. +.PP +\f[B]ibase\f[] is a global variable determining how to interpret +constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] +(\f[B]\-\-warn\f[]) flags were not given on the command line, the max +allowable value for \f[B]ibase\f[] is \f[B]36\f[]. +Otherwise, it is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in bc(1) +programs with the \f[B]maxibase()\f[] built\-in function. +.PP +\f[B]obase\f[] is a global variable determining how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in +function. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a global variable that sets the precision of any operations, with +exceptions. +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and +can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in +function. +.PP +bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. +All \f[I]local\f[] variables are local to the function; they are +parameters or are introduced in the \f[B]auto\f[] list of a function +(see the \f[B]FUNCTIONS\f[] section). +If a variable is accessed which is not a parameter or in the +\f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. +If a parent function has a \f[I]local\f[] variable version of a variable +that a child function considers \f[I]global\f[], the value of that +\f[I]global\f[] variable in the child function is the value of the +variable in the parent function, not the value of the actual +\f[I]global\f[] variable. +.PP +All of the above applies to arrays as well. +.PP +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence +operator is an assignment operator \f[I]and\f[] the expression is +notsurrounded by parentheses. +.PP +The value that is printed is also assigned to the special variable +\f[B]last\f[]. +A single dot (\f[B].\f[]) may also be used as a synonym for +\f[B]last\f[]. +These are \f[B]non\-portable extensions\f[]. +.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[] and \f[B]*/\f[]. +.IP "2." 3 +Line comments go from \f[B]#\f[] until, and not including, the next +newline. +This is a \f[B]non\-portable extension\f[]. +.SS Named Expressions +.PP +The following are named expressions in bc(1): +.IP "1." 3 +Variables: \f[B]I\f[] +.IP "2." 3 +Array Elements: \f[B]I[E]\f[] +.IP "3." 3 +\f[B]ibase\f[] +.IP "4." 3 +\f[B]obase\f[] +.IP "5." 3 +\f[B]scale\f[] +.IP "6." 3 +\f[B]seed\f[] +.IP "7." 3 +\f[B]last\f[] or a single dot (\f[B].\f[]) +.PP +Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. +.PP +The meaning of \f[B]seed\f[] 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[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] +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[] value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if \f[B]seed\f[] is queried again immediately. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will +\f[I]not\f[] produce unique sequences of pseudo\-random numbers. +The value of \f[B]seed\f[] will change after any use of the +\f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the +\f[I]Operands\f[] subsection below), except if the parameter passed to +\f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +Variables and arrays do not interfere; users can have arrays named the +same as variables. +This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so +a user can have a variable, array, and function that all have the same +name, and they will not shadow each other, whether inside of functions +or not. +.PP +Named expressions are required as the operand of +\f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of +\f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). +.SS Operands +.PP +The following are valid operands in bc(1): +.IP " 1." 4 +Numbers (see the \f[I]Numbers\f[] subsection below). +.IP " 2." 4 +Array indices (\f[B]I[E]\f[]). +.IP " 3." 4 +\f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). +.IP " 4." 4 +\f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. +\f[B]E\f[] must be non\-negative. +.IP " 5." 4 +\f[B]length(E)\f[]: The number of significant decimal digits in +\f[B]E\f[]. +.IP " 6." 4 +\f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 7." 4 +\f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. +.IP " 8." 4 +\f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP " 9." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.IP "10." 4 +\f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an +expression. +The result of that expression is the result of the \f[B]read()\f[] +operand. +This is a \f[B]non\-portable extension\f[]. +.IP "11." 4 +\f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "12." 4 +\f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "13." 4 +\f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "14." 4 +\f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) +and \f[B]BC_RAND_MAX\f[] (inclusive). +Using this operand will change the value of \f[B]seed\f[]. +This is a \f[B]non\-portable extension\f[]. +.IP "15." 4 +\f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] +(inclusive) and the value of \f[B]E\f[] (exclusive). +If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s +\f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets +(see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. +If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this operand is +unbounded. +Using this operand will change the value of \f[B]seed\f[], unless the +value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] +changed. +This is a \f[B]non\-portable extension\f[]. +.IP "16." 4 +\f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. +This is a \f[B]non\-portable extension\f[]. +.PP +The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are +guaranteed to be as unbiased as possible, subject to the limitations of +the pseudo\-random number generator. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to +\f[I]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[I]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.SS Numbers +.PP +Numbers are strings made up of digits, uppercase letters, and at most +\f[B]1\f[] period for a radix. +Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]Z\f[] alone always equals decimal \f[B]35\f[]. +.PP +In addition, bc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +Using scientific notation is an error or warning if the \f[B]\-s\f[] or +\f[B]\-w\f[], respectively, command\-line options (or equivalents) are +given. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if bc(1) is given the number string +\f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.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 +.B \f[B]++\f[] \f[B]\-\-\f[] +Type: Prefix and Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]increment\f[], \f[B]decrement\f[] +.RE +.TP +.B \f[B]\-\f[] \f[B]!\f[] +Type: Prefix +.RS +.PP +Associativity: None +.PP +Description: \f[B]negation\f[], \f[B]boolean not\f[] +.RE +.TP +.B \f[B]$\f[] +Type: Postfix +.RS +.PP +Associativity: None +.PP +Description: \f[B]truncation\f[] +.RE +.TP +.B \f[B]\@\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]set precision\f[] +.RE +.TP +.B \f[B]^\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]power\f[] +.RE +.TP +.B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] +.RE +.TP +.B \f[B]+\f[] \f[B]\-\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]add\f[], \f[B]subtract\f[] +.RE +.TP +.B \f[B]<<\f[] \f[B]>>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]shift left\f[], \f[B]shift right\f[] +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +Type: Binary +.RS +.PP +Associativity: Right +.PP +Description: \f[B]assignment\f[] +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]relational\f[] +.RE +.TP +.B \f[B]&&\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean and\f[] +.RE +.TP +.B \f[B]||\f[] +Type: Binary +.RS +.PP +Associativity: Left +.PP +Description: \f[B]boolean or\f[] +.RE +.PP +The operators will be described in more detail below. +.TP +.B \f[B]++\f[] \f[B]\-\-\f[] +The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] +operators behave exactly like they would in C. +They require a named expression (see the \f[I]Named Expressions\f[] +subsection) as an operand. +.RS +.PP +The prefix versions of these operators are more efficient; use them +where possible. +.RE +.TP +.B \f[B]\-\f[] +The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to +negate any expression with the value \f[B]0\f[]. +Otherwise, a copy of the expression with its sign flipped is returned. +.RS +.RE +.TP +.B \f[B]!\f[] +The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression +is \f[B]0\f[], or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +The \f[B]truncation\f[] operator returns a copy of the given expression +with all of its \f[I]scale\f[] removed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\@\f[] +The \f[B]set precision\f[] operator takes two expressions and returns a +copy of the first with its \f[I]scale\f[] equal to the value of the +second expression. +That could either mean that the number is returned without change (if +the \f[I]scale\f[] of the first expression matches the value of the +second expression), extended (if it is less), or truncated (if it is +more). +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as +it would be in C) takes two expressions and raises the first to the +power of the value of the second. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]), and if it +is negative, the first value must be non\-zero. +.RE +.TP +.B \f[B]*\f[] +The \f[B]multiply\f[] operator takes two expressions, multiplies them, +and returns the product. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The \f[B]divide\f[] operator takes two expressions, divides them, and +returns the quotient. +The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[] and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.RS +.PP +The second expression must be non\-zero. +.RE +.TP +.B \f[B]+\f[] +The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max +of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]\-\f[] +The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to +the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. +.RS +.RE +.TP +.B \f[B]<<\f[] +The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the right. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]>>\f[] +The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and +\f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its +decimal point moved \f[B]b\f[] places to the left. +.RS +.PP +The second expression must be an integer (no \f[I]scale\f[]) and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] +The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and +\f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named +Expressions\f[] subsection). +.RS +.PP +For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to +\f[B]a\f[]. +For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the +corresponding arithmetic operator and the result is assigned to +\f[B]a\f[]. +.PP +The \f[B]assignment\f[] operators that correspond to operators that are +extensions are themselves \f[B]non\-portable extensions\f[]. +.RE +.TP +.B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] +The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] +and \f[B]b\f[], and if the relation holds, according to C language +semantics, the result is \f[B]1\f[]. +Otherwise, it is \f[B]0\f[]. +.RS +.PP +Note that unlike in C, these operators have a lower precedence than the +\f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is +interpreted as \f[B](a=b)>c\f[]. +.PP +Also, unlike the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +requires, these operators can appear anywhere any other expressions can +be used. +This allowance is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]&&\f[] +The \f[B]boolean and\f[] operator takes two expressions and returns +\f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]||\f[] +The \f[B]boolean or\f[] operator takes two expressions and returns +\f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. +.RS +.PP +This is \f[I]not\f[] a short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Statements +.PP +The following items are statements: +.IP " 1." 4 +\f[B]E\f[] +.IP " 2." 4 +\f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... +\f[B];\f[] \f[B]S\f[] \f[B]}\f[] +.IP " 3." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 4." 4 +\f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] +\f[B]S\f[] +.IP " 5." 4 +\f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 6." 4 +\f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] +\f[B]E\f[] \f[B])\f[] \f[B]S\f[] +.IP " 7." 4 +An empty statement +.IP " 8." 4 +\f[B]break\f[] +.IP " 9." 4 +\f[B]continue\f[] +.IP "10." 4 +\f[B]quit\f[] +.IP "11." 4 +\f[B]halt\f[] +.IP "12." 4 +\f[B]limits\f[] +.IP "13." 4 +A string of characters, enclosed in double quotes +.IP "14." 4 +\f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... +\f[B],\f[] \f[B]E\f[] +.IP "15." 4 +\f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where +\f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the +\f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). +The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], +which will automatically be turned into array references (see the +\f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) +if the corresponding parameter in the function definition is an array +reference. +.PP +Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. +.PP +Also, as a \f[B]non\-portable extension\f[], 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[]. +.PP +The \f[B]break\f[] statement causes a loop to stop iterating and resume +execution immediately following a loop. +This is only allowed in loops. +.PP +The \f[B]continue\f[] statement causes a loop iteration to stop early +and returns to the start of the loop, including testing the loop +condition. +This is only allowed in loops. +.PP +The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. +.PP +The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a +branch that will not be executed (it is a compile\-time command). +.PP +The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. +(Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement +that is not executed, bc(1) does not quit.) +.PP +The \f[B]limits\f[] statement prints the limits that this bc(1) is +subject to. +This is like the \f[B]quit\f[] statement in that it is a compile\-time +command. +.PP +An expression by itself is evaluated and printed, followed by a newline. +.PP +Both scientific notation and engineering notation are available for +printing the results of expressions. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[], and engineering notation is activated by assigning +\f[B]1\f[] to \f[B]obase\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Scientific notation and engineering notation are disabled if bc(1) is +run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options +(or equivalents). +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.SS Print Statement +.PP +The "expressions" in a \f[B]print\f[] statement may also be strings. +If they are, there are backslash escape sequences that are interpreted +specially. +What those sequences are, and what they cause to be printed, are shown +below: +.PP +.TS +tab(@); +l l. +T{ +\f[B]\\a\f[] +T}@T{ +\f[B]\\a\f[] +T} +T{ +\f[B]\\b\f[] +T}@T{ +\f[B]\\b\f[] +T} +T{ +\f[B]\\\\\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\e\f[] +T}@T{ +\f[B]\\\f[] +T} +T{ +\f[B]\\f\f[] +T}@T{ +\f[B]\\f\f[] +T} +T{ +\f[B]\\n\f[] +T}@T{ +\f[B]\\n\f[] +T} +T{ +\f[B]\\q\f[] +T}@T{ +\f[B]"\f[] +T} +T{ +\f[B]\\r\f[] +T}@T{ +\f[B]\\r\f[] +T} +T{ +\f[B]\\t\f[] +T}@T{ +\f[B]\\t\f[] +T} +.TE +.PP +Any other character following a backslash causes the backslash and +character to be printed as\-is. +.PP +Any non\-string expression in a print statement shall be assigned to +\f[B]last\f[], like any other expression that is printed. +.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[] is equal to +\f[B]0\f[], in the expression +.IP +.nf +\f[C] +a[i++]\ =\ i++ +\f[] +.fi +.PP +the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and +\f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. +.PP +This includes function arguments. +Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the +expression +.IP +.nf +\f[C] +x(i++,\ i++) +\f[] +.fi +.PP +the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second +argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before +the function starts executing. +.SH FUNCTIONS +.PP +Function definitions are as follows: +.IP +.nf +\f[C] +define\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return(E) +} +\f[] +.fi +.PP +Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be +replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an +array, and any \f[B]I\f[] in the parameter list may be replaced with +\f[B]*I[]\f[] to make a parameter an array reference. +Callers of functions that take array references should not put an +asterisk in the call; they must be called with just \f[B]I[]\f[] like +normal array parameters and will be automatically converted into +references. +.PP +As a \f[B]non\-portable extension\f[], the opening brace of a +\f[B]define\f[] statement may appear on the next line. +.PP +As a \f[B]non\-portable extension\f[], the return statement may also be +in one of the following forms: +.IP "1." 3 +\f[B]return\f[] +.IP "2." 3 +\f[B]return\f[] \f[B](\f[] \f[B])\f[] +.IP "3." 3 +\f[B]return\f[] \f[B]E\f[] +.PP +The first two, or not specifying a \f[B]return\f[] statement, is +equivalent to \f[B]return (0)\f[], unless the function is a +\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection +below). +.SS Void Functions +.PP +Functions can also be \f[B]void\f[] functions, defined as follows: +.IP +.nf +\f[C] +define\ void\ I(I,...,I){ +\ \ \ \ auto\ I,...,I +\ \ \ \ S;...;S +\ \ \ \ return +} +\f[] +.fi +.PP +They can only be used as standalone expressions, where such an +expression would be printed alone, except in a print statement. +.PP +Void functions can only use the first two \f[B]return\f[] statements +listed above. +They can also omit the return statement entirely. +.PP +The word "void" is not treated as a keyword; it is still possible to +have variables, arrays, and functions named \f[B]void\f[]. +The word "void" is only treated specially right after the +\f[B]define\f[] keyword. +.PP +This is a \f[B]non\-portable extension\f[]. +.SS Array References +.PP +For any array in the parameter list, if the array is declared in the +form +.IP +.nf +\f[C] +*I[] +\f[] +.fi +.PP +it is a \f[B]reference\f[]. +Any changes to the array in the function are reflected, when the +function returns, to the array that was passed in. +.PP +Other than this, all function arguments are passed by value. +.PP +This is a \f[B]non\-portable extension\f[]. +.SH LIBRARY +.PP +All of the functions below, including the functions in the extended math +library (see the \f[I]Extended Library\f[] subsection below), are +available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line +flags are given, except that the extended math library is not available +when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents +are given. +.SS Standard Library +.PP +The +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +defines the following functions for the math library: +.TP +.B \f[B]s(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]c(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l(x)\f[] +Returns the natural logarithm of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]e(x)\f[] +Returns the mathematical constant \f[B]e\f[] raised to the power of +\f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]j(x, n)\f[] +Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.SS Extended Library +.PP +The extended library is \f[I]not\f[] loaded when the +\f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] +options are given since they are not part of the library defined by the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). +.PP +The extended library is a \f[B]non\-portable extension\f[]. +.TP +.B \f[B]p(x, y)\f[] +Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is +not an integer, and returns the result to the current \f[B]scale\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round half away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). +.RS +.RE +.TP +.B \f[B]ceil(x, p)\f[] +Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the +rounding mode round away from +\f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). +.RS +.RE +.TP +.B \f[B]f(x)\f[] +Returns the factorial of the truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]perm(n, k)\f[] +Returns the permutation of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]comb(n, k)\f[] +Returns the combination of the truncated absolute value of \f[B]n\f[] of +the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. +If not, it returns \f[B]0\f[]. +.RS +.RE +.TP +.B \f[B]l2(x)\f[] +Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]l10(x)\f[] +Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]log(x, b)\f[] +Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cbrt(x)\f[] +Returns the cube root of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]root(x, n)\f[] +Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns +the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. +.RS +.PP +If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes +bc(1) to reset (see the \f[B]RESET\f[] section). +It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even +and \f[B]x\f[] is negative. +.RE +.TP +.B \f[B]pi(p)\f[] +Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]t(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]a2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]sin(x)\f[] +Returns the sine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]s(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]cos(x)\f[] +Returns the cosine of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +This is an alias of \f[B]c(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]tan(x)\f[] +Returns the tangent of \f[B]x\f[], which is assumed to be in radians. +.RS +.PP +If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +.PP +This is an alias of \f[B]t(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan(x)\f[] +Returns the arctangent of \f[B]x\f[], in radians. +.RS +.PP +This is an alias of \f[B]a(x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]atan2(y, x)\f[] +Returns the arctangent of \f[B]y/x\f[], in radians. +If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an +error and causes bc(1) to reset (see the \f[B]RESET\f[] section). +Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns +\f[B]a(y/x)\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or +equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. +If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than +\f[B]0\f[], it returns \f[B]pi/2\f[]. +If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than +\f[B]0\f[], it returns \f[B]\-pi/2\f[]. +.RS +.PP +This function is the same as the \f[B]atan2()\f[] function in many +programming languages. +.PP +This is an alias of \f[B]a2(y, x)\f[]. +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]r2d(x)\f[] +Converts \f[B]x\f[] from radians to degrees and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]d2r(x)\f[] +Converts \f[B]x\f[] from degrees to radians and returns the result. +.RS +.PP +This is a transcendental function (see the \f[I]Transcendental +Functions\f[] subsection below). +.RE +.TP +.B \f[B]frand(p)\f[] +Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and +\f[B]1\f[] (exclusive) with the number of decimal digits after the +decimal point equal to the truncated absolute value of \f[B]p\f[]. +If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change +the value of \f[B]seed\f[]. +If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and +\f[B]seed\f[] is \f[I]not\f[] changed. +.RS +.RE +.TP +.B \f[B]ifrand(i, p)\f[] +Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) +and the truncated absolute value of \f[B]i\f[] (exclusive) with the +number of decimal digits after the decimal point equal to the truncated +absolute value of \f[B]p\f[]. +If the absolute value of \f[B]i\f[] is greater than or equal to +\f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function +will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is +returned and \f[B]seed\f[] is not changed. +.RS +.RE +.TP +.B \f[B]srand(x)\f[] +Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. +In other words, it randomizes the sign of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]brand()\f[] +Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). +.RS +.RE +.TP +.B \f[B]ubytes(x)\f[] +Returns the numbers of unsigned integer bytes required to hold the +truncated absolute value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]sbytes(x)\f[] +Returns the numbers of signed, two\[aq]s\-complement integer bytes +required to hold the truncated value of \f[B]x\f[]. +.RS +.RE +.TP +.B \f[B]hex(x)\f[] +Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary(x)\f[] +Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output(x, b)\f[] +Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in as few power of two bytes as possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or is negative, an error message is +printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] +section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in as few power of two bytes as +possible. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, an error message is printed instead, +but bc(1) is not reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uintn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]intn(x, n)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]1\f[] byte, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int8(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int16(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int32(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]uint64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +an unsigned integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer, is negative, or cannot fit into +\f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not +reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]int64(x)\f[] +Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as +a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. +Both outputs are split into bytes separated by spaces. +.RS +.PP +If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an +error message is printed instead, but bc(1) is not reset (see the +\f[B]RESET\f[] section). +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]hex_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]binary_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in binary using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_uint(x, n)\f[] +Outputs the representation of the truncated absolute value of \f[B]x\f[] +as an unsigned integer in the current \f[B]obase\f[] (see the +\f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. +Not all of the value will be output if \f[B]n\f[] is too small. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.TP +.B \f[B]output_byte(x, i)\f[] +Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], +where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes +\- 1\f[] is the most significant byte. +.RS +.PP +This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] +subsection of the \f[B]FUNCTIONS\f[] section). +.RE +.SS Transcendental Functions +.PP +All transcendental functions can return slightly inaccurate results (up +to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). +This is unavoidable, and this +article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains +why it is impossible and unnecessary to calculate exact results for the +transcendental functions. +.PP +Because of the possible inaccuracy, I recommend that users call those +functions with the precision (\f[B]scale\f[]) set to at least 1 higher +than is necessary. +If exact results are \f[I]absolutely\f[] required, users can double the +precision (\f[B]scale\f[]) and then truncate. +.PP +The transcendental functions in the standard math library are: +.IP \[bu] 2 +\f[B]s(x)\f[] +.IP \[bu] 2 +\f[B]c(x)\f[] +.IP \[bu] 2 +\f[B]a(x)\f[] +.IP \[bu] 2 +\f[B]l(x)\f[] +.IP \[bu] 2 +\f[B]e(x)\f[] +.IP \[bu] 2 +\f[B]j(x, n)\f[] +.PP +The transcendental functions in the extended math library are: +.IP \[bu] 2 +\f[B]l2(x)\f[] +.IP \[bu] 2 +\f[B]l10(x)\f[] +.IP \[bu] 2 +\f[B]log(x, b)\f[] +.IP \[bu] 2 +\f[B]pi(p)\f[] +.IP \[bu] 2 +\f[B]t(x)\f[] +.IP \[bu] 2 +\f[B]a2(y, x)\f[] +.IP \[bu] 2 +\f[B]sin(x)\f[] +.IP \[bu] 2 +\f[B]cos(x)\f[] +.IP \[bu] 2 +\f[B]tan(x)\f[] +.IP \[bu] 2 +\f[B]atan(x)\f[] +.IP \[bu] 2 +\f[B]atan2(y, x)\f[] +.IP \[bu] 2 +\f[B]r2d(x)\f[] +.IP \[bu] 2 +\f[B]d2r(x)\f[] +.SH RESET +.PP +When bc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any functions that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all functions returned) is skipped. +.PP +Thus, when bc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] section), it asks for more input; +otherwise, it exits with the appropriate return code. +.PP +Note that this reset behavior is different from the GNU bc(1), which +attempts to start executing the statement right after the one that +caused an error. +.SH PERFORMANCE +.PP +Most bc(1) implementations use \f[B]char\f[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This bc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]BC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]BC_BASE_DIGS\f[]. +.PP +The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can +be queried with the \f[B]limits\f[] statement. +.PP +In addition, this bc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]BC_LONG_BIT\f[], 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 +.B \f[B]BC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +bc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]BC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]BC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]BC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]BC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]BC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]BC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]BC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]BC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]BC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. +Set at \f[B]2^BC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]BC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +The actual values can be queried with the \f[B]limits\f[] statement. +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +bc(1) recognizes the following environment variables: +.TP +.B \f[B]POSIXLY_CORRECT\f[] +If this variable exists (no matter the contents), bc(1) behaves as if +the \f[B]\-s\f[] option was given. +.RS +.RE +.TP +.B \f[B]BC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time bc(1) runs. +.RS +.PP +The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "bc" +file.bc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]BC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including +the backslash (\f[B]\\\f[]). +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]BC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), bc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +bc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and +right shift (\f[B]>>\f[]) operators and their corresponding assignment +operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, using a token +where it is invalid, giving an invalid expression, giving an invalid +print statement, giving an invalid function definition, attempting to +assign to an expression that is not a named expression (see the +\f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), +giving an invalid \f[B]auto\f[] list, having a duplicate +\f[B]auto\f[]/function parameter, failing to find the end of a code +block, attempting to return a value from a \f[B]void\f[] function, +attempting to use a variable as a reference, and using any extensions +when the option \f[B]\-s\f[] or any equivalents were given. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, passing the wrong number of arguments +to functions, attempting to call an undefined function, and attempting +to use a \f[B]void\f[] function call as a value in an expression. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (bc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) +always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. +.PP +The other statuses will only be returned when bc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +bc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Per the +standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), +bc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, bc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, bc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the +current input. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If bc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing +a file, it can seem as though bc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +bc(1) supports interactive command\-line editing. +If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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[]. +.SH SEE ALSO +.PP +dc(1) +.SH STANDARDS +.PP +bc(1) is compliant with the IEEE Std 1003.1\-2017 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions +noted above are extensions to that specification. +.PP +Note that the specification explicitly says that bc(1) only accepts +numbers that use a period (\f[B].\f[]) as a radix point, regardless of +the value of \f[B]LC_NUMERIC\f[]. +.PP +This bc(1) supports error messages for different locales, and thus, it +supports \f[B]LC_MESSAGES\f[]. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHORS +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/bc/P.1.md b/manuals/bc/P.1.md new file mode 100644 index 000000000000..1f7379ebfe41 --- /dev/null +++ b/manuals/bc/P.1.md @@ -0,0 +1,1691 @@ + + +# NAME + +bc - arbitrary-precision arithmetic language and calculator + +# SYNOPSIS + +**bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] +[*file*...] + +# DESCRIPTION + +bc(1) is an interactive processor for a language first standardized in 1991 by +POSIX. (The current standard is [here][1].) The language provides unlimited +precision decimal arithmetic and is somewhat C-like, but there are differences. +Such differences will be noted in this document. + +After parsing and handling options, this bc(1) reads any files given on the +command line and executes them before reading from **stdin**. + +This bc(1) is a drop-in replacement for *any* bc(1), including (and +especially) the GNU bc(1). It also has many extensions and extra features beyond +other implementations. + +# OPTIONS + +The following are the options that bc(1) accepts. + +**-g**, **--global-stacks** + +: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. + + This has the effect that a copy of the current value of all four are pushed + onto a stack for every function call, as well as popped when every function + returns. This means that functions can assign to any and all of those + globals without worrying that the change will affect other functions. + Thus, a hypothetical function named **output(x,b)** that simply printed + **x** in base **b** could be written like this: + + define void output(x, b) { + obase=b + x + } + + instead of like this: + + define void output(x, b) { + auto c + c=obase + obase=b + x + obase=c + } + + This makes writing functions much easier. + + (**Note**: the function **output(x,b)** exists in the extended math library. + See the **LIBRARY** section.) + + However, since using this flag means that functions cannot set **ibase**, + **obase**, **scale**, or **seed** globally, functions that are made to do so + cannot work anymore. There are two possible use cases for that, and each has + a solution. + + First, if a function is called on startup to turn bc(1) into a number + converter, it is possible to replace that capability with various shell + aliases. Examples: + + alias d2o="bc -e ibase=A -e obase=8" + alias h2b="bc -e ibase=G -e obase=2" + + Second, if the purpose of a function is to set **ibase**, **obase**, + **scale**, or **seed** globally for any other purpose, it could be split + into one to four functions (based on how many globals it sets) and each of + those functions could return the desired value for a global. + + For functions that set **seed**, the value assigned to **seed** is not + propagated to parent functions. This means that the sequence of + pseudo-random numbers that they see will not be the same sequence of + pseudo-random numbers that any parent sees. This is only the case once + **seed** has been set. + + If a function desires to not affect the sequence of pseudo-random numbers + of its parents, but wants to use the same **seed**, it can use the following + line: + + seed = seed + + If the behavior of this option is desired for every run of bc(1), then users + could make sure to define **BC_ENV_ARGS** and include this option (see the + **ENVIRONMENT VARIABLES** section for more details). + + If **-s**, **-w**, or any equivalents are used, this option is ignored. + + This is a **non-portable extension**. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-l**, **--mathlib** + +: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included + math library and the extended math library before running any code, + including any expressions or files specified on the command line. + + To learn what is in the libraries, see the **LIBRARY** section. + +**-P**, **--no-prompt** + +: This option is a no-op. + + This is a **non-portable extension**. + +**-q**, **--quiet** + +: Do not print copyright header. bc(1) will also suppress the header in + non-interactive mode. + + This is mostly for compatibility with the [GNU bc(1)][2]. + + This is a **non-portable extension**. + +**-s**, **--standard** + +: Process exactly the language defined by the [standard][1] and error if any + extensions are used. + + This is a **non-portable extension**. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + + This is a **non-portable extension**. + +**-w**, **--warn** + +: Like **-s** and **--standard**, except that warnings (and not errors) are + printed for non-standard extensions and execution continues normally. + + This is a **non-portable extension**. + +**-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. + + In other bc(1) implementations, this option causes the program to execute + the expressions and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other bc(1) implementations, this option causes the program to execute + the files and then exit. This bc(1) does not, unless the + **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **bc >&-**, it will quit with an error. This +is done so that bc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This +is done so that bc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other bc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +The syntax for bc(1) programs is mostly C-like, with some differences. This +bc(1) follows the [POSIX standard][1], which is a much more thorough resource +for the language this bc(1) accepts. This section is meant to be a summary and a +listing of all the extensions to the standard. + +In the sections below, **E** means expression, **S** means statement, and **I** +means identifier. + +Identifiers (**I**) start with a lowercase letter and can be followed by any +number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits +(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. +Identifiers with more than one character (letter) are a +**non-portable extension**. + +**ibase** is a global variable determining how to interpret constant numbers. It +is the "input" base, or the number base used for interpreting input numbers. +**ibase** is initially **10**. If the **-s** (**--standard**) and **-w** +(**--warn**) flags were not given on the command line, the max allowable value +for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for +**ibase** is **2**. The max allowable value for **ibase** can be queried in +bc(1) programs with the **maxibase()** built-in function. + +**obase** is a global variable determining how to output results. It is the +"output" base, or the number base used for outputting numbers. **obase** is +initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and +can be queried in bc(1) programs with the **maxobase()** built-in function. The +min allowable value for **obase** is **0**. If **obase** is **0**, values are +output in scientific notation, and if **obase** is **1**, values are output in +engineering notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a global variable that +sets the precision of any operations, with exceptions. **scale** is initially +**0**. **scale** cannot be negative. The max allowable value for **scale** is +**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** +built-in function. + +bc(1) has both *global* variables and *local* variables. All *local* +variables are local to the function; they are parameters or are introduced in +the **auto** list of a function (see the **FUNCTIONS** section). If a variable +is accessed which is not a parameter or in the **auto** list, it is assumed to +be *global*. If a parent function has a *local* variable version of a variable +that a child function considers *global*, the value of that *global* variable in +the child function is the value of the variable in the parent function, not the +value of the actual *global* variable. + +All of the above applies to arrays as well. + +The value of a statement that is an expression (i.e., any of the named +expressions or operands) is printed unless the lowest precedence operator is an +assignment operator *and* the expression is notsurrounded by parentheses. + +The value that is printed is also assigned to the special variable **last**. A +single dot (**.**) may also be used as a synonym for **last**. These are +**non-portable extensions**. + +Either semicolons or newlines may separate statements. + +## Comments + +There are two kinds of comments: + +1. Block comments are enclosed in **/\*** and **\*/**. +2. Line comments go from **#** until, and not including, the next newline. This + is a **non-portable extension**. + +## Named Expressions + +The following are named expressions in bc(1): + +1. Variables: **I** +2. Array Elements: **I[E]** +3. **ibase** +4. **obase** +5. **scale** +6. **seed** +7. **last** or a single dot (**.**) + +Numbers 6 and 7 are **non-portable extensions**. + +The meaning of **seed** is dependent on the current pseudo-random number +generator but is guaranteed to not change except for new major versions. + +The *scale* and sign of the value may be significant. + +If a previously used **seed** value is assigned to **seed** and used again, the +pseudo-random number generator is guaranteed to produce the same sequence of +pseudo-random numbers as it did when the **seed** value was previously used. + +The exact value assigned to **seed** is not guaranteed to be returned if +**seed** is queried again immediately. However, if **seed** *does* return a +different value, both values, when assigned to **seed**, are guaranteed to +produce the same sequence of pseudo-random numbers. This means that certain +values assigned to **seed** will *not* produce unique sequences of pseudo-random +numbers. The value of **seed** will change after any use of the **rand()** and +**irand(E)** operands (see the *Operands* subsection below), except if the +parameter passed to **irand(E)** is **0**, **1**, or negative. + +There is no limit to the length (number of significant decimal digits) or +*scale* of the value that can be assigned to **seed**. + +Variables and arrays do not interfere; users can have arrays named the same as +variables. This also applies to functions (see the **FUNCTIONS** section), so a +user can have a variable, array, and function that all have the same name, and +they will not shadow each other, whether inside of functions or not. + +Named expressions are required as the operand of **increment**/**decrement** +operators and as the left side of **assignment** operators (see the *Operators* +subsection). + +## Operands + +The following are valid operands in bc(1): + +1. Numbers (see the *Numbers* subsection below). +2. Array indices (**I[E]**). +3. **(E)**: The value of **E** (used to change precedence). +4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. +5. **length(E)**: The number of significant decimal digits in **E**. +6. **length(I[])**: The number of elements in the array **I**. This is a + **non-portable extension**. +7. **scale(E)**: The *scale* of **E**. +8. **abs(E)**: The absolute value of **E**. This is a **non-portable + extension**. +9. **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. +10. **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**. +11. **maxibase()**: The max allowable **ibase**. This is a **non-portable + extension**. +12. **maxobase()**: The max allowable **obase**. This is a **non-portable + extension**. +13. **maxscale()**: The max allowable **scale**. This is a **non-portable + extension**. +14. **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**. +15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the + value of **E** (exclusive). If **E** is negative or is a non-integer + (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see + the **RESET** section) while **seed** remains unchanged. If **E** is larger + than **BC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this operand is unbounded. Using this operand will + change the value of **seed**, unless the value of **E** is **0** or **1**. + In that case, **0** is returned, and **seed** is *not* changed. This is a + **non-portable extension**. +16. **maxrand()**: The max integer returned by **rand()**. This is a + **non-portable extension**. + +The integers generated by **rand()** and **irand(E)** are guaranteed to be as +unbiased as possible, subject to the limitations of the pseudo-random number +generator. + +**Note**: The values returned by the pseudo-random number generator with +**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they *are* guaranteed to be reproducible with identical **seed** values. + +## Numbers + +Numbers are strings made up of digits, uppercase letters, and at most **1** +period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase +letters are equal to **9** + their position in the alphabet (i.e., **A** equals +**10**, or **9+1**). If a digit or letter makes no sense with the current value +of **ibase**, they are set to the value of the highest valid digit in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **Z** alone always equals decimal +**35**. + +In addition, bc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. + +Using scientific notation is an error or warning if the **-s** or **-w**, +respectively, command-line options (or equivalents) are given. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and bc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if bc(1) is given the +number string **10e-4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +## Operators + +The following arithmetic and logical operators can be used. They are listed in +order of decreasing precedence. Operators in the same group have the same +precedence. + +**++** **--** + +: Type: Prefix and Postfix + + Associativity: None + + Description: **increment**, **decrement** + +**-** **!** + +: Type: Prefix + + Associativity: None + + Description: **negation**, **boolean not** + +**\$** + +: Type: Postfix + + Associativity: None + + Description: **truncation** + +**\@** + +: Type: Binary + + Associativity: Right + + Description: **set precision** + +**\^** + +: Type: Binary + + Associativity: Right + + Description: **power** + +**\*** **/** **%** + +: Type: Binary + + Associativity: Left + + Description: **multiply**, **divide**, **modulus** + +**+** **-** + +: Type: Binary + + Associativity: Left + + Description: **add**, **subtract** + +**\<\<** **\>\>** + +: Type: Binary + + Associativity: Left + + Description: **shift left**, **shift right** + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: Type: Binary + + Associativity: Right + + Description: **assignment** + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: Type: Binary + + Associativity: Left + + Description: **relational** + +**&&** + +: Type: Binary + + Associativity: Left + + Description: **boolean and** + +**||** + +: Type: Binary + + Associativity: Left + + Description: **boolean or** + +The operators will be described in more detail below. + +**++** **--** + +: The prefix and postfix **increment** and **decrement** operators behave + exactly like they would in C. They require a named expression (see the + *Named Expressions* subsection) as an operand. + + The prefix versions of these operators are more efficient; use them where + possible. + +**-** + +: The **negation** operator returns **0** if a user attempts to negate any + expression with the value **0**. Otherwise, a copy of the expression with + its sign flipped is returned. + +**!** + +: The **boolean not** operator returns **1** if the expression is **0**, or + **0** otherwise. + + This is a **non-portable extension**. + +**\$** + +: The **truncation** operator returns a copy of the given expression with all + of its *scale* removed. + + This is a **non-portable extension**. + +**\@** + +: The **set precision** operator takes two expressions and returns a copy of + the first with its *scale* equal to the value of the second expression. That + could either mean that the number is returned without change (if the + *scale* of the first expression matches the value of the second + expression), extended (if it is less), or truncated (if it is more). + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\^** + +: The **power** operator (not the **exclusive or** operator, as it would be in + C) takes two expressions and raises the first to the power of the value of + the second. + + The second expression must be an integer (no *scale*), and if it is + negative, the first value must be non-zero. + +**\*** + +: The **multiply** operator takes two expressions, multiplies them, and + returns the product. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result is + equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The **divide** operator takes two expressions, divides them, and returns the + quotient. The *scale* of the result shall be the value of **scale**. + + The second expression must be non-zero. + +**%** + +: The **modulus** operator takes two expressions, **a** and **b**, and + evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the + result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The second expression must be non-zero. + +**+** + +: The **add** operator takes two expressions, **a** and **b**, and returns the + sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. + +**-** + +: The **subtract** operator takes two expressions, **a** and **b**, and + returns the difference, with a *scale* equal to the max of the *scale*s of + **a** and **b**. + +**\<\<** + +: The **left shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the right. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**\>\>** + +: The **right shift** operator takes two expressions, **a** and **b**, and + returns a copy of the value of **a** with its decimal point moved **b** + places to the left. + + The second expression must be an integer (no *scale*) and non-negative. + + This is a **non-portable extension**. + +**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** + +: The **assignment** operators take two expressions, **a** and **b** where + **a** is a named expression (see the *Named Expressions* subsection). + + For **=**, **b** is copied and the result is assigned to **a**. For all + others, **a** and **b** are applied as operands to the corresponding + arithmetic operator and the result is assigned to **a**. + + The **assignment** operators that correspond to operators that are + extensions are themselves **non-portable extensions**. + +**==** **\<=** **\>=** **!=** **\<** **\>** + +: The **relational** operators compare two expressions, **a** and **b**, and + if the relation holds, according to C language semantics, the result is + **1**. Otherwise, it is **0**. + + Note that unlike in C, these operators have a lower precedence than the + **assignment** operators, which means that **a=b\>c** is interpreted as + **(a=b)\>c**. + + Also, unlike the [standard][1] requires, these operators can appear anywhere + any other expressions can be used. This allowance is a + **non-portable extension**. + +**&&** + +: The **boolean and** operator takes two expressions and returns **1** if both + expressions are non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +**||** + +: The **boolean or** operator takes two expressions and returns **1** if one + of the expressions is non-zero, **0** otherwise. + + This is *not* a short-circuit operator. + + This is a **non-portable extension**. + +## Statements + +The following items are statements: + +1. **E** +2. **{** **S** **;** ... **;** **S** **}** +3. **if** **(** **E** **)** **S** +4. **if** **(** **E** **)** **S** **else** **S** +5. **while** **(** **E** **)** **S** +6. **for** **(** **E** **;** **E** **;** **E** **)** **S** +7. An empty statement +8. **break** +9. **continue** +10. **quit** +11. **halt** +12. **limits** +13. A string of characters, enclosed in double quotes +14. **print** **E** **,** ... **,** **E** +15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for + a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form + **I[]**, which will automatically be turned into array references (see the + *Array References* subsection of the **FUNCTIONS** section) if the + corresponding parameter in the function definition is an array reference. + +Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. + +Also, as a **non-portable extension**, any or all of the expressions in the +header of a for loop may be omitted. If the condition (second expression) is +omitted, it is assumed to be a constant **1**. + +The **break** statement causes a loop to stop iterating and resume execution +immediately following a loop. This is only allowed in loops. + +The **continue** statement causes a loop iteration to stop early and returns to +the start of the loop, including testing the loop condition. This is only +allowed in loops. + +The **if** **else** statement does the same thing as in C. + +The **quit** statement causes bc(1) to quit, even if it is on a branch that will +not be executed (it is a compile-time command). + +The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** +if it is on a branch of an **if** statement that is not executed, bc(1) does not +quit.) + +The **limits** statement prints the limits that this bc(1) is subject to. This +is like the **quit** statement in that it is a compile-time command. + +An expression by itself is evaluated and printed, followed by a newline. + +Both scientific notation and engineering notation are available for printing the +results of expressions. Scientific notation is activated by assigning **0** to +**obase**, and engineering notation is activated by assigning **1** to +**obase**. To deactivate them, just assign a different value to **obase**. + +Scientific notation and engineering notation are disabled if bc(1) is run with +either the **-s** or **-w** command-line options (or equivalents). + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +## Print Statement + +The "expressions" in a **print** statement may also be strings. If they are, there +are backslash escape sequences that are interpreted specially. What those +sequences are, and what they cause to be printed, are shown below: + +-------- ------- +**\\a** **\\a** +**\\b** **\\b** +**\\\\** **\\** +**\\e** **\\** +**\\f** **\\f** +**\\n** **\\n** +**\\q** **"** +**\\r** **\\r** +**\\t** **\\t** +-------- ------- + +Any other character following a backslash causes the backslash and character to +be printed as-is. + +Any non-string expression in a print statement shall be assigned to **last**, +like any other expression that is printed. + +## Order of Evaluation + +All expressions in a statment are evaluated left to right, except as necessary +to maintain order of operations. This means, for example, assuming that **i** is +equal to **0**, in the expression + + a[i++] = i++ + +the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** +at the end of the expression. + +This includes function arguments. Thus, assuming **i** is equal to **0**, this +means that in the expression + + x(i++, i++) + +the first argument passed to **x()** is **0**, and the second argument is **1**, +while **i** is equal to **2** before the function starts executing. + +# FUNCTIONS + +Function definitions are as follows: + +``` +define I(I,...,I){ + auto I,...,I + S;...;S + return(E) +} +``` + +Any **I** in the parameter list or **auto** list may be replaced with **I[]** to +make a parameter or **auto** var an array, and any **I** in the parameter list +may be replaced with **\*I[]** to make a parameter an array reference. Callers +of functions that take array references should not put an asterisk in the call; +they must be called with just **I[]** like normal array parameters and will be +automatically converted into references. + +As a **non-portable extension**, the opening brace of a **define** statement may +appear on the next line. + +As a **non-portable extension**, the return statement may also be in one of the +following forms: + +1. **return** +2. **return** **(** **)** +3. **return** **E** + +The first two, or not specifying a **return** statement, is equivalent to +**return (0)**, unless the function is a **void** function (see the *Void +Functions* subsection below). + +## Void Functions + +Functions can also be **void** functions, defined as follows: + +``` +define void I(I,...,I){ + auto I,...,I + S;...;S + return +} +``` + +They can only be used as standalone expressions, where such an expression would +be printed alone, except in a print statement. + +Void functions can only use the first two **return** statements listed above. +They can also omit the return statement entirely. + +The word "void" is not treated as a keyword; it is still possible to have +variables, arrays, and functions named **void**. The word "void" is only +treated specially right after the **define** keyword. + +This is a **non-portable extension**. + +## Array References + +For any array in the parameter list, if the array is declared in the form + +``` +*I[] +``` + +it is a **reference**. Any changes to the array in the function are reflected, +when the function returns, to the array that was passed in. + +Other than this, all function arguments are passed by value. + +This is a **non-portable extension**. + +# LIBRARY + +All of the functions below, including the functions in the extended math +library (see the *Extended Library* subsection below), are available when the +**-l** or **--mathlib** command-line flags are given, except that the extended +math library is not available when the **-s** option, the **-w** option, or +equivalents are given. + +## Standard Library + +The [standard][1] defines the following functions for the math library: + +**s(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**c(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a(x)** + +: Returns the arctangent of **x**, in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l(x)** + +: Returns the natural logarithm of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**e(x)** + +: Returns the mathematical constant **e** raised to the power of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**j(x, n)** + +: Returns the bessel integer order **n** (truncated) of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +## Extended Library + +The extended library is *not* loaded when the **-s**/**--standard** or +**-w**/**--warn** options are given since they are not part of the library +defined by the [standard][1]. + +The extended library is a **non-portable extension**. + +**p(x, y)** + +: Calculates **x** to the power of **y**, even if **y** is not an integer, and + returns the result to the current **scale**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round half away from **0**][3]. + +**ceil(x, p)** + +: Returns **x** rounded to **p** decimal places according to the rounding mode + [round away from **0**][6]. + +**f(x)** + +: Returns the factorial of the truncated absolute value of **x**. + +**perm(n, k)** + +: Returns the permutation of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**comb(n, k)** + +: Returns the combination of the truncated absolute value of **n** of the + truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. + +**l2(x)** + +: Returns the logarithm base **2** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**l10(x)** + +: Returns the logarithm base **10** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**log(x, b)** + +: Returns the logarithm base **b** of **x**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cbrt(x)** + +: Returns the cube root of **x**. + +**root(x, n)** + +: Calculates the truncated value of **n**, **r**, and returns the **r**th root + of **x** to the current **scale**. + + If **r** is **0** or negative, this raises an error and causes bc(1) to + reset (see the **RESET** section). It also raises an error and causes bc(1) + to reset if **r** is even and **x** is negative. + +**pi(p)** + +: Returns **pi** to **p** decimal places. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**t(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**a2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**sin(x)** + +: Returns the sine of **x**, which is assumed to be in radians. + + This is an alias of **s(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**cos(x)** + +: Returns the cosine of **x**, which is assumed to be in radians. + + This is an alias of **c(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**tan(x)** + +: Returns the tangent of **x**, which is assumed to be in radians. + + If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) + to reset (see the **RESET** section). + + This is an alias of **t(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan(x)** + +: Returns the arctangent of **x**, in radians. + + This is an alias of **a(x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**atan2(y, x)** + +: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are + equal to **0**, it raises an error and causes bc(1) to reset (see the + **RESET** section). Otherwise, if **x** is greater than **0**, it returns + **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal + to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** + is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, + and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to + **0**, and **y** is less than **0**, it returns **-pi/2**. + + This function is the same as the **atan2()** function in many programming + languages. + + This is an alias of **a2(y, x)**. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**r2d(x)** + +: Converts **x** from radians to degrees and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**d2r(x)** + +: Converts **x** from degrees to radians and returns the result. + + This is a transcendental function (see the *Transcendental Functions* + subsection below). + +**frand(p)** + +: Generates a pseudo-random number between **0** (inclusive) and **1** + (exclusive) with the number of decimal digits after the decimal point equal + to the truncated absolute value of **p**. If **p** is not **0**, then + calling this function will change the value of **seed**. If **p** is **0**, + then **0** is returned, and **seed** is *not* changed. + +**ifrand(i, p)** + +: Generates a pseudo-random number that is between **0** (inclusive) and the + truncated absolute value of **i** (exclusive) with the number of decimal + digits after the decimal point equal to the truncated absolute value of + **p**. If the absolute value of **i** is greater than or equal to **2**, and + **p** is not **0**, then calling this function will change the value of + **seed**; otherwise, **0** is returned and **seed** is not changed. + +**srand(x)** + +: Returns **x** with its sign flipped with probability **0.5**. In other + words, it randomizes the sign of **x**. + +**brand()** + +: Returns a random boolean value (either **0** or **1**). + +**ubytes(x)** + +: Returns the numbers of unsigned integer bytes required to hold the truncated + absolute value of **x**. + +**sbytes(x)** + +: Returns the numbers of signed, two's-complement integer bytes required to + hold the truncated value of **x**. + +**hex(x)** + +: Outputs the hexadecimal (base **16**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary(x)** + +: Outputs the binary (base **2**) representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output(x, b)** + +: Outputs the base **b** representation of **x**. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in as few power of two bytes as possible. Both outputs are + split into bytes separated by spaces. + + If **x** is not an integer or is negative, an error message is printed + instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in as few power of two bytes as possible. Both + outputs are split into bytes separated by spaces. + + If **x** is not an integer, an error message is printed instead, but bc(1) + is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uintn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **n** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **n** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**intn(x, n)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **n** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **n** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **1** byte. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **1** byte, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int8(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **1** byte. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **1** byte, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **2** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **2** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int16(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **2** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **2** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **4** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **4** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int32(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **4** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **4** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**uint64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as an + unsigned integer in **8** bytes. Both outputs are split into bytes separated + by spaces. + + If **x** is not an integer, is negative, or cannot fit into **8** bytes, an + error message is printed instead, but bc(1) is not reset (see the **RESET** + section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**int64(x)** + +: Outputs the representation, in binary and hexadecimal, of **x** as a signed, + two's-complement integer in **8** bytes. Both outputs are split into bytes + separated by spaces. + + If **x** is not an integer or cannot fit into **8** bytes, an error message + is printed instead, but bc(1) is not reset (see the **RESET** section). + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**hex_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in hexadecimal using **n** bytes. Not all of the value will + be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**binary_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in binary using **n** bytes. Not all of the value will be + output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_uint(x, n)** + +: Outputs the representation of the truncated absolute value of **x** as an + unsigned integer in the current **obase** (see the **SYNTAX** section) using + **n** bytes. Not all of the value will be output if **n** is too small. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +**output_byte(x, i)** + +: Outputs byte **i** of the truncated absolute value of **x**, where **0** is + the least significant byte and **number_of_bytes - 1** is the most + significant byte. + + This is a **void** function (see the *Void Functions* subsection of the + **FUNCTIONS** section). + +## Transcendental Functions + +All transcendental functions can return slightly inaccurate results (up to 1 +[ULP][4]). This is unavoidable, and [this article][5] explains why it is +impossible and unnecessary to calculate exact results for the transcendental +functions. + +Because of the possible inaccuracy, I recommend that users call those functions +with the precision (**scale**) set to at least 1 higher than is necessary. If +exact results are *absolutely* required, users can double the precision +(**scale**) and then truncate. + +The transcendental functions in the standard math library are: + +* **s(x)** +* **c(x)** +* **a(x)** +* **l(x)** +* **e(x)** +* **j(x, n)** + +The transcendental functions in the extended math library are: + +* **l2(x)** +* **l10(x)** +* **log(x, b)** +* **pi(p)** +* **t(x)** +* **a2(y, x)** +* **sin(x)** +* **cos(x)** +* **tan(x)** +* **atan(x)** +* **atan2(y, x)** +* **r2d(x)** +* **d2r(x)** + +# RESET + +When bc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any functions that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +functions returned) is skipped. + +Thus, when bc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +Note that this reset behavior is different from the GNU bc(1), which attempts to +start executing the statement right after the one that caused an error. + +# PERFORMANCE + +Most bc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This bc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**BC_BASE_DIGS**. + +The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with +the **limits** statement. + +In addition, this bc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **BC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on bc(1): + +**BC_LONG_BIT** + +: The number of bits in the **long** type in the environment where bc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**BC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **BC_LONG_BIT**. + +**BC_BASE_POW** + +: The max decimal number that each large integer can store (see + **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. + +**BC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **BC_LONG_BIT**. + +**BC_BASE_MAX** + +: The maximum output base. Set at **BC_BASE_POW**. + +**BC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**BC_SCALE_MAX** + +: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. + +**BC_STRING_MAX** + +: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NAME_MAX** + +: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. + +**BC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **BC_OVERFLOW_MAX-1**. + +**BC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **rand()** operand. Set at + **2\^BC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **BC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +The actual values can be queried with the **limits** statement. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +bc(1) recognizes the following environment variables: + +**POSIXLY_CORRECT** + +: If this variable exists (no matter the contents), bc(1) behaves as if + the **-s** option was given. + +**BC_ENV_ARGS** + +: This is another way to give command-line arguments to bc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **BC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time bc(1) runs. + + The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string + **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **BC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**BC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output + lines to that length, including the backslash (**\\**). The default line + length is **70**. + +**BC_EXPR_EXIT** + +: If this variable exists (no matter the contents), bc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +bc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**) + operators and their corresponding assignment operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, using a token where it is invalid, + giving an invalid expression, giving an invalid print statement, giving an + invalid function definition, attempting to assign to an expression that is + not a named expression (see the *Named Expressions* subsection of the + **SYNTAX** section), giving an invalid **auto** list, having a duplicate + **auto**/function parameter, failing to find the end of a code block, + attempting to return a value from a **void** function, attempting to use a + variable as a reference, and using any extensions when the option **-s** or + any equivalents were given. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, passing the wrong number of + arguments to functions, attempting to call an undefined function, and + attempting to use a **void** function call as a value in an expression. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (bc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, bc(1) always exits +and returns **4**, no matter what mode bc(1) is in. + +The other statuses will only be returned when bc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow bc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, bc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If +bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If bc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If bc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it +can seem as though bc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with bc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This bc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGES**. + +# SEE ALSO + +dc(1) + +# STANDARDS + +bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] +specification. The flags **-efghiqsvVw**, all long options, and the extensions +noted above are extensions to that specification. + +Note that the specification explicitly says that bc(1) only accepts numbers that +use a period (**.**) as a radix point, regardless of the value of +**LC_NUMERIC**. + +This bc(1) supports error messages for different locales, and thus, it supports +**LC_MESSAGES**. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHORS + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html +[2]: https://www.gnu.org/software/bc/ +[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero +[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place +[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT +[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero diff --git a/manuals/build.md b/manuals/build.md index 5ced5e70c13c..3d0c0132fb85 100644 --- a/manuals/build.md +++ b/manuals/build.md @@ -402,7 +402,7 @@ the others are, as the operators `$`, `@`, `H`, and `h`, respectively. In addition, this `bc` has the option of outputting in scientific notation or engineering notation. It can also take input in scientific or engineering notation. On top of that, it has a pseudo-random number generator. (See the -[full manual](./bc.md) for more details.) +full manual for more details.) Extra operators, scientific notation, engineering notation, and the pseudo-random number generator can be disabled by passing either the `-E` flag @@ -417,8 +417,7 @@ Both commands are equivalent. This `bc` also has a larger library that is only enabled if extra operators and the pseudo-random number generator are. More information about the functions can -be found in the [Extended Library](./bc.md#extended-library) section of the -[full manual](./bc.md). +be found in the Extended Library section of the full manual. ### Manpages diff --git a/manuals/dc.1 b/manuals/dc.1 deleted file mode 100644 index edc55a5cad62..000000000000 --- a/manuals/dc.1 +++ /dev/null @@ -1,951 +0,0 @@ -.\" generated with Ronn/v0.7.3 -.\" http://github.com/rtomayko/ronn/tree/0.7.3 -. -.TH "DC" "1" "June 2020" "Gavin D. Howard" "General Commands Manual" -. -.SH "NAME" -\fBdc\fR \- arbitrary\-precision reverse\-Polish notation calculator -. -.SH "SYNOPSIS" -\fBdc\fR [\fB\-hiPvVx\fR] [\fB\-\-version\fR] [\fB\-\-help\fR] [\fB\-\-interactive\fR] [\fB\-\-no\-prompt\fR] [\fB\-\-extended\-register\fR] [\fB\-e\fR \fIexpr\fR] [\fB\-\-expression=\fR\fIexpr\fR\.\.\.] [\fB\-f\fR \fIfile\fR\.\.\.] [\fB\-file=\fR\fIfile\fR\.\.\.] [\fIfile\fR\.\.\.] -. -.SH "DESCRIPTION" -dc(1) is an arbitrary\-precision calculator\. It uses a stack (reverse Polish notation) to store numbers and results of computations\. Arithmetic operations pop arguments off of the stack and push the results\. -. -.P -If no files are given on the command\-line as extra arguments (i\.e\., not as \fB\-f\fR or \fB\-\-file\fR arguments), then dc(1) reads from \fBstdin\fR\. Otherwise, those files are processed, and dc(1) will then exit\. -. -.P -This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \fB\-e\fR (\fB\-\-expression\fR) and \fB\-f\fR (\fB\-\-file\fR) arguments cause dc(1) to execute them and exit\. The reason for this is that this dc(1) allows users to set arguments in the environment variable \fBDC_ENV_ARGS\fR (see the ENVIRONMENT VARIABLES section)\. Any expressions given on the command\-line should be used to set up a standard environment\. For example, if a user wants the \fBscale\fR always set to \fB10\fR, they can set \fBDC_ENV_ARGS\fR to "\-e 10k", and this dc(1) will always start with a \fBscale\fR of \fB10\fR\. -. -.P -If users want to have dc(1) exit after processing all input from \fB\-e\fR and \fB\-f\fR arguments (and their equivalents), then they can just simply add "\-e q" as the last command\-line argument or define the environment variable \fBDC_EXPR_EXIT\fR\. -. -.SH "OPTIONS" -The following are the options that dc(1) accepts\. -. -.TP -\fB\-h\fR, \fB\-\-help\fR -Prints a usage message and quits\. -. -.TP -\fB\-v\fR, \fB\-V\fR, \fB\-\-version\fR -Print the version information (copyright header) and exit\. -. -.TP -\fB\-i\fR, \fB\-\-interactive\fR -Forces interactive mode\. (See the INTERACTIVE MODE section\.) -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-P\fR, \fB\-\-no\-prompt\fR -Disables the prompt in interactive mode\. This is mostly for those users that do not want a prompt or are not used to having them in \fBdc\fR\. Most of those users would want to put this option in \fBDC_ENV_ARGS\fR\. -. -.IP -If the prompt has been disabled while building dc(1), this option is a no\-op\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-x\fR \fB\-\-extended\-register\fR -Enables extended register mode\. See the REGISTERS section for more information\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-e\fR \fIexpr\fR, \fB\-\-expression\fR=\fIexpr\fR -Evaluates \fBexpr\fR\. If multiple expressions are given, they are evaluated in order\. If files are given as well (see below), the expressions and files are evaluated in the order given\. This means that if a file is given before an expression, the file is read in and evaluated first\. -. -.IP -In other dc(1) implementations, this option causes the program to execute the expressions and then exit\. This dc(1) does not, unless the \fBDC_EXPR_EXIT\fR is defined (see the ENVIRONMENT VARIABLES section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB\-f\fR \fIfile\fR, \fB\-\-file\fR=\fIfile\fR -Reads in \fBfile\fR and evaluates it\. If expressions are also given (see above), the expressions are evaluated in the order given\. -. -.IP -In other dc(1) implementations, this option causes the program to execute the files and then exit\. This dc(1) does not, unless the \fBDC_EXPR_EXIT\fR is defined (see the ENVIRONMENT VARIABLES section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.P -\fBNote\fR: long options are only accepted if dc(1) is built with them enabled\. -. -.SH "STDOUT" -Any non\-error output is written to \fBstdout\fR\. -. -.P -\fBNote\fR: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the EXIT STATUS section) if it cannot write to \fBstdout\fR, so if \fBstdout\fR is closed, as in \fBdc >&\-\fR, it will quit with an error\. This is done so that dc(1) can report problems when \fBstdout\fR is redirected to a file\. -. -.P -If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \fBstdout\fR to \fB/dev/null\fR\. -. -.SH "STDERR" -Any error output is written to \fBstderr\fR\. -. -.P -\fBNote\fR: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the EXIT STATUS section) if it cannot write to \fBstderr\fR, so if \fBstderr\fR is closed, as in \fBdc 2>&\-\fR, it will quit with an error\. This is done so that dc(1) can report problems when \fBstderr\fR is redirected to a file\. -. -.P -If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \fBstderr\fR to \fB/dev/null\fR\. -. -.SH "SYNTAX" -\fBibase\fR is a register (see the REGISTERS section) determining how to interpret constant numbers\. It is the "input" base, or the number base used for interpreting input numbers\. \fBibase\fR is initially \fB10\fR\. The max allowable value for \fBibase\fR is \fB16\fR\. The min allowable value for \fBibase\fR is \fB2\fR\. The max allowable value for \fBibase\fR can be queried in dc(1) programs with the \fBT\fR command\. -. -.P -\fBobase\fR is a register (see the REGISTERS section) determining how to output results\. It is the "output" base, or the number base used for outputting numbers\. \fBobase\fR is initially \fB10\fR\. The max allowable value for \fBobase\fR is \fBDC_BASE_MAX\fR\. The min allowable value for \fBobase\fR is \fB2\fR unless dc(1) was built with the extra math option\. If it was, then the min allowable value is \fB0\fR\. In this case, if \fBobase\fR is \fB0\fR, values are output in scientific notation, and if \fBobase\fR is \fB1\fR, values are output in engineering notation\. (Outputting in scientific or engineering notation are \fBnon\-portable extensions\fR\.) The max allowable value for \fBobase\fR can be queried in dc(1) programs with the \fBU\fR command\. -. -.P -The \fBscale\fR of an expression is the number of digits in the result of the expression right of the decimal point, and \fBscale\fR is a register (see the REGISTERS section) that sets the precision of any operations (with exceptions)\. \fBscale\fR is initially \fB0\fR\. \fBscale\fR cannot be negative\. The max allowable value for \fBscale\fR can be queried in dc(1) programs with the \fBV\fR command\. -. -.P -Each item in the input source code, either a number (see the NUMBERS section) or a command (see the COMMANDS section), is processed and executed, in order\. Input is processed immediately when entered\. -. -.P -If dc(1) was built with the extra math option, there is an additional register named \fBseed\fR\. This is the current seed used by the pseudo\-random number generator\. If the current value of \fBseed\fR is queried and stored, then if it is assigned to \fBseed\fR later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \fBseed\fR was first queried\. -. -.P -Multiple values assigned to \fBseed\fR can produce the same sequence of pseudo\-random numbers\. Likewise, when a value is assigned to \fBseed\fR, it is not guaranteed that querying \fBseed\fR immediately after will return the same value\. In addition, the value of \fBseed\fR will change after any call to the \fB'\fR or \fB"\fR commands\. The maximum integer returned by the \fB'\fR command can be queried with the \fBW\fR command\. -. -.P -\fBNote\fR: The values returned by the pseudo\-random number generator with the \fB'\fR and \fB"\fR commands are guaranteed to \fBNOT\fR be cryptographically\-secure\. This is a consequence of using a seeded pseudo\-random number generator\. However, they \fBare\fR guaranteed to be reproducible with identical \fBseed\fR values\. -. -.P -The pseudo\-random number generator, \fBseed\fR, and all associated operations are \fBnon\-portable extensions\fR\. -. -.SS "Comments" -Comments go from \fB#\fR until, and not including, the next newline\. This is a \fBnon\-portable extension\fR\. -. -.SH "NUMBERS" -Numbers are strings made up of digits, uppercase letters up to \fBF\fR, and at most \fB1\fR period for a radix\. Numbers can have up to \fBDC_NUM_MAX\fR digits\. Uppercase letters equal \fB9\fR + their position in the alphabet (i\.e\., \fBA\fR equals \fB10\fR, or \fB9 + 1\fR)\. If a digit or letter makes no sense with the current value of \fBibase\fR, they are set to the value of the highest valid digit in \fBibase\fR\. -. -.P -Single\-character numbers (i\.e\., \fBA\fR) take the value that they would have if they were valid digits, regardless of the value of \fBibase\fR\. This means that \fBA\fR always equals decimal \fB10\fR and \fBF\fR always equals decimal \fB15\fR\. -. -.P -In addition, if dc(1) was built with the extra math option, it accepts numbers in scientific notation\. For dc(1), an example is \fB1\.89237e9\fR, which is equal to \fB1892370000\fR\. Negative exponents are also allowed, so \fB4\.2890e_3\fR is equal to \fB0\.0042890\fR\. -. -.P -\fBWARNING\fR: Both the number and the exponent in scientific notation are interpreted according to the current \fBibase\fR, but the number is still multiplied by \fB10^exponent\fR regardless of the current \fBibase\fR\. For example, if \fBibase\fR is \fB16\fR and dc(1) is given the number string \fB"FFeA"\fR, the resulting decimal number will be \fB2550000000000\fR, and if dc(1) is given the number string \fB"10e_4"\fR, the resulting decimal number will be \fB0\.0016\fR\. -. -.P -Accepting input as scientific notation is a \fBnon\-portable extension\fR\. -. -.SH "COMMANDS" -The valid commands are listed below\. -. -.SS "Printing" -These commands are used for printing\. -. -.P -Note that if dc(1) has been built with the extra math option enabled, both scientific notation and engineering notation are available for printing numbers\. Scientific notation is activated by assigning \fB0\fR to \fBobase\fR using \fB0o\fR (in any other context, an \fBobase\fR of \fB0\fR is invalid), and engineering notation is activated by assigning \fB1\fR to \fBobase\fR using \fB1o\fR (which is also invalid in any other context)\. To deactivate them, just assign a different value to \fBobase\fR\. -. -.P -Printing numbers in scientific notation and/or engineering notation is a \fBnon\-portable extension\fR\. -. -.TP -\fBp\fR -Prints the value on top of the stack, whether number or string, and prints a newline after\. -. -.IP -This does not alter the stack\. -. -.TP -\fBn\fR -Prints the value on top of the stack, whether number or string, and pops it off of the stack\. -. -.TP -\fBP\fR -Pops a value off the stack\. -. -.IP -If the value is a number, it is truncated and the absolute value of the result is printed as though \fBobase\fR is \fBUCHAR_MAX + 1\fR and each digit is interpreted as an ASCII character, making it a byte stream\. -. -.IP -If the value is a string, it is printed without a trailing newline\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBf\fR -Prints the entire contents of the stack, in order from newest to oldest, without altering anything\. -. -.IP -Users should use this command when they get lost\. -. -.SS "Arithmetic" -These are the commands used for arithmetic\. -. -.TP -\fB+\fR -The top two values are popped off the stack, added, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to the max \fBscale\fR of both operands\. -. -.TP -\fB\-\fR -The top two values are popped off the stack, subtracted, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to the max \fBscale\fR of both operands\. -. -.TP -\fB*\fR -The top two values are popped off the stack, multiplied, and the result is pushed onto the stack\. If \fBa\fR is the \fBscale\fR of the first expression and \fBb\fR is the \fBscale\fR of the second expression, the \fBscale\fR of the result is equal to \fBmin(a+b,max(scale,a,b))\fR where \fBmin\fR and \fBmax\fR return the obvious values\. -. -.TP -\fB/\fR -The top two values are popped off the stack, divided, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to \fBscale\fR\. -. -.IP -The first value popped off of the stack must be non\-zero\. -. -.TP -\fB%\fR -The top two values are popped off the stack, remaindered, and the result is pushed onto the stack\. -. -.IP -Remaindering is equivalent to 1) Computing \fBa/b\fR to current \fBscale\fR, and 2) Using the result of step 1 to calculate \fBa\-(a/b)*b\fR to \fBscale\fR \fBmax(scale + scale(b), scale(a))\fR\. -. -.IP -The first value popped off of the stack must be non\-zero\. -. -.TP -\fB~\fR -The top two values are popped off the stack, divided and remaindered, and the results (divided first, remainder second) are pushed onto the stack\. This is equivalent to \fBx y / x y %\fR except that \fBx\fR and \fBy\fR are only evaluated once\. -. -.IP -The first value popped off of the stack must be non\-zero\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB^\fR -The top two values are popped off the stack, the second is raised to the power of the first, and the result is pushed onto the stack\. -. -.IP -The first value popped off of the stack must be an integer, and if that value is negative, the second value popped off of the stack must be non\-zero\. -. -.TP -\fBv\fR -The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to \fBscale\fR\. -. -.IP -The value popped off of the stack must be non\-negative\. -. -.TP -\fB_\fR -If this command \fIimmediately\fR precedes a number (i\.e\., no spaces or other commands), then that number is input as a negative number\. -. -.IP -Otherwise, the top value on the stack is popped and copied, and the copy is negated and pushed onto the stack\. This behavior without a number is a \fBnon\-portable extension\fR\. -. -.TP -\fBb\fR -The top value is popped off the stack, and if it is zero, it is pushed back onto the stack\. Otherwise, its absolute value is pushed onto the stack\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB|\fR -The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack\. -. -.IP -The first value popped is used as the reduction modulus and must be an integer and non\-zero\. The second value popped is used as the exponent and must be an integer and non\-negative\. The third value popped is the base and must be an integer\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB$\fR -The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB@\fR -The top two values are popped off the stack, and the precision of the second is set to the value of the first, whether by truncation or extension\. -. -.IP -The first value popped off of the stack must be an integer and non\-negative\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBH\fR -The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first\. -. -.IP -The first value popped off of the stack must be an integer and non\-negative\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBh\fR -The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first\. -. -.IP -The first value popped off of the stack must be an integer and non\-negative\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBG\fR -The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if they are equal, or \fB0\fR otherwise\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBN\fR -The top value is popped off of the stack, and if it a \fB0\fR, a \fB1\fR is pushed; otherwise, a \fB0\fR is pushed\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB(\fR -The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is less than the second, or \fB0\fR otherwise\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB{\fR -The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is less than or equal to the second, or \fB0\fR otherwise\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB)\fR -The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is greater than the second, or \fB0\fR otherwise\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB}\fR -The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is greater than or equal to the second, or \fB0\fR otherwise\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBM\fR -The top two values are popped off of the stack\. If they are both non\-zero, a \fB1\fR is pushed onto the stack\. If either of them is zero, or both of them are, then a \fB0\fR is pushed onto the stack\. -. -.IP -This is like the \fB&&\fR operator in bc(1), and it is not a short\-circuit operator\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBm\fR -The top two values are popped off of the stack\. If at least one of them is non\-zero, a \fB1\fR is pushed onto the stack\. If both of them are zero, then a \fB0\fR is pushed onto the stack\. -. -.IP -This is like the \fB||\fR operator in bc(1), and it is not a short\-circuit operator\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.SS "Pseudo\-Random Number Generator" -If dc(1) was built with the extra math option, it has a built\-in pseudo\-random number generator\. These commands query the pseudo\-random number generator\. (See Parameters for more information about the \fBseed\fR value that controls the pseudo\-random number generator\.) -. -.P -The pseudo\-random number generator is guaranteed to \fBNOT\fR be cryptographically\-secure\. -. -.TP -\fB'\fR -Generates an integer between 0 and \fBDC_RAND_MAX\fR, inclusive (see the LIMITS section)\. -. -.IP -The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator\. -. -.IP -This command is only available if dc(1) was built with the extra math option\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB"\fR -Pops a value off of the stack, which is used as an \fBexclusive\fR upper bound on the integer that will be generated\. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the RESET section)\. If the bound is larger than \fBDC_RAND_MAX\fR, the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \fBDC_RAND_MAX + 1\fR, and adding them together\. Thus, the size of integer that can be generated with this command is unbounded\. Using this command will change the value of \fBseed\fR\. -. -.IP -If the operand is \fB0\fR or \fB1\fR, then the result pushed onto the stack is \fB0\fR, and \fBseed\fR is not changed\. -. -.IP -The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator\. -. -.IP -This command is only available if dc(1) was built with the extra math option\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.SS "Stack Control" -These commands control the stack\. -. -.TP -\fBc\fR -Removes all items from ("clears") the stack\. -. -.TP -\fBd\fR -Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack\. -. -.TP -\fBr\fR -Swaps ("reverses") the two top items on the stack\. -. -.TP -\fBR\fR -Pops ("removes") the top value from the stack\. -. -.SS "Register Control" -These commands control registers (see the REGISTERS section)\. -. -.TP -\fBs\fR\fIr\fR -Pops the value off the top of the stack and stores it into register \fBr\fR\. -. -.TP -\fBl\fR\fIr\fR -Copies the value in register \fBr\fR and pushes it onto the stack\. This does not alter the contents of \fBr\fR\. -. -.TP -\fBS\fR\fIr\fR -Pops the value off the top of the (main) stack and pushes it onto the stack of register \fBr\fR\. The previous value of the register becomes inaccessible\. -. -.TP -\fBL\fR\fIr\fR -Pops the value off the top of the stack for register \fBr\fR and push it onto the main stack\. The previous value in the stack for register \fBr\fR, if any, is now accessible via the \fBl\fR\fIr\fR command\. -. -.SS "Parameters" -These commands control the values of \fBibase\fR, \fBobase\fR, \fBscale\fR, and \fBseed\fR (if dc(1) was built with the extra math option)\. Also see the SYNTAX section\. -. -.TP -\fBi\fR -Pops the value off of the top of the stack and uses it to set \fBibase\fR, which must be between \fB2\fR and \fB16\fR, inclusive\. -. -.IP -If the value on top of the stack has any \fBscale\fR, the \fBscale\fR is ignored\. -. -.TP -\fBo\fR -Pops the value off of the top of the stack and uses it to set \fBobase\fR, which must be between \fB2\fR and \fBDC_BASE_MAX\fR, inclusive (see bc(1))\. The value can be either \fB0\fR or \fB1\fR if dc(1) was built with the extra math option\. -. -.IP -If the value on top of the stack has any \fBscale\fR, the \fBscale\fR is ignored\. -. -.TP -\fBk\fR -Pops the value off of the top of the stack and uses it to set \fBscale\fR, which must be non\-negative\. -. -.IP -If the value on top of the stack has any \fBscale\fR, the \fBscale\fR is ignored\. -. -.TP -\fBj\fR -Pops the value off of the top of the stack and uses it to set \fBseed\fR\. The meaning of \fBseed\fR is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions\. -. -.IP -The \fBscale\fR of the value may be significant\. -. -.IP -If a previously used \fBseed\fR value is used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \fBseed\fR value was previously used\. -. -.IP -The exact value assigned to \fBseed\fR is not guaranteed to be returned if the \fBJ\fR command is used\. However, if \fBseed\fR \fIdoes\fR return a different value, both values, when assigned to \fBseed\fR, are guaranteed to produce the same sequence of pseudo\-random numbers\. This means that certain values assigned to \fBseed\fR will not produce unique sequences of pseudo\-random numbers\. -. -.IP -There is no limit to the length (number of significant decimal digits) or \fIscale\fR of the value that can be assigned to \fBseed\fR\. -. -.IP -This command is only available if dc(1) was built with the extra math option\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBI\fR -Pushes the current value of \fBibase\fR onto the main stack\. -. -.TP -\fBO\fR -Pushes the current value of \fBobase\fR onto the main stack\. -. -.TP -\fBK\fR -Pushes the current value of \fBscale\fR onto the main stack\. -. -.TP -\fBJ\fR -Pushes the current value of \fBseed\fR onto the main stack\. -. -.IP -This command is only available if dc(1) was built with the extra math option\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBT\fR -Pushes the maximum allowable value of \fBibase\fR onto the main stack\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBU\fR -Pushes the maximum allowable value of \fBobase\fR onto the main stack\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBV\fR -Pushes the maximum allowable value of \fBscale\fR onto the main stack\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBW\fR -Pushes the maximum (inclusive) integer that can be generated with the \fB'\fR pseudo\-random number generator command\. -. -.IP -This command is only available if dc(1) was built with the extra math option\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.SS "Strings" -The following commands control strings\. -. -.P -dc(1) can work with both numbers and strings, and registers (see the REGISTERS section) can hold both strings and numbers\. dc(1) always knows whether the contents of a register are a string or a number\. -. -.P -While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings\. -. -.P -Strings can also be executed as macros\. For example, if the string \fB[1pR]\fR is executed as a macro, then the code \fB1pR\fR is executed, meaning that the \fB1\fR will be printed with a newline after and then popped from the stack\. -. -.TP -\fB[\fR\fIcharacters\fR\fB]\fR -Makes a string containing \fIcharacters\fR and pushes it onto the stack\. -. -.IP -If there are brackets (\fB[\fR and \fB]\fR) in the string, then they must be balanced\. Unbalanced brackets can be escaped using a backslash (\fB\e\fR) character\. -. -.IP -If there is a backslash character in the string, the character after it (even another backslash) is put into the string verbatim, but the (first) backslash is not\. -. -.TP -\fBa\fR -The value on top of the stack is popped\. -. -.IP -If it is a number, it is truncated and its absolute value is taken\. The result mod \fBUCHAR_MAX + 1\fR is calculated\. If that result is \fB0\fR, push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character\. -. -.IP -If it is a string, then a new string is made\. If the original string is empty, the new string is empty\. If it is not, then the first character of the original string is used to create the new string as a one\-character string\. The new string is then pushed onto the stack\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fBx\fR -Pops a value off of the top of the stack\. -. -.IP -If it is a number, it is pushed onto the stack\. -. -.IP -If it is a string, it is executed as a macro\. -. -.IP -This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below\. -. -.TP -\fB>\fR\fIr\fR -Pops two values off of the stack that must be numbers and compares them\. If the first value is greater than the second, then the contents of register \fBr\fR are executed\. -. -.IP -For example, \fB0 1>a\fR will execute the contents of register \fBa\fR, and \fB1 0>a\fR will not\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.TP -\fB>\fR\fIr\fR\fBe\fR\fIs\fR -Like the above, but will execute register \fBs\fR if the comparison fails\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB!>\fR\fIr\fR -Pops two values off of the stack that must be numbers and compares them\. If the first value is not greater than the second (less than or equal to), then the contents of register \fBr\fR are executed\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.TP -\fB!>\fR\fIr\fR\fBe\fR\fIs\fR -Like the above, but will execute register \fBs\fR if the comparison fails\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB<\fR\fIr\fR -Pops two values off of the stack that must be numbers and compares them\. If the first value is less than the second, then the contents of register \fBr\fR are executed\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.TP -\fB<\fR\fIr\fR\fBe\fR\fIs\fR -Like the above, but will execute register \fBs\fR if the comparison fails\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB!<\fR\fIr\fR -Pops two values off of the stack that must be numbers and compares them\. If the first value is not less than the second (greater than or equal to), then the contents of register \fBr\fR are executed\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.TP -\fB!<\fR\fIr\fR\fBe\fR\fIs\fR -Like the above, but will execute register \fBs\fR if the comparison fails\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB=\fR\fIr\fR -Pops two values off of the stack that must be numbers and compares them\. If the first value is equal to the second, then the contents of register \fBr\fR are executed\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.TP -\fB=\fR\fIr\fR\fBe\fR\fIs\fR -Like the above, but will execute register \fBs\fR if the comparison fails\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB!=\fR\fIr\fR -Pops two values off of the stack that must be numbers and compares them\. If the first value is not equal to the second, then the contents of register \fBr\fR are executed\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.TP -\fB!=\fR\fIr\fR\fBe\fR\fIs\fR -Like the above, but will execute register \fBs\fR if the comparison fails\. -. -.IP -If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\. -. -.IP -This is a \fBnon\-portable extension\fR\. -. -.TP -\fB?\fR -Reads a line from the \fBstdin\fR and executes it\. This is to allow macros to request input from users\. -. -.TP -\fBq\fR -During execution of a macro, this exits the execution of that macro and the execution of the macro that executed it\. If there are no macros, or only one macro executing, dc(1) exits\. -. -.TP -\fBQ\fR -Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack\. If the number of levels to pop is greater than the number of executing macros, dc(1) exits\. -. -.SS "Status" -These commands query status of the stack or its top value\. -. -.TP -\fBZ\fR -Pops a value off of the stack\. -. -.IP -If it is a number, calculates the number of significant decimal digits it has and pushes the result\. -. -.IP -If it is a string, pushes the number of characters the string has\. -. -.TP -\fBX\fR -Pops a value off of the stack\. -. -.IP -If it is a number, pushes the \fBscale\fR of the value onto the stack\. -. -.IP -If it is a string, pushes \fB0\fR\. -. -.TP -\fBz\fR -Pushes the current stack depth (before execution of this command)\. -. -.SS "Arrays" -These commands manipulate arrays\. -. -.TP -\fB:\fR\fIr\fR -Pops the top two values off of the stack\. The second value will be stored in the array \fBr\fR (see the REGISTERS section), indexed by the first value\. -. -.TP -\fB;\fR\fIr\fR -Pops the value on top of the stack and uses it as an index into the array \fBr\fR\. The selected value is then pushed onto the stack\. -. -.SH "REGISTERS" -Registers are names that can store strings, numbers, and arrays\. (Number/string registers do not interfere with array registers\.) -. -.P -Each register is also its own stack, so the current register value is the top of the stack for the register\. All registers, when first referenced, have one value (\fB0\fR) in their stack\. -. -.P -In non\-extended register mode, a register name is just the single character that follows any command that needs a register name\. The only exception is a newline (\fB\'\en\'\fR); it is a parse error for a newline to be used as a register name\. -. -.SS "Extended Register Mode" -Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled\. -. -.P -If extended register mode is enabled (\fB\-x\fR or \fB\-\-extended\-register\fR command\-line arguments are given), then normal single character registers are used \fB\fIunless\fR\fR the character immediately following a command that needs a register name is a space (according to \fBisspace()\fR) and not a newline (\fB\'\en\'\fR)\. -. -.P -In that case, the register name is found according to the regex \fB[a\-z][a\-z0\-9_]*\fR (like bc(1)), and it is a parse error if the next non\-space characters do not match that regex\. -. -.SH "RESET" -When dc(1) encounters an error or a signal that it has a non\-default handler for, it resets\. This means that several things happen\. -. -.P -First, any macros that are executing are stopped and popped off the stack\. The behavior is not unlike that of exceptions in programming languages\. Then the execution point is set so that any code waiting to execute (after all functions returned) is skipped\. -. -.P -Thus, when dc(1) resets, it skips any remaining code waiting to be executed\. Then, if it is interactive mode, and the error was not a fatal error (see the EXIT STATUS section), it asks for more input; otherwise, it exits with the appropriate return code\. -. -.SH "PERFORMANCE" -Most dc(1) implementations use \fBchar\fR types to calculate the value of \fB1\fR decimal digit at a time, but that can be slow\. This dc(1) does something different\. -. -.P -It uses large integers to calculate more than \fB1\fR decimal digit at a time\. If built in a environment where \fBDC_LONG_BIT\fR (see the LIMITS section) is \fB64\fR, then each integer has \fB9\fR decimal digits\. If built in an environment where \fBDC_LONG_BIT\fR is \fB32\fR then each integer has \fB4\fR decimal digits\. This value (the number of decimal digits per large integer) is called \fBDC_BASE_DIGS\fR\. -. -.P -In addition, this dc(1) uses an even larger integer for overflow checking\. This integer type depends on the value of \fBDC_LONG_BIT\fR, but is always at least twice as large as the integer type used to store digits\. -. -.SH "LIMITS" -The following are the limits on dc(1): -. -.TP -\fBDC_LONG_BIT\fR -The number of bits in the \fBlong\fR type in the environment where dc(1) was built\. This determines how many decimal digits can be stored in a single large integer (see the PERFORMANCE section)\. -. -.TP -\fBDC_BASE_DIGS\fR -The number of decimal digits per large integer (see the PERFORMANCE section)\. Depends on \fBDC_LONG_BIT\fR\. -. -.TP -\fBDC_BASE_POW\fR -The max decimal number that each large integer can store (see \fBDC_BASE_DIGS\fR) plus \fB1\fR\. Depends on \fBDC_BASE_DIGS\fR\. -. -.TP -\fBDC_OVERFLOW_MAX\fR -The max number that the overflow type (see the PERFORMANCE section) can hold\. Depends on \fBDC_LONG_BIT\fR\. -. -.TP -\fBDC_BASE_DIGS\fR -The number of decimal digits per large integer (see the PERFORMANCE section)\. -. -.TP -\fBDC_BASE_MAX\fR -The maximum output base\. Set at \fBDC_BASE_POW\fR\. -. -.TP -\fBDC_DIM_MAX\fR -The maximum size of arrays\. Set at \fBSIZE_MAX\-1\fR\. -. -.TP -\fBDC_SCALE_MAX\fR -The maximum \fBscale\fR\. Set at \fBDC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBDC_STRING_MAX\fR -The maximum length of strings\. Set at \fBDC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBDC_NAME_MAX\fR -The maximum length of identifiers\. Set at \fBDC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBDC_NUM_MAX\fR -The maximum length of a number (in decimal digits), which includes digits after the decimal point\. Set at \fBDC_OVERFLOW_MAX\-1\fR\. -. -.TP -\fBDC_RAND_MAX\fR -The maximum integer (inclusive) returned by the \fB'\fR command, if dc(1) has been built with the extra math option\. Set at \fB2^DC_LONG_BIT\-1\fR\. -. -.TP -Exponent -The maximum allowable exponent (positive or negative)\. Set at \fBDC_OVERFLOW_MAX\fR\. -. -.TP -Number of vars -The maximum number of vars/arrays\. Set at \fBSIZE_MAX\-1\fR\. -. -.P -These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem\. In fact, memory should be exhausted before these limits should be hit\. -. -.SH "ENVIRONMENT VARIABLES" -dc(1) recognizes the following environment variables: -. -.TP -\fBDC_ENV_ARGS\fR -This is another way to give command\-line arguments to dc(1)\. They should be in the same format as all other command\-line arguments\. These are always processed first, so any files given in \fBDC_ENV_ARGS\fR will be processed before arguments and files given on the command\-line\. This gives the user the ability to set up "standard" options and files to be used at every invocation\. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs\. Another use would be to use the \fB\-e\fR option to set \fBscale\fR to a value other than \fB0\fR\. -. -.IP -The code that parses \fBDC_ENV_ARGS\fR will correctly handle quoted arguments, but it does not understand escape sequences\. For example, the string \fB"/home/gavin/some dc file\.dc"\fR will be correctly parsed, but the string \fB"/home/gavin/some \e"dc\e" file\.dc"\fR will include the backslashes\. -. -.IP -The quote parsing will handle either kind of quotes, \fB'\fR or \fB"\fR\. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \fB"some \'bc\' file\.bc"\fR, and vice versa if you have a file with double quotes\. However, handling a file with both kinds of quotes in \fBDC_ENV_ARGS\fR is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell\. -. -.TP -\fBDC_LINE_LENGTH\fR -If this environment variable exists and contains an integer that is greater than \fB1\fR and is less than \fBUINT16_MAX\fR (\fB2^16\-1\fR), dc(1) will output lines to that length, including the backslash newline combo\. The default line length is \fB70\fR\. -. -.TP -\fBDC_EXPR_EXIT\fR -If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \fB\-e\fR and/or \fB\-f\fR command\-line options (and any equivalents)\. -. -.SH "EXIT STATUS" -dc(1) returns the following exit statuses: -. -.TP -\fB0\fR -No error\. -. -.TP -\fB1\fR -A math error occurred\. This follows standard practice of using \fB1\fR for expected errors, since math errors will happen in the process of normal execution\. -. -.IP -Math errors include divide by \fB0\fR, taking the square root of a negative number, using a negative number as a bound for the pseudo\-random number generator, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required\. -. -.IP -Converting to a hardware integer happens for the second operand of the power (\fB^\fR), places (\fB@\fR), left shift (\fBH\fR), and right shift (\fBh\fR) operators\. -. -.TP -\fB2\fR -A parse error occurred\. -. -.IP -Parse errors include unexpected \fBEOF\fR, using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid\. -. -.TP -\fB3\fR -A runtime error occurred\. -. -.IP -Runtime errors include assigning an invalid number to \fBibase\fR, \fBobase\fR, or \fBscale\fR; give a bad expression to a \fBread()\fR call, calling \fBread()\fR inside of a \fBread()\fR call, type errors, and attempting an operation when the stack has too few elements\. -. -.TP -\fB4\fR -A fatal error occurred\. -. -.IP -Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (dc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options\. -. -.P -The exit status \fB4\fR is special; when a fatal error occurs, dc(1) always exits and returns \fB4\fR, no matter what mode dc(1) is in\. -. -.P -The other statuses will only be returned when dc(1) is not in interactive mode (see the INTERACTIVE MODE section), since dc(1) resets its state (see the RESET section) and accepts more input when one of those errors occurs in interactive mode\. This is also the case when interactive mode is forced by the \fB\-i\fR flag or \fB\-\-interactive\fR option\. -. -.P -These exit statuses allow dc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \fB\-i\fR flag or \fB\-\-interactive\fR option\. -. -.SH "INTERACTIVE MODE" -Like bc(1), dc(1) has an interactive mode and a non\-interactive mode\. Interactive mode is turned on automatically when both \fBstdin\fR and \fBstdout\fR are hooked to a terminal, but the \fB\-i\fR flag and \fB\-\-interactive\fR option can turn it on in other cases\. -. -.P -In interactive mode, dc(1) attempts to recover from errors (see the RESET section), and in normal execution, flushes \fBstdout\fR as soon as execution is done for the current input\. -. -.SH "TTY MODE" -If \fBstdin\fR, \fBstdout\fR, and \fBstderr\fR are all connected to a TTY, dc(1) turns on "TTY mode\." -. -.P -TTY mode is required for history to be enabled (see the COMMAND LINE HISTORY section)\. It is also required to enable special handling for \fBSIGINT\fR signals\. -. -.P -TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR, and interactive mode requires only \fBstdin\fR and \fBstdout\fR to be connected to a terminal\. -. -.SH "SIGNAL HANDLING" -Sending a \fBSIGINT\fR will cause dc(1) to stop execution of the current input\. If dc(1) is in TTY mode (see the TTY MODE section), it will reset (see the RESET section)\. Otherwise, it will clean up and exit\. -. -.P -Note that "current input" can mean one of two things\. If dc(1) is processing input from \fBstdin\fR in TTY mode, it will ask for more input\. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \fBstdin\fR if no other file exists\. -. -.P -This means that if a \fBSIGINT\fR is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file\. This is by design; most files that users execute when interacting with dc(1) have function definitions, which are quick to parse\. If a file takes a long time to execute, there may be a bug in that file\. The rest of the files could still be executed without problem, allowing the user to continue\. -. -.P -\fBSIGTERM\fR and \fBSIGQUIT\fR cause dc(1) to clean up and exit, and it uses the default handler for all other signals\. The one exception is \fBSIGHUP\fR, if dc(1) was built with history support; in that case, when dc(1) is in TTY mode, a \fBSIGHUP\fR will cause dc(1) to clean up and exit\. -. -.SH "COMMAND LINE HISTORY" -dc(1) supports interactive command\-line editing, if compiled with the history option enabled\. If dc(1) is in TTY mode (see the TTY MODE section), history is enabled\. Previous lines can be recalled and edited with the arrow keys\. -. -.P -\fBNote\fR: when dc(1) is built with history support, tabs are converted to 8 spaces\. -. -.SH "LOCALES" -This dc(1) ships with support for adding error messages for different locales\. -. -.SH "SEE ALSO" -bc(1) -. -.SH "STANDARDS" -The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003\.1\-2017 (“POSIX\.1\-2017â€) \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR specification\. -. -.SH "AUTHOR" -This dc(1) was made from scratch by Gavin D\. Howard\. -. -.SH "BUGS" -None are known\. Report bugs at https://git\.yzena\.com/gavin/bc\. diff --git a/manuals/dc.1.md.in b/manuals/dc.1.md.in new file mode 100644 index 000000000000..b6d252a2276e --- /dev/null +++ b/manuals/dc.1.md.in @@ -0,0 +1,1257 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +{{ A E H N EH EN HN EHN }} +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. +{{ end }} +{{ P EP HP NP EHP ENP HNP EHNP }} +: This option is a no-op. +{{ end }} + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +{{ A H N P HN HP NP HNP }} +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +value for **obase** is **2**. Values are output in the specified base. +{{ end }} + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +{{ A H N P HN HP NP HNP }} +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. +{{ end }} + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +{{ A H N P HN HP NP HNP }} +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. +{{ end }} + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +{{ A H N P HN HP NP HNP }} +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. +{{ end }} + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +{{ A H N P HN HP NP HNP }} +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. +{{ end }} + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +{{ A H N P HN HP NP HNP }} +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. +{{ end }} + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +{{ A H N P HN HP NP HNP }} +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. +{{ end }} + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, +{{ A H N P HN HP NP HNP }} + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). +{{ end }} + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +{{ A H N P HN HP NP HNP }} +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. +{{ end }} + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +{{ A H N P HN HP NP HNP }} +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. +{{ end }} + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +{{ A H N P HN HP NP HNP }} +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. +{{ end }} + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +{{ A H N P HN HP NP HNP }} +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. +{{ end }} + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative +{{ A H N P HN HP NP HNP }} + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. +{{ end }} +{{ E EH EN EP EHN EHP ENP EHNP }} + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. +{{ end }} + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +{{ A E N P EN EP NP ENP }} +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. +{{ end }} + +{{ A E H N EH EN HN EHN }} +The prompt is enabled in TTY mode. +{{ end }} + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +{{ A E N P EN EP NP ENP }} +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. +{{ end }} +{{ H EH HN HP EHN EHP HNP EHNP }} +default handler for all other signals. +{{ end }} + +{{ A E N P EN EP NP ENP }} +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. +{{ end }} + +{{ A E H P EH EP HP EHP }} +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. +{{ end }} + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc.1.ronn b/manuals/dc.1.ronn deleted file mode 100644 index 924ac805820d..000000000000 --- a/manuals/dc.1.ronn +++ /dev/null @@ -1,1103 +0,0 @@ -dc(1) -- arbitrary-precision reverse-Polish notation calculator -=============================================================== - -SYNOPSIS --------- - -`dc` [`-hiPvVx`] [`--version`] [`--help`] [`--interactive`] [`--no-prompt`] -[`--extended-register`] [`-e` *expr*] [`--expression=`*expr*...] -[`-f` *file*...] [`-file=`*file*...] [*file*...] - -DESCRIPTION ------------ - -dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish -notation) to store numbers and results of computations. Arithmetic operations -pop arguments off of the stack and push the results. - -If no files are given on the command-line as extra arguments (i.e., not as `-f` -or `--file` arguments), then dc(1) reads from `stdin`. Otherwise, those files -are processed, and dc(1) will then exit. - -This is different from the dc(1) on OpenBSD and possibly other dc(1) -implementations, where `-e` (`--expression`) and `-f` (`--file`) arguments cause -dc(1) to execute them and exit. The reason for this is that this dc(1) allows -users to set arguments in the environment variable `DC_ENV_ARGS` (see the -ENVIRONMENT VARIABLES section). Any expressions given on the command-line should -be used to set up a standard environment. For example, if a user wants the -`scale` always set to `10`, they can set `DC_ENV_ARGS` to "-e 10k", and this -dc(1) will always start with a `scale` of `10`. - -If users want to have dc(1) exit after processing all input from `-e` and `-f` -arguments (and their equivalents), then they can just simply add "-e q" as the -last command-line argument or define the environment variable `DC_EXPR_EXIT`. - -OPTIONS -------- - -The following are the options that dc(1) accepts. - - * `-h`, `--help`: - Prints a usage message and quits. - - * `-v`, `-V`, `--version`: - Print the version information (copyright header) and exit. - - * `-i`, `--interactive`: - Forces interactive mode. (See the INTERACTIVE MODE section.) - - This is a **non-portable extension**. - - * `-P`, `--no-prompt`: - Disables the prompt in interactive mode. This is mostly for those users that - do not want a prompt or are not used to having them in `dc`. Most of those - users would want to put this option in `DC_ENV_ARGS`. - - If the prompt has been disabled while building dc(1), this option is a - no-op. - - This is a **non-portable extension**. - - * `-x` `--extended-register`: - Enables extended register mode. See the REGISTERS section for more - information. - - 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. - - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - `DC_EXPR_EXIT` is defined (see the ENVIRONMENT VARIABLES section). - - This is a **non-portable extension**. - - * `-f` *file*, `--file`=*file*: - Reads in `file` and evaluates it. If expressions are also given (see above), - the expressions are evaluated in the order given. - - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - `DC_EXPR_EXIT` is defined (see the ENVIRONMENT VARIABLES section). - - This is a **non-portable extension**. - -**Note**: long options are only accepted if dc(1) is built with them enabled. - -STDOUT ------- - -Any non-error output is written to `stdout`. - -**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal -error (see the EXIT STATUS section) if it cannot write to `stdout`, so if -`stdout` is closed, as in `dc >&-`, it will quit with an error. This is -done so that dc(1) can report problems when `stdout` is redirected to a file. - -If there are scripts that depend on the behavior of other dc(1) implementations, -it is recommended that those scripts be changed to redirect `stdout` to -`/dev/null`. - -STDERR ------- - -Any error output is written to `stderr`. - -**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal -error (see the EXIT STATUS section) if it cannot write to `stderr`, so if -`stderr` is closed, as in `dc 2>&-`, it will quit with an error. This is -done so that dc(1) can report problems when `stderr` is redirected to a file. - -If there are scripts that depend on the behavior of other dc(1) implementations, -it is recommended that those scripts be changed to redirect `stderr` to -`/dev/null`. - -SYNTAX ------- - -`ibase` is a register (see the REGISTERS section) determining how to interpret -constant numbers. It is the "input" base, or the number base used for -interpreting input numbers. `ibase` is initially `10`. The max allowable value -for `ibase` is `16`. The min allowable value for `ibase` is `2`. The max -allowable value for `ibase` can be queried in dc(1) programs with the `T` -command. - -`obase` is a register (see the REGISTERS section) determining how to output -results. It is the "output" base, or the number base used for outputting -numbers. `obase` is initially `10`. The max allowable value for `obase` is -`DC_BASE_MAX`. The min allowable value for `obase` is `2` unless dc(1) was built -with the extra math option. If it was, then the min allowable value is `0`. In -this case, if `obase` is `0`, values are output in scientific notation, and if -`obase` is `1`, values are output in engineering notation. (Outputting in -scientific or engineering notation are **non-portable extensions**.) The max -allowable value for `obase` can be queried in dc(1) programs with the `U` -command. - -The **scale** of an expression is the number of digits in the result of the -expression right of the decimal point, and `scale` is a register (see the -REGISTERS section) that sets the precision of any operations (with exceptions). -`scale` is initially `0`. `scale` cannot be negative. The max allowable value -for `scale` can be queried in dc(1) programs with the `V` command. - -Each item in the input source code, either a number (see the NUMBERS section) or -a command (see the COMMANDS section), is processed and executed, in order. Input -is processed immediately when entered. - -If dc(1) was built with the extra math option, there is an additional register -named `seed`. This is the current seed used by the pseudo-random number -generator. If the current value of `seed` is queried and stored, then if it is -assigned to `seed` later, the pseudo-random number generator is guaranteed to -produce the same sequence of pseudo-random numbers that were generated after the -value of `seed` was first queried. - -Multiple values assigned to `seed` can produce the same sequence of -pseudo-random numbers. Likewise, when a value is assigned to `seed`, it is not -guaranteed that querying `seed` immediately after will return the same value. -In addition, the value of `seed` will change after any call to the `'` or `"` -commands. The maximum integer returned by the `'` command can be queried with -the `W` command. - -**Note**: The values returned by the pseudo-random number generator with the -`'` and `"` commands are guaranteed to **NOT** be cryptographically-secure. -This is a consequence of using a seeded pseudo-random number generator. However, -they **are** guaranteed to be reproducible with identical `seed` values. - -The pseudo-random number generator, `seed`, and all associated operations are -**non-portable extensions**. - -### Comments - -Comments go from `#` until, and not including, the next newline. This is a -**non-portable extension**. - -NUMBERS -------- - -Numbers are strings made up of digits, uppercase letters up to `F`, and at most -`1` period for a radix. Numbers can have up to `DC_NUM_MAX` digits. Uppercase -letters equal `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`) take the value that they would have if they -were valid digits, regardless of the value of `ibase`. This means that `A` -always equals decimal `10` and `F` always equals decimal `15`. - -In addition, if dc(1) was built with the extra math option, it accepts numbers -in scientific notation. For dc(1), an example is `1.89237e9`, which is equal to -`1892370000`. Negative exponents are also allowed, so `4.2890e_3` is equal to -`0.0042890`. - -**WARNING**: Both the number and the exponent in scientific notation are -interpreted according to the current `ibase`, but the number is still multiplied -by `10^exponent` regardless of the current `ibase`. For example, if `ibase` is -`16` and dc(1) is given the number string `"FFeA"`, the resulting decimal number -will be `2550000000000`, and if dc(1) is given the number string `"10e_4"`, the -resulting decimal number will be `0.0016`. - -Accepting input as scientific notation is a **non-portable extension**. - -COMMANDS --------- - -The valid commands are listed below. - -### Printing - -These commands are used for printing. - -Note that if dc(1) has been built with the extra math option enabled, both -scientific notation and engineering notation are available for printing numbers. -Scientific notation is activated by assigning `0` to `obase` using `0o` (in any -other context, an `obase` of `0` is invalid), and engineering notation is -activated by assigning `1` to `obase` using `1o` (which is also invalid in any -other context). To deactivate them, just assign a different value to `obase`. - -Printing numbers in scientific notation and/or engineering notation is a -**non-portable extension**. - - * `p`: - Prints the value on top of the stack, whether number or string, and prints a - newline after. - - This does not alter the stack. - - * `n`: - Prints the value on top of the stack, whether number or string, and pops it - off of the stack. - - * `P`: - Pops a value off the stack. - - If the value is a number, it is truncated and the absolute value of the - result is printed as though `obase` is `UCHAR_MAX + 1` and each digit is - interpreted as an ASCII character, making it a byte stream. - - If the value is a string, it is printed without a trailing newline. - - This is a **non-portable extension**. - - * `f`: - Prints the entire contents of the stack, in order from newest to oldest, - without altering anything. - - Users should use this command when they get lost. - -### Arithmetic - -These are the commands used for arithmetic. - - * `+`: - The top two values are popped off the stack, added, and the result is pushed - onto the stack. The **scale** of the result is equal to the max **scale** of - both operands. - - * `-`: - The top two values are popped off the stack, subtracted, and the result is - pushed onto the stack. The **scale** of the result is equal to the max - **scale** of both operands. - - * `*`: - The top two values are popped off the stack, multiplied, and the result is - pushed onto the stack. If `a` is the **scale** of the first expression and - `b` is the **scale** of the second expression, the **scale** of the result - is equal to `min(a+b,max(scale,a,b))` where `min` and `max` return the - obvious values. - - * `/`: - The top two values are popped off the stack, divided, and the result is - pushed onto the stack. The **scale** of the result is equal to `scale`. - - The first value popped off of the stack must be non-zero. - - * `%`: - The top two values are popped off the stack, remaindered, and the result is - pushed onto the stack. - - Remaindering is equivalent to 1) Computing `a/b` to current `scale`, and 2) - Using the result of step 1 to calculate `a-(a/b)*b` to **scale** - `max(scale + scale(b), scale(a))`. - - The first value popped off of the stack must be non-zero. - - * `~`: - The top two values are popped off the stack, divided and remaindered, and - the results (divided first, remainder second) are pushed onto the stack. - This is equivalent to `x y / x y %` except that `x` and `y` are only - evaluated once. - - The first value popped off of the stack must be non-zero. - - This is a **non-portable extension**. - - * `^`: - The top two values are popped off the stack, the second is raised to the - power of the first, and the result is pushed onto the stack. - - The first value popped off of the stack must be an integer, and if that - value is negative, the second value popped off of the stack must be - non-zero. - - * `v`: - The top value is popped off the stack, its square root is computed, and the - result is pushed onto the stack. The **scale** of the result is equal to - `scale`. - - The value popped off of the stack must be non-negative. - - * `_`: - If this command *immediately* precedes a number (i.e., no spaces or other - commands), then that number is input as a negative number. - - Otherwise, the top value on the stack is popped and copied, and the copy is - negated and pushed onto the stack. This behavior without a number is a - **non-portable extension**. - - * `b`: - The top value is popped off the stack, and if it is zero, it is pushed back - onto the stack. Otherwise, its absolute value is pushed onto the stack. - - This is a **non-portable extension**. - - * `|`: - The top three values are popped off the stack, a modular exponentiation is - computed, and the result is pushed onto the stack. - - The first value popped is used as the reduction modulus and must be an - integer and non-zero. The second value popped is used as the exponent and - must be an integer and non-negative. The third value popped is the base and - must be an integer. - - This is a **non-portable extension**. - - * `$`: - The top value is popped off the stack and copied, and the copy is truncated - and pushed onto the stack. - - This is a **non-portable extension**. - - * `@`: - The top two values are popped off the stack, and the precision of the second - is set to the value of the first, whether by truncation or extension. - - The first value popped off of the stack must be an integer and non-negative. - - This is a **non-portable extension**. - - * `H`: - The top two values are popped off the stack, and the second is shifted left - (radix shifted right) to the value of the first. - - The first value popped off of the stack must be an integer and non-negative. - - This is a **non-portable extension**. - - * `h`: - The top two values are popped off the stack, and the second is shifted right - (radix shifted left) to the value of the first. - - The first value popped off of the stack must be an integer and non-negative. - - This is a **non-portable extension**. - - * `G`: - The top two values are popped off of the stack, they are compared, and a `1` - is pushed if they are equal, or `0` otherwise. - - This is a **non-portable extension**. - - * `N`: - The top value is popped off of the stack, and if it a `0`, a `1` is pushed; - otherwise, a `0` is pushed. - - This is a **non-portable extension**. - - * `(`: - The top two values are popped off of the stack, they are compared, and a `1` - is pushed if the first is less than the second, or `0` otherwise. - - This is a **non-portable extension**. - - * `{`: - The top two values are popped off of the stack, they are compared, and a `1` - is pushed if the first is less than or equal to the second, or `0` - otherwise. - - This is a **non-portable extension**. - - * `)`: - The top two values are popped off of the stack, they are compared, and a `1` - is pushed if the first is greater than the second, or `0` otherwise. - - This is a **non-portable extension**. - - * `}`: - The top two values are popped off of the stack, they are compared, and a `1` - is pushed if the first is greater than or equal to the second, or `0` - otherwise. - - This is a **non-portable extension**. - - * `M`: - The top two values are popped off of the stack. If they are both non-zero, a - `1` is pushed onto the stack. If either of them is zero, or both of them - are, then a `0` is pushed onto the stack. - - This is like the `&&` operator in bc(1), and it is not a short-circuit - operator. - - This is a **non-portable extension**. - - * `m`: - The top two values are popped off of the stack. If at least one of them is - non-zero, a `1` is pushed onto the stack. If both of them are zero, then a - `0` is pushed onto the stack. - - This is like the `||` operator in bc(1), and it is not a short-circuit - operator. - - This is a **non-portable extension**. - -### Pseudo-Random Number Generator - -If dc(1) was built with the extra math option, it has a built-in pseudo-random -number generator. These commands query the pseudo-random number generator. (See -Parameters for more information about the `seed` value that controls the -pseudo-random number generator.) - -The pseudo-random number generator is guaranteed to **NOT** be -cryptographically-secure. - - * `'`: - Generates an integer between 0 and `DC_RAND_MAX`, inclusive (see the LIMITS - section). - - The generated integer is made as unbiased as possible, subject to the - limitations of the pseudo-random number generator. - - This command is only available if dc(1) was built with the extra math - option. - - This is a **non-portable extension**. - - * `"`: - Pops a value off of the stack, which is used as an **exclusive** upper bound - on the integer that will be generated. If the bound is negative or is a - non-integer, an error is raised, and dc(1) resets (see the RESET section). - If the bound is larger than `DC_RAND_MAX`, the higher bound is honored by - generating several pseudo-random integers, multiplying them by appropriate - powers of `DC_RAND_MAX + 1`, and adding them together. Thus, the size of - integer that can be generated with this command is unbounded. Using this - command will change the value of `seed`. - - If the operand is `0` or `1`, then the result pushed onto the stack is `0`, - and `seed` is not changed. - - The generated integer is made as unbiased as possible, subject to the - limitations of the pseudo-random number generator. - - This command is only available if dc(1) was built with the extra math - option. - - This is a **non-portable extension**. - -### Stack Control - -These commands control the stack. - - * `c`: - Removes all items from ("clears") the stack. - - * `d`: - Copies the item on top of the stack ("duplicates") and pushes the copy onto - the stack. - - * `r`: - Swaps ("reverses") the two top items on the stack. - - * `R`: - Pops ("removes") the top value from the stack. - -### Register Control - -These commands control registers (see the REGISTERS section). - - * `s`*r*: - Pops the value off the top of the stack and stores it into register `r`. - - * `l`*r*: - Copies the value in register `r` and pushes it onto the stack. This does not - alter the contents of `r`. - - * `S`*r*: - Pops the value off the top of the (main) stack and pushes it onto the stack - of register `r`. The previous value of the register becomes inaccessible. - - * `L`*r*: - Pops the value off the top of the stack for register `r` and push it onto - the main stack. The previous value in the stack for register `r`, if any, is - now accessible via the `l`*r* command. - -### Parameters - -These commands control the values of `ibase`, `obase`, `scale`, and `seed` (if -dc(1) was built with the extra math option). Also see the SYNTAX section. - - * `i`: - Pops the value off of the top of the stack and uses it to set `ibase`, which - must be between `2` and `16`, inclusive. - - If the value on top of the stack has any **scale**, the **scale** is - ignored. - - * `o`: - Pops the value off of the top of the stack and uses it to set `obase`, which - must be between `2` and `DC_BASE_MAX`, inclusive (see bc(1)). The value can - be either `0` or `1` if dc(1) was built with the extra math option. - - If the value on top of the stack has any **scale**, the **scale** is - ignored. - - * `k`: - Pops the value off of the top of the stack and uses it to set `scale`, which - must be non-negative. - - If the value on top of the stack has any **scale**, the **scale** is - ignored. - - * `j`: - Pops the value off of the top of the stack and uses it to set `seed`. The - meaning of `seed` is dependent on the current pseudo-random number - generator but is guaranteed to not change except for new major versions. - - The **scale** of the value may be significant. - - If a previously used `seed` value is used again, the pseudo-random number - generator is guaranteed to produce the same sequence of pseudo-random - numbers as it did when the `seed` value was previously used. - - The exact value assigned to `seed` is not guaranteed to be returned if the - `J` command is used. However, if `seed` *does* return a different value, - both values, when assigned to `seed`, are guaranteed to produce the same - sequence of pseudo-random numbers. This means that certain values assigned - to `seed` will not produce unique sequences of pseudo-random numbers. - - There is no limit to the length (number of significant decimal digits) or - *scale* of the value that can be assigned to `seed`. - - This command is only available if dc(1) was built with the extra math - option. - - This is a **non-portable extension**. - - * `I`: - Pushes the current value of `ibase` onto the main stack. - - * `O`: - Pushes the current value of `obase` onto the main stack. - - * `K`: - Pushes the current value of `scale` onto the main stack. - - * `J`: - Pushes the current value of `seed` onto the main stack. - - This command is only available if dc(1) was built with the extra math - option. - - This is a **non-portable extension**. - - * `T`: - Pushes the maximum allowable value of `ibase` onto the main stack. - - This is a **non-portable extension**. - - * `U`: - Pushes the maximum allowable value of `obase` onto the main stack. - - This is a **non-portable extension**. - - * `V`: - Pushes the maximum allowable value of `scale` onto the main stack. - - This is a **non-portable extension**. - - * `W`: - Pushes the maximum (inclusive) integer that can be generated with the `'` - pseudo-random number generator command. - - This command is only available if dc(1) was built with the extra math - option. - - This is a **non-portable extension**. - -### Strings - -The following commands control strings. - -dc(1) can work with both numbers and strings, and registers (see the REGISTERS -section) can hold both strings and numbers. dc(1) always knows whether the -contents of a register are a string or a number. - -While arithmetic operations have to have numbers, and will print an error if -given a string, other commands accept strings. - -Strings can also be executed as macros. For example, if the string `[1pR]` is -executed as a macro, then the code `1pR` is executed, meaning that the `1` will -be printed with a newline after and then popped from the stack. - - * `[`*characters*`]`: - Makes a string containing *characters* and pushes it onto the stack. - - If there are brackets (`[` and `]`) in the string, then they must be - balanced. Unbalanced brackets can be escaped using a backslash (`\`) - character. - - If there is a backslash character in the string, the character after it - (even another backslash) is put into the string verbatim, but the (first) - backslash is not. - - * `a`: - The value on top of the stack is popped. - - If it is a number, it is truncated and its absolute value is taken. The - result mod `UCHAR_MAX + 1` is calculated. If that result is `0`, push an - empty string; otherwise, push a one-character string where the character is - the result of the mod interpreted as an ASCII character. - - If it is a string, then a new string is made. If the original string is - empty, the new string is empty. If it is not, then the first character of - the original string is used to create the new string as a one-character - string. The new string is then pushed onto the stack. - - This is a **non-portable extension**. - - * `x`: - Pops a value off of the top of the stack. - - If it is a number, it is pushed onto the stack. - - If it is a string, it is executed as a macro. - - This behavior is the norm whenever a macro is executed, whether by this - command or by the conditional execution commands below. - - * `>`*r*: - Pops two values off of the stack that must be numbers and compares them. If - the first value is greater than the second, then the contents of register - `r` are executed. - - For example, `0 1>a` will execute the contents of register `a`, and `1 0>a` - will not. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - * `>`*r*`e`*s*: - Like the above, but will execute register `s` if the comparison fails. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - This is a **non-portable extension**. - - * `!>`*r*: - Pops two values off of the stack that must be numbers and compares them. If - the first value is not greater than the second (less than or equal to), then - the contents of register `r` are executed. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - * `!>`*r*`e`*s*: - Like the above, but will execute register `s` if the comparison fails. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - This is a **non-portable extension**. - - * `<`*r*: - Pops two values off of the stack that must be numbers and compares them. If - the first value is less than the second, then the contents of register `r` - are executed. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - * `<`*r*`e`*s*: - Like the above, but will execute register `s` if the comparison fails. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - This is a **non-portable extension**. - - * `!<`*r*: - Pops two values off of the stack that must be numbers and compares them. If - the first value is not less than the second (greater than or equal to), then - the contents of register `r` are executed. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - * `!<`*r*`e`*s*: - Like the above, but will execute register `s` if the comparison fails. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - This is a **non-portable extension**. - - * `=`*r*: - Pops two values off of the stack that must be numbers and compares them. If - the first value is equal to the second, then the contents of register `r` - are executed. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - * `=`*r*`e`*s*: - Like the above, but will execute register `s` if the comparison fails. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - This is a **non-portable extension**. - - * `!=`*r*: - Pops two values off of the stack that must be numbers and compares them. If - the first value is not equal to the second, then the contents of register - `r` are executed. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - * `!=`*r*`e`*s*: - Like the above, but will execute register `s` if the comparison fails. - - If either or both of the values are not numbers, dc(1) will raise an error - and reset (see the RESET section). - - This is a **non-portable extension**. - - * `?`: - Reads a line from the `stdin` and executes it. This is to allow macros to - request input from users. - - * `q`: - During execution of a macro, this exits the execution of that macro and the - execution of the macro that executed it. If there are no macros, or only one - macro executing, dc(1) exits. - - * `Q`: - Pops a value from the stack which must be non-negative and is used the - number of macro executions to pop off of the execution stack. If the number - of levels to pop is greater than the number of executing macros, dc(1) - exits. - -### Status - -These commands query status of the stack or its top value. - - * `Z`: - Pops a value off of the stack. - - If it is a number, calculates the number of significant decimal digits it - has and pushes the result. - - If it is a string, pushes the number of characters the string has. - - * `X`: - Pops a value off of the stack. - - If it is a number, pushes the **scale** of the value onto the stack. - - If it is a string, pushes `0`. - - * `z`: - Pushes the current stack depth (before execution of this command). - -### Arrays - -These commands manipulate arrays. - - * `:`*r*: - Pops the top two values off of the stack. The second value will be stored in - the array `r` (see the REGISTERS section), indexed by the first value. - - * `;`*r*: - Pops the value on top of the stack and uses it as an index into the array - `r`. The selected value is then pushed onto the stack. - -REGISTERS ---------- - -Registers are names that can store strings, numbers, and arrays. (Number/string -registers do not interfere with array registers.) - -Each register is also its own stack, so the current register value is the top of -the stack for the register. All registers, when first referenced, have one value -(`0`) in their stack. - -In non-extended register mode, a register name is just the single character that -follows any command that needs a register name. The only exception is a newline -(`'\n'`); it is a parse error for a newline to be used as a register name. - -### Extended Register Mode - -Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited -amounts of registers, if extended register mode is enabled. - -If extended register mode is enabled (`-x` or `--extended-register` command-line -arguments are given), then normal single character registers are used -***unless*** the character immediately following a command that needs a register -name is a space (according to `isspace()`) and not a newline (`'\n'`). - -In that case, the register name is found according to the regex -`[a-z][a-z0-9_]*` (like bc(1)), and it is a parse error if the next -non-space characters do not match that regex. - -RESET ------ - -When dc(1) encounters an error or a signal that it has a non-default handler -for, it resets. This means that several things happen. - -First, any macros that are executing are stopped and popped off the stack. -The behavior is not unlike that of exceptions in programming languages. Then -the execution point is set so that any code waiting to execute (after all -functions returned) is skipped. - -Thus, when dc(1) resets, it skips any remaining code waiting to be executed. -Then, if it is interactive mode, and the error was not a fatal error (see the -EXIT STATUS section), it asks for more input; otherwise, it exits with the -appropriate return code. - -PERFORMANCE ------------ - -Most dc(1) implementations use `char` types to calculate the value of `1` -decimal digit at a time, but that can be slow. This dc(1) does something -different. - -It uses large integers to calculate more than `1` decimal digit at a time. If -built in a environment where `DC_LONG_BIT` (see the LIMITS section) is `64`, -then each integer has `9` decimal digits. If built in an environment where -`DC_LONG_BIT` is `32` then each integer has `4` decimal digits. This value (the -number of decimal digits per large integer) is called `DC_BASE_DIGS`. - -In addition, this dc(1) uses an even larger integer for overflow checking. This -integer type depends on the value of `DC_LONG_BIT`, but is always at least twice -as large as the integer type used to store digits. - -LIMITS ------- - -The following are the limits on dc(1): - - * `DC_LONG_BIT`: - The number of bits in the `long` type in the environment where dc(1) was - built. This determines how many decimal digits can be stored in a single - large integer (see the PERFORMANCE section). - - * `DC_BASE_DIGS`: - The number of decimal digits per large integer (see the PERFORMANCE - section). Depends on `DC_LONG_BIT`. - - * `DC_BASE_POW`: - The max decimal number that each large integer can store (see - `DC_BASE_DIGS`) plus `1`. Depends on `DC_BASE_DIGS`. - - * `DC_OVERFLOW_MAX`: - The max number that the overflow type (see the PERFORMANCE section) can - hold. Depends on `DC_LONG_BIT`. - - * `DC_BASE_DIGS`: - The number of decimal digits per large integer (see the PERFORMANCE - section). - - * `DC_BASE_MAX`: - The maximum output base. Set at `DC_BASE_POW`. - - * `DC_DIM_MAX`: - The maximum size of arrays. Set at `SIZE_MAX-1`. - - * `DC_SCALE_MAX`: - The maximum `scale`. Set at `DC_OVERFLOW_MAX-1`. - - * `DC_STRING_MAX`: - The maximum length of strings. Set at `DC_OVERFLOW_MAX-1`. - - * `DC_NAME_MAX`: - The maximum length of identifiers. Set at `DC_OVERFLOW_MAX-1`. - - * `DC_NUM_MAX`: - The maximum length of a number (in decimal digits), which includes digits - after the decimal point. Set at `DC_OVERFLOW_MAX-1`. - - * `DC_RAND_MAX`: - The maximum integer (inclusive) returned by the `'` command, if dc(1) has - been built with the extra math option. Set at `2^DC_LONG_BIT-1`. - - * Exponent: - The maximum allowable exponent (positive or negative). Set at - `DC_OVERFLOW_MAX`. - - * Number of vars: - The maximum number of vars/arrays. Set at `SIZE_MAX-1`. - -These limits are meant to be effectively non-existent; the limits are so large -(at least on 64-bit machines) that there should not be any point at which they -become a problem. In fact, memory should be exhausted before these limits should -be hit. - -ENVIRONMENT VARIABLES ---------------------- - -dc(1) recognizes the following environment variables: - - * `DC_ENV_ARGS`: - This is another way to give command-line arguments to dc(1). They should be - in the same format as all other command-line arguments. These are always - processed first, so any files given in `DC_ENV_ARGS` will be processed - before arguments and files given on the command-line. This gives the user - the ability to set up "standard" options and files to be used at every - invocation. The most useful thing for such files to contain would be useful - functions that the user might want every time dc(1) runs. Another use would - be to use the `-e` option to set `scale` to a value other than `0`. - - The code that parses `DC_ENV_ARGS` will correctly handle quoted arguments, - but it does not understand escape sequences. For example, the string - `"/home/gavin/some dc file.dc"` will be correctly parsed, but the string - `"/home/gavin/some \"dc\" file.dc"` will include the backslashes. - - The quote parsing will handle either kind of quotes, `'` or `"`. Thus, if - you have a file with any number of single quotes in the name, you can use - double quotes as the outside quotes, as in `"some 'bc' file.bc"`, and vice - versa if you have a file with double quotes. However, handling a file with - both kinds of quotes in `DC_ENV_ARGS` is not supported due to the complexity - of the parsing, though such files are still supported on the command-line - where the parsing is done by the shell. - - * `DC_LINE_LENGTH`: - If this environment variable exists and contains an integer that is greater - than `1` and is less than `UINT16_MAX` (`2^16-1`), dc(1) will output lines - to that length, including the backslash newline combo. The default line - length is `70`. - - * `DC_EXPR_EXIT`: - If this variable exists (no matter the contents), dc(1) will exit - immediately after executing expressions and files given by the `-e` and/or - `-f` command-line options (and any equivalents). - -EXIT STATUS ------------ - -dc(1) returns the following exit statuses: - - * `0`: - No error. - - * `1`: - A math error occurred. This follows standard practice of using `1` for - expected errors, since math errors will happen in the process of normal - execution. - - Math errors include divide by `0`, taking the square root of a negative - number, using a negative number as a bound for the pseudo-random number - generator, attempting to convert a negative number to a hardware integer, - overflow when converting a number to a hardware integer, and attempting to - use a non-integer where an integer is required. - - Converting to a hardware integer happens for the second operand of the power - (`^`), places (`@`), left shift (`H`), and right shift (`h`) operators. - - * `2`: - A parse error occurred. - - Parse errors include unexpected `EOF`, using an invalid character, failing - to find the end of a string or comment, and using a token where it is - invalid. - - * `3`: - A runtime error occurred. - - Runtime errors include assigning an invalid number to `ibase`, `obase`, or - `scale`; give a bad expression to a `read()` call, calling `read()` inside - of a `read()` call, type errors, and attempting an operation when the stack - has too few elements. - - * `4`: - A fatal error occurred. - - Fatal errors include memory allocation errors, I/O errors, failing to open - files, attempting to use files that do not have only ASCII characters (dc(1) - only accepts ASCII characters), attempting to open a directory as a file, - and giving invalid command-line options. - -The exit status `4` is special; when a fatal error occurs, dc(1) always exits -and returns `4`, no matter what mode dc(1) is in. - -The other statuses will only be returned when dc(1) is not in interactive mode -(see the INTERACTIVE MODE section), since dc(1) resets its state (see the RESET -section) and accepts more input when one of those errors occurs in interactive -mode. This is also the case when interactive mode is forced by the `-i` flag or -`--interactive` option. - -These exit statuses allow dc(1) to be used in shell scripting with error -checking, and its normal behavior can be forced by using the `-i` flag or -`--interactive` option. - -INTERACTIVE MODE ----------------- - -Like bc(1), dc(1) has an interactive mode and a non-interactive mode. -Interactive mode is turned on automatically when both `stdin` and `stdout` are -hooked to a terminal, but the `-i` flag and `--interactive` option can turn it -on in other cases. - -In interactive mode, dc(1) attempts to recover from errors (see the RESET -section), and in normal execution, flushes `stdout` as soon as execution is done -for the current input. - -TTY MODE --------- - -If `stdin`, `stdout`, and `stderr` are all connected to a TTY, dc(1) turns on -"TTY mode." - -TTY mode is required for history to be enabled (see the COMMAND LINE HISTORY -section). It is also required to enable special handling for `SIGINT` signals. - -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. - -SIGNAL HANDLING ---------------- - -Sending a `SIGINT` will cause dc(1) to stop execution of the current input. If -dc(1) is in TTY mode (see the TTY MODE section), it will reset (see the RESET -section). Otherwise, it will clean up and exit. - -Note that "current input" can mean one of two things. If dc(1) is processing -input from `stdin` in TTY mode, it will ask for more input. If dc(1) is -processing input from a file in TTY mode, it will stop processing the file and -start processing the next file, if one exists, or ask for input from `stdin` if -no other file exists. - -This means that if a `SIGINT` is sent to dc(1) as it is executing a file, it can -seem as though dc(1) did not respond to the signal since it will immediately -start executing the next file. This is by design; most files that users execute -when interacting with dc(1) have function definitions, which are quick to parse. -If a file takes a long time to execute, there may be a bug in that file. The -rest of the files could still be executed without problem, allowing the user to -continue. - -`SIGTERM` and `SIGQUIT` cause dc(1) to clean up and exit, and it uses the -default handler for all other signals. The one exception is `SIGHUP`, if dc(1) -was built with history support; in that case, when dc(1) is in TTY mode, a -`SIGHUP` will cause dc(1) to clean up and exit. - -COMMAND LINE HISTORY --------------------- - -dc(1) supports interactive command-line editing, if compiled with the history -option enabled. If dc(1) is in TTY mode (see the TTY MODE section), history is -enabled. Previous lines can be recalled and edited with the arrow keys. - -**Note**: when dc(1) is built with history support, tabs are converted to 8 -spaces. - -LOCALES -------- - -This dc(1) ships with support for adding error messages for different locales. - -SEE ALSO --------- - -bc(1) - -STANDARDS ---------- - -The dc(1) utility operators are compliant with the operators in the bc(1) -[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. - -AUTHOR ------- - -This dc(1) was made from scratch by Gavin D. Howard. - -BUGS ----- - -None are known. Report bugs at https://git.yzena.com/gavin/bc. - -[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc.md b/manuals/dc.md deleted file mode 120000 index 2255e4cc6104..000000000000 --- a/manuals/dc.md +++ /dev/null @@ -1 +0,0 @@ -dc.1.ronn \ No newline at end of file diff --git a/manuals/dc/A.1 b/manuals/dc/A.1 new file mode 100644 index 000000000000..10627cb197ec --- /dev/null +++ b/manuals/dc/A.1 @@ -0,0 +1,1406 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/A.1.md b/manuals/dc/A.1.md new file mode 100644 index 000000000000..36b20862c57f --- /dev/null +++ b/manuals/dc/A.1.md @@ -0,0 +1,1194 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/E.1 b/manuals/dc/E.1 new file mode 100644 index 000000000000..7f11a33bb18a --- /dev/null +++ b/manuals/dc/E.1 @@ -0,0 +1,1202 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/E.1.md b/manuals/dc/E.1.md new file mode 100644 index 000000000000..028e61b42bcc --- /dev/null +++ b/manuals/dc/E.1.md @@ -0,0 +1,1030 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/EH.1 b/manuals/dc/EH.1 new file mode 100644 index 000000000000..d7efbd649a76 --- /dev/null +++ b/manuals/dc/EH.1 @@ -0,0 +1,1187 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/EH.1.md b/manuals/dc/EH.1.md new file mode 100644 index 000000000000..774ba6e32b3a --- /dev/null +++ b/manuals/dc/EH.1.md @@ -0,0 +1,1017 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/EHN.1 b/manuals/dc/EHN.1 new file mode 100644 index 000000000000..a77032398174 --- /dev/null +++ b/manuals/dc/EHN.1 @@ -0,0 +1,1183 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/EHN.1.md b/manuals/dc/EHN.1.md new file mode 100644 index 000000000000..b4845bf77d86 --- /dev/null +++ b/manuals/dc/EHN.1.md @@ -0,0 +1,1012 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/EHNP.1 b/manuals/dc/EHNP.1 new file mode 100644 index 000000000000..fb350b8ed2f9 --- /dev/null +++ b/manuals/dc/EHNP.1 @@ -0,0 +1,1176 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/EHNP.1.md b/manuals/dc/EHNP.1.md new file mode 100644 index 000000000000..71a24ac4e635 --- /dev/null +++ b/manuals/dc/EHNP.1.md @@ -0,0 +1,1007 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/EHP.1 b/manuals/dc/EHP.1 new file mode 100644 index 000000000000..2a47184695cb --- /dev/null +++ b/manuals/dc/EHP.1 @@ -0,0 +1,1180 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/EHP.1.md b/manuals/dc/EHP.1.md new file mode 100644 index 000000000000..5445e17e5811 --- /dev/null +++ b/manuals/dc/EHP.1.md @@ -0,0 +1,1012 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/EN.1 b/manuals/dc/EN.1 new file mode 100644 index 000000000000..cc6ec8baaefd --- /dev/null +++ b/manuals/dc/EN.1 @@ -0,0 +1,1198 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/EN.1.md b/manuals/dc/EN.1.md new file mode 100644 index 000000000000..114c4d1916b1 --- /dev/null +++ b/manuals/dc/EN.1.md @@ -0,0 +1,1025 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/ENP.1 b/manuals/dc/ENP.1 new file mode 100644 index 000000000000..01a49aff21ae --- /dev/null +++ b/manuals/dc/ENP.1 @@ -0,0 +1,1191 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/ENP.1.md b/manuals/dc/ENP.1.md new file mode 100644 index 000000000000..df9c398527c8 --- /dev/null +++ b/manuals/dc/ENP.1.md @@ -0,0 +1,1020 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/EP.1 b/manuals/dc/EP.1 new file mode 100644 index 000000000000..00d29fc3ff9c --- /dev/null +++ b/manuals/dc/EP.1 @@ -0,0 +1,1195 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. +Values are output in the specified base. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and +\f[B]scale\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]2\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], 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, and +attempting to use a non\-integer where an integer is required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]) operator. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/EP.1.md b/manuals/dc/EP.1.md new file mode 100644 index 000000000000..99bb462fb0a0 --- /dev/null +++ b/manuals/dc/EP.1.md @@ -0,0 +1,1025 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **2**. Values are output in the specified base. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, and **scale**. Also +see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **2** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**) operator. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/H.1 b/manuals/dc/H.1 new file mode 100644 index 000000000000..02825b898261 --- /dev/null +++ b/manuals/dc/H.1 @@ -0,0 +1,1391 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/H.1.md b/manuals/dc/H.1.md new file mode 100644 index 000000000000..ab3b13fbf758 --- /dev/null +++ b/manuals/dc/H.1.md @@ -0,0 +1,1181 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/HN.1 b/manuals/dc/HN.1 new file mode 100644 index 000000000000..cb97ca4cafb3 --- /dev/null +++ b/manuals/dc/HN.1 @@ -0,0 +1,1387 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/HN.1.md b/manuals/dc/HN.1.md new file mode 100644 index 000000000000..a4d3b9f6ca9e --- /dev/null +++ b/manuals/dc/HN.1.md @@ -0,0 +1,1176 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/HNP.1 b/manuals/dc/HNP.1 new file mode 100644 index 000000000000..fefaa2a56c9d --- /dev/null +++ b/manuals/dc/HNP.1 @@ -0,0 +1,1380 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/HNP.1.md b/manuals/dc/HNP.1.md new file mode 100644 index 000000000000..b97a4a118d89 --- /dev/null +++ b/manuals/dc/HNP.1.md @@ -0,0 +1,1171 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/HP.1 b/manuals/dc/HP.1 new file mode 100644 index 000000000000..45b0cc111be8 --- /dev/null +++ b/manuals/dc/HP.1 @@ -0,0 +1,1384 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/HP.1.md b/manuals/dc/HP.1.md new file mode 100644 index 000000000000..fb7569dab186 --- /dev/null +++ b/manuals/dc/HP.1.md @@ -0,0 +1,1176 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/N.1 b/manuals/dc/N.1 new file mode 100644 index 000000000000..a4fb86637c1f --- /dev/null +++ b/manuals/dc/N.1 @@ -0,0 +1,1402 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +Disables the prompt in TTY mode. +(The prompt is only enabled in TTY mode. +See the \f[B]TTY MODE\f[] 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[]. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.PP +The prompt is enabled in TTY mode. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/N.1.md b/manuals/dc/N.1.md new file mode 100644 index 000000000000..ac7e27b6e5a3 --- /dev/null +++ b/manuals/dc/N.1.md @@ -0,0 +1,1189 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. + See the **TTY MODE** section) This is mostly for those users that do not + want a prompt or are not used to having them in dc(1). Most of those users + would want to put this option in **DC_ENV_ARGS**. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +The prompt is enabled in TTY mode. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/NP.1 b/manuals/dc/NP.1 new file mode 100644 index 000000000000..9b0b407bb327 --- /dev/null +++ b/manuals/dc/NP.1 @@ -0,0 +1,1395 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/NP.1.md b/manuals/dc/NP.1.md new file mode 100644 index 000000000000..f521c3df205e --- /dev/null +++ b/manuals/dc/NP.1.md @@ -0,0 +1,1184 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/manuals/dc/P.1 b/manuals/dc/P.1 new file mode 100644 index 000000000000..4ba6c64322d9 --- /dev/null +++ b/manuals/dc/P.1 @@ -0,0 +1,1399 @@ +.\" +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions are met: +.\" +.\" * Redistributions of source code must retain the above copyright notice, +.\" this list of conditions and the following disclaimer. +.\" +.\" * Redistributions in binary form must reproduce the above copyright notice, +.\" this list of conditions and the following disclaimer in the documentation +.\" and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +.\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +.\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +.\" POSSIBILITY OF SUCH DAMAGE. +.\" +.TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" +.SH Name +.PP +dc \- arbitrary\-precision reverse\-Polish notation calculator +.SH SYNOPSIS +.PP +\f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] +[\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] +[\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] +[\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] +\f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] +.SH DESCRIPTION +.PP +dc(1) is an arbitrary\-precision calculator. +It uses a stack (reverse Polish notation) to store numbers and results +of computations. +Arithmetic operations pop arguments off of the stack and push the +results. +.PP +If no files are given on the command\-line as extra arguments (i.e., not +as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from +\f[B]stdin\f[]. +Otherwise, those files are processed, and dc(1) will then exit. +.PP +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and +\f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them +and exit. +The reason for this is that this dc(1) allows users to set arguments in +the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT +VARIABLES\f[] section). +Any expressions given on the command\-line should be used to set up a +standard environment. +For example, if a user wants the \f[B]scale\f[] always set to +\f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and +this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. +.PP +If users want to have dc(1) exit after processing all input from +\f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then +they can just simply add \f[B]\-e q\f[] as the last command\-line +argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. +.SH OPTIONS +.PP +The following are the options that dc(1) accepts. +.TP +.B \f[B]\-h\f[], \f[B]\-\-help\f[] +Prints a usage message and quits. +.RS +.RE +.TP +.B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] +Print the version information (copyright header) and exit. +.RS +.RE +.TP +.B \f[B]\-i\f[], \f[B]\-\-interactive\f[] +Forces interactive mode. +(See the \f[B]INTERACTIVE MODE\f[] section.) +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] +This option is a no\-op. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] +Enables extended register mode. +See the \f[I]Extended Register Mode\f[] subsection of the +\f[B]REGISTERS\f[] section for more information. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] +Evaluates \f[I]expr\f[]. +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 +In other dc(1) implementations, this option causes the program to +execute the expressions and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] +Reads in \f[I]file\f[] and evaluates it, line by line, as though it were +read through \f[B]stdin\f[]. +If expressions are also given (see above), the expressions are evaluated +in the order given. +.RS +.PP +In other dc(1) implementations, this option causes the program to +execute the files and then exit. +This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see +the \f[B]ENVIRONMENT VARIABLES\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.PP +All long options are \f[B]non\-portable extensions\f[]. +.SH STDOUT +.PP +Any non\-error output is written to \f[B]stdout\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc +>&\-\f[], it will quit with an error. +This is done so that dc(1) can report problems when \f[B]stdout\f[] is +redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. +.SH STDERR +.PP +Any error output is written to \f[B]stderr\f[]. +.PP +\f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue +a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write +to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc +2>&\-\f[], it will quit with an error. +This is done so that dc(1) can exit with an error code when +\f[B]stderr\f[] is redirected to a file. +.PP +If there are scripts that depend on the behavior of other dc(1) +implementations, it is recommended that those scripts be changed to +redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. +.SH SYNTAX +.PP +Each item in the input source code, either a number (see the +\f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] +section), is processed and executed, in order. +Input is processed immediately when entered. +.PP +\f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to interpret constant numbers. +It is the "input" base, or the number base used for interpreting input +numbers. +\f[B]ibase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. +The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. +The max allowable value for \f[B]ibase\f[] can be queried in dc(1) +programs with the \f[B]T\f[] command. +.PP +\f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that +determines how to output results. +It is the "output" base, or the number base used for outputting numbers. +\f[B]obase\f[] is initially \f[B]10\f[]. +The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and +can be queried with the \f[B]U\f[] command. +The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. +If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific +notation, and if \f[B]obase\f[] is \f[B]1\f[], 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[]. +.PP +The \f[I]scale\f[] of an expression is the number of digits in the +result of the expression right of the decimal point, and \f[B]scale\f[] +is a register (see the \f[B]REGISTERS\f[] section) that sets the +precision of any operations (with exceptions). +\f[B]scale\f[] is initially \f[B]0\f[]. +\f[B]scale\f[] cannot be negative. +The max allowable value for \f[B]scale\f[] can be queried in dc(1) +programs with the \f[B]V\f[] command. +.PP +\f[B]seed\f[] is a register containing the current seed for the +pseudo\-random number generator. +If the current value of \f[B]seed\f[] is queried and stored, then if it +is assigned to \f[B]seed\f[] 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[] was first queried. +.PP +Multiple values assigned to \f[B]seed\f[] can produce the same sequence +of pseudo\-random numbers. +Likewise, when a value is assigned to \f[B]seed\f[], it is not +guaranteed that querying \f[B]seed\f[] immediately after will return the +same value. +In addition, the value of \f[B]seed\f[] will change after any call to +the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get +receive a value of \f[B]0\f[] or \f[B]1\f[]. +The maximum integer returned by the \f[B]\[aq]\f[] command can be +queried with the \f[B]W\f[] command. +.PP +\f[B]Note\f[]: The values returned by the pseudo\-random number +generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed +to \f[B]NOT\f[] be cryptographically secure. +This is a consequence of using a seeded pseudo\-random number generator. +However, they \f[B]are\f[] guaranteed to be reproducible with identical +\f[B]seed\f[] values. +.PP +The pseudo\-random number generator, \f[B]seed\f[], and all associated +operations are \f[B]non\-portable extensions\f[]. +.SS Comments +.PP +Comments go from \f[B]#\f[] until, and not including, the next newline. +This is a \f[B]non\-portable extension\f[]. +.SH NUMBERS +.PP +Numbers are strings made up of digits, uppercase letters up to +\f[B]F\f[], and at most \f[B]1\f[] period for a radix. +Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. +Uppercase letters are equal to \f[B]9\f[] + their position in the +alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). +If a digit or letter makes no sense with the current value of +\f[B]ibase\f[], they are set to the value of the highest valid digit in +\f[B]ibase\f[]. +.PP +Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that +they would have if they were valid digits, regardless of the value of +\f[B]ibase\f[]. +This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and +\f[B]F\f[] alone always equals decimal \f[B]15\f[]. +.PP +In addition, dc(1) accepts numbers in scientific notation. +These have the form \f[B]e\f[]. +The power (the portion after the \f[B]e\f[]) must be an integer. +An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. +Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to +\f[B]0.0042890\f[]. +.PP +\f[B]WARNING\f[]: Both the number and the exponent in scientific +notation are interpreted according to the current \f[B]ibase\f[], but +the number is still multiplied by \f[B]10^exponent\f[] regardless of the +current \f[B]ibase\f[]. +For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the +number string \f[B]FFeA\f[], the resulting decimal number will be +\f[B]2550000000000\f[], and if dc(1) is given the number string +\f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. +.PP +Accepting input as scientific notation is a \f[B]non\-portable +extension\f[]. +.SH COMMANDS +.PP +The valid commands are listed below. +.SS Printing +.PP +These commands are used for printing. +.PP +Note that both scientific notation and engineering notation are +available for printing numbers. +Scientific notation is activated by assigning \f[B]0\f[] to +\f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated +by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. +To deactivate them, just assign a different value to \f[B]obase\f[]. +.PP +Printing numbers in scientific notation and/or engineering notation is a +\f[B]non\-portable extension\f[]. +.TP +.B \f[B]p\f[] +Prints the value on top of the stack, whether number or string, and +prints a newline after. +.RS +.PP +This does not alter the stack. +.RE +.TP +.B \f[B]n\f[] +Prints the value on top of the stack, whether number or string, and pops +it off of the stack. +.RS +.RE +.TP +.B \f[B]P\f[] +Pops a value off the stack. +.RS +.PP +If the value is a number, it is truncated and the absolute value of the +result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and +each digit is interpreted as an 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[]. +.RE +.TP +.B \f[B]f\f[] +Prints the entire contents of the stack, in order from newest to oldest, +without altering anything. +.RS +.PP +Users should use this command when they get lost. +.RE +.SS Arithmetic +.PP +These are the commands used for arithmetic. +.TP +.B \f[B]+\f[] +The top two values are popped off the stack, added, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]\-\f[] +The top two values are popped off the stack, subtracted, and the result +is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of +both operands. +.RS +.RE +.TP +.B \f[B]*\f[] +The top two values are popped off the stack, multiplied, and the result +is pushed onto the stack. +If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and +\f[B]b\f[] is the \f[I]scale\f[] of the second expression, the +\f[I]scale\f[] of the result is equal to +\f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] +return the obvious values. +.RS +.RE +.TP +.B \f[B]/\f[] +The top two values are popped off the stack, divided, and the result is +pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]%\f[] +The top two values are popped off the stack, remaindered, and the result +is pushed onto the stack. +.RS +.PP +Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current +\f[B]scale\f[], and 2) Using the result of step 1 to calculate +\f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] +\f[B]max(scale+scale(b),scale(a))\f[]. +.PP +The first value popped off of the stack must be non\-zero. +.RE +.TP +.B \f[B]~\f[] +The top two values are popped off the stack, divided and remaindered, +and the results (divided first, remainder second) are pushed onto the +stack. +This is equivalent to \f[B]x y / x y %\f[] except that \f[B]x\f[] and +\f[B]y\f[] are only evaluated once. +.RS +.PP +The first value popped off of the stack must be non\-zero. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]^\f[] +The top two values are popped off the stack, the second is raised to the +power of the first, and the result is pushed onto the stack. +.RS +.PP +The first value popped off of the stack must be an integer, and if that +value is negative, the second value popped off of the stack must be +non\-zero. +.RE +.TP +.B \f[B]v\f[] +The top value is popped off the stack, its square root is computed, and +the result is pushed onto the stack. +The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. +.RS +.PP +The value popped off of the stack must be non\-negative. +.RE +.TP +.B \f[B]_\f[] +If this command \f[I]immediately\f[] precedes a number (i.e., no spaces +or other commands), then that number is input as a negative number. +.RS +.PP +Otherwise, the top value on the stack is popped and copied, and the copy +is negated and pushed onto the stack. +This behavior without a number is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]b\f[] +The top value is popped off the stack, and if it is zero, it is pushed +back onto the stack. +Otherwise, its absolute value is pushed onto the stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]|\f[] +The top three values are popped off the stack, a modular exponentiation +is computed, and the result is pushed onto the stack. +.RS +.PP +The first value popped is used as the reduction modulus and must be an +integer and non\-zero. +The second value popped is used as the exponent and must be an integer +and non\-negative. +The third value popped is the base and must be an integer. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]$\f[] +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[]. +.RE +.TP +.B \f[B]\@\f[] +The top two values are popped off the stack, and the precision of the +second is set to the value of the first, whether by truncation or +extension. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]H\f[] +The top two values are popped off the stack, and the second is shifted +left (radix shifted right) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]h\f[] +The top two values are popped off the stack, and the second is shifted +right (radix shifted left) to the value of the first. +.RS +.PP +The first value popped off of the stack must be an integer and +non\-negative. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]G\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]N\f[] +The top value is popped off of the stack, and if it a \f[B]0\f[], a +\f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B](\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] +otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]{\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is less than or equal to the second, +or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B])\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than the second, or +\f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]}\f[] +The top two values are popped off of the stack, they are compared, and a +\f[B]1\f[] is pushed if the first is greater than or equal to the +second, or \f[B]0\f[] otherwise. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]M\f[] +The top two values are popped off of the stack. +If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. +If either of them is zero, or both of them are, then a \f[B]0\f[] is +pushed onto the stack. +.RS +.PP +This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]m\f[] +The top two values are popped off of the stack. +If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the +stack. +If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. +.RS +.PP +This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a +short\-circuit operator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Pseudo\-Random Number Generator +.PP +dc(1) has a built\-in pseudo\-random number generator. +These commands query the pseudo\-random number generator. +(See Parameters for more information about the \f[B]seed\f[] value that +controls the pseudo\-random number generator.) +.PP +The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be +cryptographically secure. +.TP +.B \f[B]\[aq]\f[] +Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see +the \f[B]LIMITS\f[] section). +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]"\f[] +Pops a value off of the stack, which is used as an \f[B]exclusive\f[] +upper bound on the integer that will be generated. +If the bound is negative or is a non\-integer, an error is raised, and +dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] +remains unchanged. +If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is +honored by generating several pseudo\-random integers, multiplying them +by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them +together. +Thus, the size of integer that can be generated with this command is +unbounded. +Using this command will change the value of \f[B]seed\f[], unless the +operand is \f[B]0\f[] or \f[B]1\f[]. +In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is +\f[I]not\f[] changed. +.RS +.PP +The generated integer is made as unbiased as possible, subject to the +limitations of the pseudo\-random number generator. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Stack Control +.PP +These commands control the stack. +.TP +.B \f[B]c\f[] +Removes all items from ("clears") the stack. +.RS +.RE +.TP +.B \f[B]d\f[] +Copies the item on top of the stack ("duplicates") and pushes the copy +onto the stack. +.RS +.RE +.TP +.B \f[B]r\f[] +Swaps ("reverses") the two top items on the stack. +.RS +.RE +.TP +.B \f[B]R\f[] +Pops ("removes") the top value from the stack. +.RS +.RE +.SS Register Control +.PP +These commands control registers (see the \f[B]REGISTERS\f[] section). +.TP +.B \f[B]s\f[]\f[I]r\f[] +Pops the value off the top of the stack and stores it into register +\f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]l\f[]\f[I]r\f[] +Copies the value in register \f[I]r\f[] and pushes it onto the stack. +This does not alter the contents of \f[I]r\f[]. +.RS +.RE +.TP +.B \f[B]S\f[]\f[I]r\f[] +Pops the value off the top of the (main) stack and pushes it onto the +stack of register \f[I]r\f[]. +The previous value of the register becomes inaccessible. +.RS +.RE +.TP +.B \f[B]L\f[]\f[I]r\f[] +Pops the value off the top of the stack for register \f[I]r\f[] and push +it onto the main stack. +The previous value in the stack for register \f[I]r\f[], if any, is now +accessible via the \f[B]l\f[]\f[I]r\f[] command. +.RS +.RE +.SS Parameters +.PP +These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], +\f[B]scale\f[], and \f[B]seed\f[]. +Also see the \f[B]SYNTAX\f[] section. +.TP +.B \f[B]i\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], +inclusive. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]o\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]obase\f[], which must be between \f[B]0\f[] and +\f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the +\f[B]NUMBERS\f[] section). +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]k\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]scale\f[], which must be non\-negative. +.RS +.PP +If the value on top of the stack has any \f[I]scale\f[], the +\f[I]scale\f[] is ignored. +.RE +.TP +.B \f[B]j\f[] +Pops the value off of the top of the stack and uses it to set +\f[B]seed\f[]. +The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random +number generator but is guaranteed to not change except for new major +versions. +.RS +.PP +The \f[I]scale\f[] and sign of the value may be significant. +.PP +If a previously used \f[B]seed\f[] 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[] +value was previously used. +.PP +The exact value assigned to \f[B]seed\f[] is not guaranteed to be +returned if the \f[B]J\f[] command is used. +However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both +values, when assigned to \f[B]seed\f[], are guaranteed to produce the +same sequence of pseudo\-random numbers. +This means that certain values assigned to \f[B]seed\f[] will not +produce unique sequences of pseudo\-random numbers. +.PP +There is no limit to the length (number of significant decimal digits) +or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]I\f[] +Pushes the current value of \f[B]ibase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]O\f[] +Pushes the current value of \f[B]obase\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]K\f[] +Pushes the current value of \f[B]scale\f[] onto the main stack. +.RS +.RE +.TP +.B \f[B]J\f[] +Pushes the current value of \f[B]seed\f[] onto the main stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]T\f[] +Pushes the maximum allowable value of \f[B]ibase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]U\f[] +Pushes the maximum allowable value of \f[B]obase\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]V\f[] +Pushes the maximum allowable value of \f[B]scale\f[] onto the main +stack. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]W\f[] +Pushes the maximum (inclusive) integer that can be generated with the +\f[B]\[aq]\f[] pseudo\-random number generator command. +.RS +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.SS Strings +.PP +The following commands control strings. +.PP +dc(1) can work with both numbers and strings, and registers (see the +\f[B]REGISTERS\f[] section) can hold both strings and numbers. +dc(1) always knows whether the contents of a register are a string or a +number. +.PP +While arithmetic operations have to have numbers, and will print an +error if given a string, other commands accept strings. +.PP +Strings can also be executed as macros. +For example, if the string \f[B][1pR]\f[] is executed as a macro, then +the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be +printed with a newline after and then popped from the stack. +.TP +.B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] +Makes a string containing \f[I]characters\f[] and pushes it onto the +stack. +.RS +.PP +If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then +they must be balanced. +Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) +character. +.PP +If there is a backslash character in the string, the character after it +(even another backslash) is put into the string verbatim, but the +(first) backslash is not. +.RE +.TP +.B \f[B]a\f[] +The value on top of the stack is popped. +.RS +.PP +If it is a number, it is truncated and its absolute value is taken. +The result mod \f[B]UCHAR_MAX+1\f[] is calculated. +If that result is \f[B]0\f[], push an empty string; otherwise, push a +one\-character string where the character is the result of the mod +interpreted as an ASCII character. +.PP +If it is a string, then a new string is made. +If the original string is empty, the new string is empty. +If it is not, then the first character of the original string is used to +create the new string as a one\-character string. +The new string is then pushed onto the stack. +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]x\f[] +Pops a value off of the top of the stack. +.RS +.PP +If it is a number, it is pushed back onto the stack. +.PP +If it is a string, it is executed as a macro. +.PP +This behavior is the norm whenever a macro is executed, whether by this +command or by the conditional execution commands below. +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is greater than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +For example, \f[B]0 1>a\f[] will execute the contents of register +\f[B]a\f[], and \f[B]1 0>a\f[] will not. +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not greater than the second (less than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is less than the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not less than the second (greater than or equal +to), then the contents of register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is equal to the second, then the contents of register +\f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[] +Pops two values off of the stack that must be numbers and compares them. +If the first value is not equal to the second, then the contents of +register \f[I]r\f[] are executed. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.RE +.TP +.B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] +Like the above, but will execute register \f[I]s\f[] if the comparison +fails. +.RS +.PP +If either or both of the values are not numbers, dc(1) will raise an +error and reset (see the \f[B]RESET\f[] section). +.PP +This is a \f[B]non\-portable extension\f[]. +.RE +.TP +.B \f[B]?\f[] +Reads a line from the \f[B]stdin\f[] and executes it. +This is to allow macros to request input from users. +.RS +.RE +.TP +.B \f[B]q\f[] +During execution of a macro, this exits the execution of that macro and +the execution of the macro that executed it. +If there are no macros, or only one macro executing, dc(1) exits. +.RS +.RE +.TP +.B \f[B]Q\f[] +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. +.RS +.RE +.SS Status +.PP +These commands query status of the stack or its top value. +.TP +.B \f[B]Z\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, calculates the number of significant decimal digits +it has and pushes the result. +.PP +If it is a string, pushes the number of characters the string has. +.RE +.TP +.B \f[B]X\f[] +Pops a value off of the stack. +.RS +.PP +If it is a number, pushes the \f[I]scale\f[] of the value onto the +stack. +.PP +If it is a string, pushes \f[B]0\f[]. +.RE +.TP +.B \f[B]z\f[] +Pushes the current stack depth (before execution of this command). +.RS +.RE +.SS Arrays +.PP +These commands manipulate arrays. +.TP +.B \f[B]:\f[]\f[I]r\f[] +Pops the top two values off of the stack. +The second value will be stored in the array \f[I]r\f[] (see the +\f[B]REGISTERS\f[] section), indexed by the first value. +.RS +.RE +.TP +.B \f[B];\f[]\f[I]r\f[] +Pops the value on top of the stack and uses it as an index into the +array \f[I]r\f[]. +The selected value is then pushed onto the stack. +.RS +.RE +.SH REGISTERS +.PP +Registers are names that can store strings, numbers, and arrays. +(Number/string registers do not interfere with array registers.) +.PP +Each register is also its own stack, so the current register value is +the top of the stack for the register. +All registers, when first referenced, have one value (\f[B]0\f[]) in +their stack. +.PP +In non\-extended register mode, a register name is just the single +character that follows any command that needs a register name. +The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse +error for a newline 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[] or +\f[B]\-\-extended\-register\f[] command\-line arguments are given), then +normal single character registers are used \f[I]unless\f[] the character +immediately following a command that needs a register name is a space +(according to \f[B]isspace()\f[]) and not a newline +(\f[B]\[aq]\\n\[aq]\f[]). +.PP +In that case, the register name is found according to the regex +\f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse +error if the next non\-space characters do not match that regex. +.SH RESET +.PP +When dc(1) encounters an error or a signal that it has a non\-default +handler for, it resets. +This means that several things happen. +.PP +First, any macros that are executing are stopped and popped off the +stack. +The behavior is not unlike that of exceptions in programming languages. +Then the execution point is set so that any code waiting to execute +(after all macros returned) is skipped. +.PP +Thus, when dc(1) resets, it skips any remaining code waiting to be +executed. +Then, if it is interactive mode, and the error was not a fatal error +(see the \f[B]EXIT STATUS\f[] 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[] types to calculate the +value of \f[B]1\f[] decimal digit at a time, but that can be slow. +This dc(1) does something different. +.PP +It uses large integers to calculate more than \f[B]1\f[] decimal digit +at a time. +If built in a environment where \f[B]DC_LONG_BIT\f[] (see the +\f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has +\f[B]9\f[] decimal digits. +If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] +then each integer has \f[B]4\f[] decimal digits. +This value (the number of decimal digits per large integer) is called +\f[B]DC_BASE_DIGS\f[]. +.PP +In addition, this dc(1) uses an even larger integer for overflow +checking. +This integer type depends on the value of \f[B]DC_LONG_BIT\f[], 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 +.B \f[B]DC_LONG_BIT\f[] +The number of bits in the \f[B]long\f[] type in the environment where +dc(1) was built. +This determines how many decimal digits can be stored in a single large +integer (see the \f[B]PERFORMANCE\f[] section). +.RS +.RE +.TP +.B \f[B]DC_BASE_DIGS\f[] +The number of decimal digits per large integer (see the +\f[B]PERFORMANCE\f[] section). +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_POW\f[] +The max decimal number that each large integer can store (see +\f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. +Depends on \f[B]DC_BASE_DIGS\f[]. +.RS +.RE +.TP +.B \f[B]DC_OVERFLOW_MAX\f[] +The max number that the overflow type (see the \f[B]PERFORMANCE\f[] +section) can hold. +Depends on \f[B]DC_LONG_BIT\f[]. +.RS +.RE +.TP +.B \f[B]DC_BASE_MAX\f[] +The maximum output base. +Set at \f[B]DC_BASE_POW\f[]. +.RS +.RE +.TP +.B \f[B]DC_DIM_MAX\f[] +The maximum size of arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_SCALE_MAX\f[] +The maximum \f[B]scale\f[]. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_STRING_MAX\f[] +The maximum length of strings. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NAME_MAX\f[] +The maximum length of identifiers. +Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. +.RS +.RE +.TP +.B \f[B]DC_NUM_MAX\f[] +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[]. +.RS +.RE +.TP +.B \f[B]DC_RAND_MAX\f[] +The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, +if dc(1). +Set at \f[B]2^DC_LONG_BIT\-1\f[]. +.RS +.RE +.TP +.B Exponent +The maximum allowable exponent (positive or negative). +Set at \f[B]DC_OVERFLOW_MAX\f[]. +.RS +.RE +.TP +.B Number of vars +The maximum number of vars/arrays. +Set at \f[B]SIZE_MAX\-1\f[]. +.RS +.RE +.PP +These limits are meant to be effectively non\-existent; the limits are +so large (at least on 64\-bit machines) that there should not be any +point at which they become a problem. +In fact, memory should be exhausted before these limits should be hit. +.SH ENVIRONMENT VARIABLES +.PP +dc(1) recognizes the following environment variables: +.TP +.B \f[B]DC_ENV_ARGS\f[] +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[] will be processed before arguments and files given +on the command\-line. +This gives the user the ability to set up "standard" options and files +to be used at every invocation. +The most useful thing for such files to contain would be useful +functions that the user might want every time dc(1) runs. +Another use would be to use the \f[B]\-e\f[] option to set +\f[B]scale\f[] to a value other than \f[B]0\f[]. +.RS +.PP +The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted +arguments, but it does not understand escape sequences. +For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be +correctly parsed, but the string \f[B]"/home/gavin/some "dc" +file.dc"\f[] will include the backslashes. +.PP +The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or +\f[B]"\f[]. +Thus, if you have a file with any number of single quotes in the name, +you can use double quotes as the outside quotes, as in \f[B]"some +\[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double +quotes. +However, handling a file with both kinds of quotes in +\f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the +parsing, though such files are still supported on the command\-line +where the parsing is done by the shell. +.RE +.TP +.B \f[B]DC_LINE_LENGTH\f[] +If this environment variable exists and contains an integer that is +greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] +(\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including +the backslash newline combo. +The default line length is \f[B]70\f[]. +.RS +.RE +.TP +.B \f[B]DC_EXPR_EXIT\f[] +If this variable exists (no matter the contents), dc(1) will exit +immediately after executing expressions and files given by the +\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any +equivalents). +.RS +.RE +.SH EXIT STATUS +.PP +dc(1) returns the following exit statuses: +.TP +.B \f[B]0\f[] +No error. +.RS +.RE +.TP +.B \f[B]1\f[] +A math error occurred. +This follows standard practice of using \f[B]1\f[] for expected errors, +since math errors will happen in the process of normal execution. +.RS +.PP +Math errors include divide by \f[B]0\f[], taking the square root of a +negative number, using a negative number as a bound for the +pseudo\-random number generator, attempting to convert a negative number +to a hardware integer, overflow when converting a number to a hardware +integer, and attempting to use a non\-integer where an integer is +required. +.PP +Converting to a hardware integer happens for the second operand of the +power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and +right shift (\f[B]h\f[]) operators. +.RE +.TP +.B \f[B]2\f[] +A parse error occurred. +.RS +.PP +Parse errors include unexpected \f[B]EOF\f[], using an invalid +character, failing to find the end of a string or comment, and using a +token where it is invalid. +.RE +.TP +.B \f[B]3\f[] +A runtime error occurred. +.RS +.PP +Runtime errors include assigning an invalid number to \f[B]ibase\f[], +\f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a +\f[B]read()\f[] call, calling \f[B]read()\f[] inside of a +\f[B]read()\f[] call, type errors, and attempting an operation when the +stack has too few elements. +.RE +.TP +.B \f[B]4\f[] +A fatal error occurred. +.RS +.PP +Fatal errors include memory allocation errors, I/O errors, failing to +open files, attempting to use files that do not have only ASCII +characters (dc(1) only accepts ASCII characters), attempting to open a +directory as a file, and giving invalid command\-line options. +.RE +.PP +The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) +always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. +.PP +The other statuses will only be returned when dc(1) is not in +interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since +dc(1) resets its state (see the \f[B]RESET\f[] 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[] flag or \f[B]\-\-interactive\f[] 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[] flag or \f[B]\-\-interactive\f[] option. +.SH INTERACTIVE MODE +.PP +Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. +Interactive mode is turned on automatically when both \f[B]stdin\f[] and +\f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and +\f[B]\-\-interactive\f[] option can turn it on in other cases. +.PP +In interactive mode, dc(1) attempts to recover from errors (see the +\f[B]RESET\f[] section), and in normal execution, flushes +\f[B]stdout\f[] as soon as execution is done for the current input. +.SH TTY MODE +.PP +If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all +connected to a TTY, dc(1) turns on "TTY mode." +.PP +TTY mode is required for history to be enabled (see the \f[B]COMMAND +LINE HISTORY\f[] section). +It is also required to enable special handling for \f[B]SIGINT\f[] +signals. +.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[] and \f[B]stdout\f[] to +be connected to a terminal. +.SH SIGNAL HANDLING +.PP +Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the +current input. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will +reset (see the \f[B]RESET\f[] section). +Otherwise, it will clean up and exit. +.PP +Note that "current input" can mean one of two things. +If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will +ask for more input. +If dc(1) is processing input from a file in TTY mode, it will stop +processing the file and start processing the next file, if one exists, +or ask for input from \f[B]stdin\f[] if no other file exists. +.PP +This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing +a file, it can seem as though dc(1) did not respond to the signal since +it will immediately start executing the next file. +This is by design; most files that users execute when interacting with +dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. +The rest of the files could still be executed without problem, allowing +the user to continue. +.PP +\f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, +and it uses the default handler for all other signals. +The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY +mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. +.SH COMMAND LINE HISTORY +.PP +dc(1) supports interactive command\-line editing. +If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is +enabled. +Previous lines can be recalled and edited with the arrow keys. +.PP +\f[B]Note\f[]: 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_MESSAGS\f[]. +.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 +(“POSIX.1\-2017â€) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) +specification. +.SH BUGS +.PP +None are known. +Report bugs at https://git.yzena.com/gavin/bc. +.SH AUTHOR +.PP +Gavin D. +Howard and contributors. diff --git a/manuals/dc/P.1.md b/manuals/dc/P.1.md new file mode 100644 index 000000000000..dc6d3d950067 --- /dev/null +++ b/manuals/dc/P.1.md @@ -0,0 +1,1189 @@ + + +# Name + +dc - arbitrary-precision reverse-Polish notation calculator + +# SYNOPSIS + +**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] + +# DESCRIPTION + +dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish +notation) to store numbers and results of computations. Arithmetic operations +pop arguments off of the stack and push the results. + +If no files are given on the command-line as extra arguments (i.e., not as +**-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, +those files are processed, and dc(1) will then exit. + +This is different from the dc(1) on OpenBSD and possibly other dc(1) +implementations, where **-e** (**--expression**) and **-f** (**--file**) +arguments cause dc(1) to execute them and exit. The reason for this is that this +dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** +(see the **ENVIRONMENT VARIABLES** section). Any expressions given on the +command-line should be used to set up a standard environment. For example, if a +user wants the **scale** always set to **10**, they can set **DC_ENV_ARGS** to +**-e 10k**, and this dc(1) will always start with a **scale** of **10**. + +If users want to have dc(1) exit after processing all input from **-e** and +**-f** arguments (and their equivalents), then they can just simply add **-e q** +as the last command-line argument or define the environment variable +**DC_EXPR_EXIT**. + +# OPTIONS + +The following are the options that dc(1) accepts. + +**-h**, **--help** + +: Prints a usage message and quits. + +**-v**, **-V**, **--version** + +: Print the version information (copyright header) and exit. + +**-i**, **--interactive** + +: Forces interactive mode. (See the **INTERACTIVE MODE** section.) + + This is a **non-portable extension**. + +**-P**, **--no-prompt** + +: This option is a no-op. + + 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**. + +**-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. + + In other dc(1) implementations, this option causes the program to execute + the expressions and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + 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. + + In other dc(1) implementations, this option causes the program to execute + the files and then exit. This dc(1) does not, unless the + **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + + This is a **non-portable extension**. + +All long options are **non-portable extensions**. + +# STDOUT + +Any non-error output is written to **stdout**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if +**stdout** is closed, as in **dc >&-**, it will quit with an error. This +is done so that dc(1) can report problems when **stdout** is redirected to a +file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stdout** to +**/dev/null**. + +# STDERR + +Any error output is written to **stderr**. + +**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal +error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if +**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This +is done so that dc(1) can exit with an error code when **stderr** is redirected +to a file. + +If there are scripts that depend on the behavior of other dc(1) implementations, +it is recommended that those scripts be changed to redirect **stderr** to +**/dev/null**. + +# SYNTAX + +Each item in the input source code, either a number (see the **NUMBERS** +section) or a command (see the **COMMANDS** section), is processed and executed, +in order. Input is processed immediately when entered. + +**ibase** is a register (see the **REGISTERS** section) that determines how to +interpret constant numbers. It is the "input" base, or the number base used for +interpreting input numbers. **ibase** is initially **10**. The max allowable +value for **ibase** is **16**. The min allowable value for **ibase** is **2**. +The max allowable value for **ibase** can be queried in dc(1) programs with the +**T** command. + +**obase** is a register (see the **REGISTERS** section) that determines how to +output results. It is the "output" base, or the number base used for outputting +numbers. **obase** is initially **10**. The max allowable value for **obase** is +**DC_BASE_MAX** and can be queried with the **U** command. The min allowable +value for **obase** is **0**. If **obase** is **0**, values are output in +scientific notation, and if **obase** is **1**, values are output in engineering +notation. Otherwise, values are output in the specified base. + +Outputting in scientific and engineering notations are **non-portable +extensions**. + +The *scale* of an expression is the number of digits in the result of the +expression right of the decimal point, and **scale** is a register (see the +**REGISTERS** section) that sets the precision of any operations (with +exceptions). **scale** is initially **0**. **scale** cannot be negative. The max +allowable value for **scale** can be queried in dc(1) programs with the **V** +command. + +**seed** is a register containing the current seed for the pseudo-random number +generator. If the current value of **seed** is queried and stored, then if it is +assigned to **seed** later, the pseudo-random number generator is guaranteed to +produce the same sequence of pseudo-random numbers that were generated after the +value of **seed** was first queried. + +Multiple values assigned to **seed** can produce the same sequence of +pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not +guaranteed that querying **seed** immediately after will return the same value. +In addition, the value of **seed** will change after any call to the **'** +command or the **"** command that does not get receive a value of **0** or +**1**. The maximum integer returned by the **'** command can be queried with the +**W** command. + +**Note**: The values returned by the pseudo-random number generator with the +**'** and **"** commands are guaranteed to **NOT** be cryptographically secure. +This is a consequence of using a seeded pseudo-random number generator. However, +they **are** guaranteed to be reproducible with identical **seed** values. + +The pseudo-random number generator, **seed**, and all associated operations are +**non-portable extensions**. + +## Comments + +Comments go from **#** until, and not including, the next newline. This is a +**non-portable extension**. + +# NUMBERS + +Numbers are strings made up of digits, uppercase letters up to **F**, and at +most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. +Uppercase letters are equal to **9** + their position in the alphabet (i.e., +**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the +current value of **ibase**, they are set to the value of the highest valid digit +in **ibase**. + +Single-character numbers (i.e., **A** alone) take the value that they would have +if they were valid digits, regardless of the value of **ibase**. This means that +**A** alone always equals decimal **10** and **F** alone always equals decimal +**15**. + +In addition, dc(1) accepts numbers in scientific notation. These have the form +**\e\**. The power (the portion after the **e**) must be an +integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative +exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. + +**WARNING**: Both the number and the exponent in scientific notation are +interpreted according to the current **ibase**, but the number is still +multiplied by **10\^exponent** regardless of the current **ibase**. For example, +if **ibase** is **16** and dc(1) is given the number string **FFeA**, the +resulting decimal number will be **2550000000000**, and if dc(1) is given the +number string **10e_4**, the resulting decimal number will be **0.0016**. + +Accepting input as scientific notation is a **non-portable extension**. + +# COMMANDS + +The valid commands are listed below. + +## Printing + +These commands are used for printing. + +Note that both scientific notation and engineering notation are available for +printing numbers. Scientific notation is activated by assigning **0** to +**obase** using **0o**, and engineering notation is activated by assigning **1** +to **obase** using **1o**. To deactivate them, just assign a different value to +**obase**. + +Printing numbers in scientific notation and/or engineering notation is a +**non-portable extension**. + +**p** + +: Prints the value on top of the stack, whether number or string, and prints a + newline after. + + This does not alter the stack. + +**n** + +: Prints the value on top of the stack, whether number or string, and pops it + off of the stack. + +**P** + +: Pops a value off the stack. + + If the value is a number, it is truncated and the absolute value of the + result is printed as though **obase** is **UCHAR_MAX+1** and each digit is + interpreted as an ASCII character, making it a byte stream. + + If the value is a string, it is printed without a trailing newline. + + This is a **non-portable extension**. + +**f** + +: Prints the entire contents of the stack, in order from newest to oldest, + without altering anything. + + Users should use this command when they get lost. + +## Arithmetic + +These are the commands used for arithmetic. + +**+** + +: The top two values are popped off the stack, added, and the result is pushed + onto the stack. The *scale* of the result is equal to the max *scale* of + both operands. + +**-** + +: The top two values are popped off the stack, subtracted, and the result is + pushed onto the stack. The *scale* of the result is equal to the max + *scale* of both operands. + +**\*** + +: The top two values are popped off the stack, multiplied, and the result is + pushed onto the stack. If **a** is the *scale* of the first expression and + **b** is the *scale* of the second expression, the *scale* of the result + is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return + the obvious values. + +**/** + +: The top two values are popped off the stack, divided, and the result is + pushed onto the stack. The *scale* of the result is equal to **scale**. + + The first value popped off of the stack must be non-zero. + +**%** + +: The top two values are popped off the stack, remaindered, and the result is + pushed onto the stack. + + Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and + 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* + **max(scale+scale(b),scale(a))**. + + The first value popped off of the stack must be non-zero. + +**~** + +: The top two values are popped off the stack, divided and remaindered, and + the results (divided first, remainder second) are pushed onto the stack. + This is equivalent to **x y / x y %** except that **x** and **y** are only + evaluated once. + + The first value popped off of the stack must be non-zero. + + This is a **non-portable extension**. + +**\^** + +: The top two values are popped off the stack, the second is raised to the + power of the first, and the result is pushed onto the stack. + + The first value popped off of the stack must be an integer, and if that + value is negative, the second value popped off of the stack must be + non-zero. + +**v** + +: The top value is popped off the stack, its square root is computed, and the + result is pushed onto the stack. The *scale* of the result is equal to + **scale**. + + The value popped off of the stack must be non-negative. + +**\_** + +: If this command *immediately* precedes a number (i.e., no spaces or other + commands), then that number is input as a negative number. + + Otherwise, the top value on the stack is popped and copied, and the copy is + negated and pushed onto the stack. This behavior without a number is a + **non-portable extension**. + +**b** + +: The top value is popped off the stack, and if it is zero, it is pushed back + onto the stack. Otherwise, its absolute value is pushed onto the stack. + + This is a **non-portable extension**. + +**|** + +: The top three values are popped off the stack, a modular exponentiation is + computed, and the result is pushed onto the stack. + + The first value popped is used as the reduction modulus and must be an + integer and non-zero. The second value popped is used as the exponent and + must be an integer and non-negative. The third value popped is the base and + must be an integer. + + This is a **non-portable extension**. + +**\$** + +: The top value is popped off the stack and copied, and the copy is truncated + and pushed onto the stack. + + This is a **non-portable extension**. + +**\@** + +: The top two values are popped off the stack, and the precision of the second + is set to the value of the first, whether by truncation or extension. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**H** + +: The top two values are popped off the stack, and the second is shifted left + (radix shifted right) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**h** + +: The top two values are popped off the stack, and the second is shifted right + (radix shifted left) to the value of the first. + + The first value popped off of the stack must be an integer and non-negative. + + This is a **non-portable extension**. + +**G** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if they are equal, or **0** otherwise. + + This is a **non-portable extension**. + +**N** + +: The top value is popped off of the stack, and if it a **0**, a **1** is + pushed; otherwise, a **0** is pushed. + + This is a **non-portable extension**. + +**(** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**{** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is less than or equal to the second, or **0** + otherwise. + + This is a **non-portable extension**. + +**)** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than the second, or **0** otherwise. + + This is a **non-portable extension**. + +**}** + +: The top two values are popped off of the stack, they are compared, and a + **1** is pushed if the first is greater than or equal to the second, or + **0** otherwise. + + This is a **non-portable extension**. + +**M** + +: The top two values are popped off of the stack. If they are both non-zero, a + **1** is pushed onto the stack. If either of them is zero, or both of them + are, then a **0** is pushed onto the stack. + + This is like the **&&** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +**m** + +: The top two values are popped off of the stack. If at least one of them is + non-zero, a **1** is pushed onto the stack. If both of them are zero, then a + **0** is pushed onto the stack. + + This is like the **||** operator in bc(1), and it is *not* a short-circuit + operator. + + This is a **non-portable extension**. + +## Pseudo-Random Number Generator + +dc(1) has a built-in pseudo-random number generator. These commands query the +pseudo-random number generator. (See Parameters for more information about the +**seed** value that controls the pseudo-random number generator.) + +The pseudo-random number generator is guaranteed to **NOT** be +cryptographically secure. + +**'** + +: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the + **LIMITS** section). + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +**"** + +: Pops a value off of the stack, which is used as an **exclusive** upper bound + on the integer that will be generated. If the bound is negative or is a + non-integer, an error is raised, and dc(1) resets (see the **RESET** + section) while **seed** remains unchanged. If the bound is larger than + **DC_RAND_MAX**, the higher bound is honored by generating several + pseudo-random integers, multiplying them by appropriate powers of + **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that + can be generated with this command is unbounded. Using this command will + change the value of **seed**, unless the operand is **0** or **1**. In that + case, **0** is pushed onto the stack, and **seed** is *not* changed. + + The generated integer is made as unbiased as possible, subject to the + limitations of the pseudo-random number generator. + + This is a **non-portable extension**. + +## Stack Control + +These commands control the stack. + +**c** + +: Removes all items from ("clears") the stack. + +**d** + +: Copies the item on top of the stack ("duplicates") and pushes the copy onto + the stack. + +**r** + +: Swaps ("reverses") the two top items on the stack. + +**R** + +: Pops ("removes") the top value from the stack. + +## Register Control + +These commands control registers (see the **REGISTERS** section). + +**s***r* + +: Pops the value off the top of the stack and stores it into register *r*. + +**l***r* + +: Copies the value in register *r* and pushes it onto the stack. This does not + alter the contents of *r*. + +**S***r* + +: Pops the value off the top of the (main) stack and pushes it onto the stack + of register *r*. The previous value of the register becomes inaccessible. + +**L***r* + +: Pops the value off the top of the stack for register *r* and push it onto + the main stack. The previous value in the stack for register *r*, if any, is + now accessible via the **l***r* command. + +## Parameters + +These commands control the values of **ibase**, **obase**, **scale**, and +**seed**. Also see the **SYNTAX** section. + +**i** + +: Pops the value off of the top of the stack and uses it to set **ibase**, + which must be between **2** and **16**, inclusive. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**o** + +: Pops the value off of the top of the stack and uses it to set **obase**, + which must be between **0** and **DC_BASE_MAX**, inclusive (see the + **LIMITS** section and the **NUMBERS** section). + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**k** + +: Pops the value off of the top of the stack and uses it to set **scale**, + which must be non-negative. + + If the value on top of the stack has any *scale*, the *scale* is ignored. + +**j** + +: Pops the value off of the top of the stack and uses it to set **seed**. The + meaning of **seed** is dependent on the current pseudo-random number + generator but is guaranteed to not change except for new major versions. + + The *scale* and sign of the value may be significant. + + If a previously used **seed** value is used again, the pseudo-random number + generator is guaranteed to produce the same sequence of pseudo-random + numbers as it did when the **seed** value was previously used. + + The exact value assigned to **seed** is not guaranteed to be returned if the + **J** command is used. However, if **seed** *does* return a different value, + both values, when assigned to **seed**, are guaranteed to produce the same + sequence of pseudo-random numbers. This means that certain values assigned + to **seed** will not produce unique sequences of pseudo-random numbers. + + There is no limit to the length (number of significant decimal digits) or + *scale* of the value that can be assigned to **seed**. + + This is a **non-portable extension**. + +**I** + +: Pushes the current value of **ibase** onto the main stack. + +**O** + +: Pushes the current value of **obase** onto the main stack. + +**K** + +: Pushes the current value of **scale** onto the main stack. + +**J** + +: Pushes the current value of **seed** onto the main stack. + + This is a **non-portable extension**. + +**T** + +: Pushes the maximum allowable value of **ibase** onto the main stack. + + This is a **non-portable extension**. + +**U** + +: Pushes the maximum allowable value of **obase** onto the main stack. + + This is a **non-portable extension**. + +**V** + +: Pushes the maximum allowable value of **scale** onto the main stack. + + This is a **non-portable extension**. + +**W** + +: Pushes the maximum (inclusive) integer that can be generated with the **'** + pseudo-random number generator command. + + This is a **non-portable extension**. + +## Strings + +The following commands control strings. + +dc(1) can work with both numbers and strings, and registers (see the +**REGISTERS** section) can hold both strings and numbers. dc(1) always knows +whether the contents of a register are a string or a number. + +While arithmetic operations have to have numbers, and will print an error if +given a string, other commands accept strings. + +Strings can also be executed as macros. For example, if the string **[1pR]** is +executed as a macro, then the code **1pR** is executed, meaning that the **1** +will be printed with a newline after and then popped from the stack. + +**\[**_characters_**\]** + +: Makes a string containing *characters* and pushes it onto the stack. + + If there are brackets (**\[** and **\]**) in the string, then they must be + balanced. Unbalanced brackets can be escaped using a backslash (**\\**) + character. + + If there is a backslash character in the string, the character after it + (even another backslash) is put into the string verbatim, but the (first) + backslash is not. + +**a** + +: The value on top of the stack is popped. + + If it is a number, it is truncated and its absolute value is taken. The + result mod **UCHAR_MAX+1** is calculated. If that result is **0**, push an + empty string; otherwise, push a one-character string where the character is + the result of the mod interpreted as an ASCII character. + + If it is a string, then a new string is made. If the original string is + empty, the new string is empty. If it is not, then the first character of + the original string is used to create the new string as a one-character + string. The new string is then pushed onto the stack. + + This is a **non-portable extension**. + +**x** + +: Pops a value off of the top of the stack. + + If it is a number, it is pushed back onto the stack. + + If it is a string, it is executed as a macro. + + This behavior is the norm whenever a macro is executed, whether by this + command or by the conditional execution commands below. + +**\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is greater than the second, then the contents of register + *r* are executed. + + For example, **0 1>a** will execute the contents of register **a**, and + **1 0>a** will not. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\>***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not greater than the second (less than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\>***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is less than the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!\<***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not less than the second (greater than or equal to), then + the contents of register *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!\<***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is equal to the second, then the contents of register *r* + are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**!=***r* + +: Pops two values off of the stack that must be numbers and compares them. If + the first value is not equal to the second, then the contents of register + *r* are executed. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + +**!=***r***e***s* + +: Like the above, but will execute register *s* if the comparison fails. + + If either or both of the values are not numbers, dc(1) will raise an error + and reset (see the **RESET** section). + + This is a **non-portable extension**. + +**?** + +: Reads a line from the **stdin** and executes it. This is to allow macros to + request input from users. + +**q** + +: During execution of a macro, this exits the execution of that macro and the + execution of the macro that executed it. If there are no macros, or only one + macro executing, dc(1) exits. + +**Q** + +: Pops a value from the stack which must be non-negative and is used the + number of macro executions to pop off of the execution stack. If the number + of levels to pop is greater than the number of executing macros, dc(1) + exits. + +## Status + +These commands query status of the stack or its top value. + +**Z** + +: Pops a value off of the stack. + + If it is a number, calculates the number of significant decimal digits it + has and pushes the result. + + If it is a string, pushes the number of characters the string has. + +**X** + +: Pops a value off of the stack. + + If it is a number, pushes the *scale* of the value onto the stack. + + If it is a string, pushes **0**. + +**z** + +: Pushes the current stack depth (before execution of this command). + +## Arrays + +These commands manipulate arrays. + +**:***r* + +: Pops the top two values off of the stack. The second value will be stored in + the array *r* (see the **REGISTERS** section), indexed by the first value. + +**;***r* + +: Pops the value on top of the stack and uses it as an index into the array + *r*. The selected value is then pushed onto the stack. + +# REGISTERS + +Registers are names that can store strings, numbers, and arrays. (Number/string +registers do not interfere with array registers.) + +Each register is also its own stack, so the current register value is the top of +the stack for the register. All registers, when first referenced, have one value +(**0**) in their stack. + +In non-extended register mode, a register name is just the single character that +follows any command that needs a register name. The only exception is a newline +(**'\\n'**); it is a parse error for a newline to be used as a register name. + +## Extended Register Mode + +Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited +amounts of registers, if extended register mode is enabled. + +If extended register mode is enabled (**-x** or **--extended-register** +command-line arguments are given), then normal single character registers are +used *unless* the character immediately following a command that needs a +register name is a space (according to **isspace()**) and not a newline +(**'\\n'**). + +In that case, the register name is found according to the regex +**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if +the next non-space characters do not match that regex. + +# RESET + +When dc(1) encounters an error or a signal that it has a non-default handler +for, it resets. This means that several things happen. + +First, any macros that are executing are stopped and popped off the stack. +The behavior is not unlike that of exceptions in programming languages. Then +the execution point is set so that any code waiting to execute (after all +macros returned) is skipped. + +Thus, when dc(1) resets, it skips any remaining code waiting to be executed. +Then, if it is interactive mode, and the error was not a fatal error (see the +**EXIT STATUS** section), it asks for more input; otherwise, it exits with the +appropriate return code. + +# PERFORMANCE + +Most dc(1) implementations use **char** types to calculate the value of **1** +decimal digit at a time, but that can be slow. This dc(1) does something +different. + +It uses large integers to calculate more than **1** decimal digit at a time. If +built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is +**64**, then each integer has **9** decimal digits. If built in an environment +where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This +value (the number of decimal digits per large integer) is called +**DC_BASE_DIGS**. + +In addition, this dc(1) uses an even larger integer for overflow checking. This +integer type depends on the value of **DC_LONG_BIT**, but is always at least +twice as large as the integer type used to store digits. + +# LIMITS + +The following are the limits on dc(1): + +**DC_LONG_BIT** + +: The number of bits in the **long** type in the environment where dc(1) was + built. This determines how many decimal digits can be stored in a single + large integer (see the **PERFORMANCE** section). + +**DC_BASE_DIGS** + +: The number of decimal digits per large integer (see the **PERFORMANCE** + section). Depends on **DC_LONG_BIT**. + +**DC_BASE_POW** + +: The max decimal number that each large integer can store (see + **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. + +**DC_OVERFLOW_MAX** + +: The max number that the overflow type (see the **PERFORMANCE** section) can + hold. Depends on **DC_LONG_BIT**. + +**DC_BASE_MAX** + +: The maximum output base. Set at **DC_BASE_POW**. + +**DC_DIM_MAX** + +: The maximum size of arrays. Set at **SIZE_MAX-1**. + +**DC_SCALE_MAX** + +: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. + +**DC_STRING_MAX** + +: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NAME_MAX** + +: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. + +**DC_NUM_MAX** + +: The maximum length of a number (in decimal digits), which includes digits + after the decimal point. Set at **DC_OVERFLOW_MAX-1**. + +**DC_RAND_MAX** + +: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set + at **2\^DC_LONG_BIT-1**. + +Exponent + +: The maximum allowable exponent (positive or negative). Set at + **DC_OVERFLOW_MAX**. + +Number of vars + +: The maximum number of vars/arrays. Set at **SIZE_MAX-1**. + +These limits are meant to be effectively non-existent; the limits are so large +(at least on 64-bit machines) that there should not be any point at which they +become a problem. In fact, memory should be exhausted before these limits should +be hit. + +# ENVIRONMENT VARIABLES + +dc(1) recognizes the following environment variables: + +**DC_ENV_ARGS** + +: This is another way to give command-line arguments to dc(1). They should be + in the same format as all other command-line arguments. These are always + processed first, so any files given in **DC_ENV_ARGS** will be processed + before arguments and files given on the command-line. This gives the user + the ability to set up "standard" options and files to be used at every + invocation. The most useful thing for such files to contain would be useful + functions that the user might want every time dc(1) runs. Another use would + be to use the **-e** option to set **scale** to a value other than **0**. + + The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, + but it does not understand escape sequences. For example, the string + **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string + **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. + + The quote parsing will handle either kind of quotes, **'** or **"**. Thus, + if you have a file with any number of single quotes in the name, you can use + double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice + versa if you have a file with double quotes. However, handling a file with + both kinds of quotes in **DC_ENV_ARGS** is not supported due to the + complexity of the parsing, though such files are still supported on the + command-line where the parsing is done by the shell. + +**DC_LINE_LENGTH** + +: If this environment variable exists and contains an integer that is greater + than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output + lines to that length, including the backslash newline combo. The default + line length is **70**. + +**DC_EXPR_EXIT** + +: If this variable exists (no matter the contents), dc(1) will exit + immediately after executing expressions and files given by the **-e** and/or + **-f** command-line options (and any equivalents). + +# EXIT STATUS + +dc(1) returns the following exit statuses: + +**0** + +: No error. + +**1** + +: A math error occurred. This follows standard practice of using **1** for + expected errors, since math errors will happen in the process of normal + execution. + + Math errors include divide by **0**, taking the square root of a negative + number, using a negative number as a bound for the pseudo-random number + generator, attempting to convert a negative number to a hardware integer, + overflow when converting a number to a hardware integer, and attempting to + use a non-integer where an integer is required. + + Converting to a hardware integer happens for the second operand of the power + (**\^**), places (**\@**), left shift (**H**), and right shift (**h**) + operators. + +**2** + +: A parse error occurred. + + Parse errors include unexpected **EOF**, using an invalid character, failing + to find the end of a string or comment, and using a token where it is + invalid. + +**3** + +: A runtime error occurred. + + Runtime errors include assigning an invalid number to **ibase**, **obase**, + or **scale**; give a bad expression to a **read()** call, calling **read()** + inside of a **read()** call, type errors, and attempting an operation when + the stack has too few elements. + +**4** + +: A fatal error occurred. + + Fatal errors include memory allocation errors, I/O errors, failing to open + files, attempting to use files that do not have only ASCII characters (dc(1) + only accepts ASCII characters), attempting to open a directory as a file, + and giving invalid command-line options. + +The exit status **4** is special; when a fatal error occurs, dc(1) always exits +and returns **4**, no matter what mode dc(1) is in. + +The other statuses will only be returned when dc(1) is not in interactive mode +(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the +**RESET** section) and accepts more input when one of those errors occurs in +interactive mode. This is also the case when interactive mode is forced by the +**-i** flag or **--interactive** option. + +These exit statuses allow dc(1) to be used in shell scripting with error +checking, and its normal behavior can be forced by using the **-i** flag or +**--interactive** option. + +# INTERACTIVE MODE + +Like bc(1), dc(1) has an interactive mode and a non-interactive mode. +Interactive mode is turned on automatically when both **stdin** and **stdout** +are hooked to a terminal, but the **-i** flag and **--interactive** option can +turn it on in other cases. + +In interactive mode, dc(1) attempts to recover from errors (see the **RESET** +section), and in normal execution, flushes **stdout** as soon as execution is +done for the current input. + +# TTY MODE + +If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns +on "TTY mode." + +TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** +section). It is also required to enable special handling for **SIGINT** signals. + +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. + +# SIGNAL HANDLING + +Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If +dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the +**RESET** section). Otherwise, it will clean up and exit. + +Note that "current input" can mean one of two things. If dc(1) is processing +input from **stdin** in TTY mode, it will ask for more input. If dc(1) is +processing input from a file in TTY mode, it will stop processing the file and +start processing the next file, if one exists, or ask for input from **stdin** +if no other file exists. + +This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it +can seem as though dc(1) did not respond to the signal since it will immediately +start executing the next file. This is by design; most files that users execute +when interacting with dc(1) have function definitions, which are quick to parse. +If a file takes a long time to execute, there may be a bug in that file. The +rest of the files could still be executed without problem, allowing the user to +continue. + +**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the +default handler for all other signals. The one exception is **SIGHUP**; in that +case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and +exit. + +# COMMAND LINE HISTORY + +dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see +the **TTY MODE** section), history is enabled. Previous lines can be recalled +and edited with the arrow keys. + +**Note**: tabs are converted to 8 spaces. + +# LOCALES + +This dc(1) ships with support for adding error messages for different locales +and thus, supports **LC_MESSAGS**. + +# SEE ALSO + +bc(1) + +# STANDARDS + +The dc(1) utility operators are compliant with the operators in the bc(1) +[IEEE Std 1003.1-2017 (“POSIX.1-2017â€)][1] specification. + +# BUGS + +None are known. Report bugs at https://git.yzena.com/gavin/bc. + +# AUTHOR + +Gavin D. Howard and contributors. + +[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html diff --git a/release.sh b/release.sh index bd37db27b286..06663b998f72 100755 --- a/release.sh +++ b/release.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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: @@ -86,7 +86,6 @@ configure() { header "$_configure_header" CFLAGS="$_configure_CFLAGS" CC="$_configure_CC" GEN_HOST="$_configure_GEN_HOST" \ LONG_BIT="$_configure_LONG_BIT" ./configure.sh $_configure_configure_flags > /dev/null - } build() { @@ -513,7 +512,7 @@ if [ "$run_tests" -ne 0 ]; then header "Configuring for afl-gcc..." - configure "$debug $gcc_flags -DDC_ENABLE_RAND=0" "afl-gcc" "-HNP -gO3" "1" "$bits" + configure "$debug $gcc_flags -DBC_ENABLE_RAND=0" "afl-gcc" "-HNP -gO3" "1" "$bits" printf '\n' printf 'Run make\n' @@ -522,7 +521,7 @@ if [ "$run_tests" -ne 0 ]; then printf '\n' printf 'Then run ASan on the fuzzer test cases with the following build:\n' printf '\n' - printf ' CFLAGS="-fsanitize=address -fno-omit-frame-pointer -DDC_ENABLE_RAND=0" ./configure.sh -gO3 -HNPS\n' + printf ' CFLAGS="-fsanitize=address -fno-omit-frame-pointer -DBC_ENABLE_RAND=0" ./configure.sh -gO3 -HNPS\n' printf ' make\n' printf '\n' printf 'Then run the GitHub release script as follows:\n' diff --git a/src/args.c b/src/args.c index d3735178fc48..1626ad4944e4 100644 --- a/src/args.c +++ b/src/args.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -184,7 +184,7 @@ void bc_args(int argc, char *argv[]) { #if DC_ENABLED case 'x': { - assert(!BC_IS_BC); + assert(BC_IS_DC); vm.flags |= DC_FLAG_X; break; } @@ -205,7 +205,7 @@ void bc_args(int argc, char *argv[]) { if (version) bc_vm_info(NULL); if (do_exit) exit((int) vm.status); - if (vm.exprs.len > 1 || !BC_IS_BC) vm.flags |= BC_FLAG_Q; + if (vm.exprs.len > 1 || BC_IS_DC) vm.flags |= BC_FLAG_Q; if (opts.optind < (size_t) argc) bc_vec_init(&vm.files, sizeof(char*), NULL); diff --git a/src/bc/bc.c b/src/bc/bc.c index 86d8f81dd401..ef0fc3d6865d 100644 --- a/src/bc/bc.c +++ b/src/bc/bc.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/bc/lex.c b/src/bc/lex.c index d4c6bd4c192e..cc780e0d6278 100644 --- a/src/bc/lex.c +++ b/src/bc/lex.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/bc/parse.c b/src/bc/parse.c index fb00447ee6bc..2aa9d97468ff 100644 --- a/src/bc/parse.c +++ b/src/bc/parse.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -399,8 +399,10 @@ static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, // right here, we need to increment this. *nexs = *nexs + 1; - if (type == BC_LEX_NAME) - bc_parse_name(p, prev, can_assign, flags | BC_PARSE_NOCALL); + if (type == BC_LEX_NAME) { + uint8_t flags2 = flags & ~BC_PARSE_ARRAY; + bc_parse_name(p, prev, can_assign, flags2 | BC_PARSE_NOCALL); + } 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); @@ -1006,24 +1008,24 @@ static void bc_parse_stmt(BcParse *p) { case BC_LEX_KW_LENGTH: case BC_LEX_KW_OBASE: case BC_LEX_KW_SCALE: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_SEED: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_IRAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_READ: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_RAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXIBASE: case BC_LEX_KW_MAXOBASE: case BC_LEX_KW_MAXSCALE: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXRAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { bc_parse_expr_status(p, BC_PARSE_PRINT, bc_parse_next_expr); break; @@ -1092,9 +1094,9 @@ static void bc_parse_stmt(BcParse *p) { bc_vm_printf("BC_STRING_MAX = %lu\n", BC_MAX_STRING); bc_vm_printf("BC_NAME_MAX = %lu\n", BC_MAX_NAME); bc_vm_printf("BC_NUM_MAX = %lu\n", BC_MAX_NUM); -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_vm_printf("BC_RAND_MAX = %lu\n", BC_MAX_RAND); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_vm_printf("MAX Exponent = %lu\n", BC_MAX_EXP); bc_vm_printf("Number of vars = %lu\n", BC_MAX_VARS); @@ -1161,7 +1163,8 @@ void bc_parse_parse(BcParse *p) { exit: BC_SIG_MAYLOCK; - if (BC_ERR((vm.status && vm.status != BC_STATUS_QUIT))) bc_parse_reset(p); + if (BC_ERR(((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig))) + bc_parse_reset(p); BC_LONGJMP_CONT; } @@ -1212,7 +1215,7 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, // I can just add the instruction because // negative will already be taken care of. bc_parse_push(p, BC_INST_TRUNC); - rprn = can_assign = false; + rprn = can_assign = incdec = false; get_token = true; flags &= ~(BC_PARSE_ARRAY); break; @@ -1355,9 +1358,9 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, case BC_LEX_KW_IBASE: case BC_LEX_KW_LAST: case BC_LEX_KW_OBASE: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_SEED: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); @@ -1376,9 +1379,9 @@ 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: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_IRAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); @@ -1392,15 +1395,15 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, } case BC_LEX_KW_READ: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_RAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXIBASE: case BC_LEX_KW_MAXOBASE: case BC_LEX_KW_MAXSCALE: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXRAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); @@ -1455,6 +1458,8 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, nexprs -= !BC_PARSE_OP_PREFIX(top); bc_vec_pop(&p->ops); + + incdec = false; } if (BC_ERR(nexprs != 1)) bc_parse_err(p, BC_ERROR_PARSE_EXPR); @@ -1482,7 +1487,8 @@ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, inst != BC_INST_ASSIGN_PLUS); } - if (inst >= BC_INST_ASSIGN_PLUS_NO_VAL && inst <= BC_INST_ASSIGN_NO_VAL) + if (inst >= BC_INST_ASSIGN_POWER_NO_VAL && + inst <= BC_INST_ASSIGN_NO_VAL) { bc_vec_pop(&p->func->code); if (incdec) bc_parse_push(p, BC_INST_ONE); diff --git a/src/data.c b/src/data.c index 3dae13763470..2556f795eed6 100644 --- a/src/data.c +++ b/src/data.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -588,6 +588,7 @@ const char* bc_inst_names[] = { "BC_INST_ARRAY", #endif // BC_ENABLED + "BC_INST_ZERO", "BC_INST_ONE", #if BC_ENABLED @@ -663,11 +664,11 @@ const char* bc_inst_names[] = { }; #endif // BC_DEBUG_CODE -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER; -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #if BC_ENABLED const BcLexKeyword bc_lex_kws[] = { @@ -685,27 +686,27 @@ const BcLexKeyword bc_lex_kws[] = { BC_LEX_KW_ENTRY("ibase", 5, true), BC_LEX_KW_ENTRY("obase", 5, true), BC_LEX_KW_ENTRY("scale", 5, true), -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("seed", 4, false), -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("length", 6, true), BC_LEX_KW_ENTRY("print", 5, false), BC_LEX_KW_ENTRY("sqrt", 4, true), BC_LEX_KW_ENTRY("abs", 3, false), -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("irand", 5, false), -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("quit", 4, true), BC_LEX_KW_ENTRY("read", 4, false), -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("rand", 4, false), -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("maxibase", 8, false), BC_LEX_KW_ENTRY("maxobase", 8, false), BC_LEX_KW_ENTRY("maxscale", 8, false), -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("maxrand", 7, false), -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("else", 4, false), }; @@ -719,7 +720,7 @@ const uint8_t bc_parse_exprs[] = { BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, false), @@ -727,7 +728,14 @@ const uint8_t bc_parse_exprs[] = { BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, false), BC_PARSE_EXPR_ENTRY(true, true, true, false, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, false, 0, 0, 0, 0, 0) -#else // BC_ENABLE_EXTRA_MATH +#elif BC_ENABLE_EXTRA_MATH // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND + BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), + BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false), + BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, false), + BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), + BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, false, true), + BC_PARSE_EXPR_ENTRY(true, false, true, true, true, true, false, 0), +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_PARSE_EXPR_ENTRY(true, true, true, false, false, true, true, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, true, true), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), @@ -786,11 +794,11 @@ const uint8_t dc_lex_regs[] = { const size_t dc_lex_regs_len = sizeof(dc_lex_regs) / sizeof(uint8_t); const uchar dc_lex_tokens[] = { -#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_IRAND, -#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, -#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_TRUNC, @@ -798,11 +806,11 @@ const uchar dc_lex_tokens[] = { BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_OP_MODULUS, BC_LEX_INVALID, -#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_RAND, -#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, -#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_LPAREN, BC_LEX_RPAREN, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID, BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, @@ -823,20 +831,20 @@ const uchar dc_lex_tokens[] = { BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_IBASE, -#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_SEED, -#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, -#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_SCALE, BC_LEX_LOAD_POP, BC_LEX_OP_BOOL_AND, BC_LEX_OP_BOOL_NOT, BC_LEX_KW_OBASE, BC_LEX_PRINT_STREAM, BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_KW_MAXIBASE, BC_LEX_KW_MAXOBASE, BC_LEX_KW_MAXSCALE, -#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_MAXRAND, -#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, -#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_SCALE_FACTOR, BC_LEX_INVALID, BC_LEX_KW_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID, @@ -848,11 +856,11 @@ const uchar dc_lex_tokens[] = { BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_STORE_IBASE, -#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_STORE_SEED, -#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, -#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_STORE_SCALE, BC_LEX_LOAD, BC_LEX_OP_BOOL_OR, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KW_PRINT, BC_LEX_KW_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID, @@ -898,21 +906,21 @@ const uchar dc_parse_insts[] = { BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED BC_INST_IBASE, BC_INST_OBASE, BC_INST_SCALE, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_SEED, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_LENGTH, BC_INST_PRINT, BC_INST_SQRT, BC_INST_ABS, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_IRAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_QUIT, BC_INST_INVALID, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_RAND, -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_MAXIBASE, BC_INST_MAXOBASE, BC_INST_MAXSCALE, -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_MAXRAND, #endif // BC_ENABLE_EXTRA_MATH BC_INST_INVALID, @@ -945,6 +953,7 @@ const BcDig bc_num_bigdigMax[] = { const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig); +const char bc_parse_zero[] = "0"; const char bc_parse_one[] = "1"; const char bc_num_hex_digits[] = "0123456789ABCDEF"; diff --git a/src/dc/dc.c b/src/dc/dc.c index 0e0774b5322a..21d7bfbd4385 100644 --- a/src/dc/dc.c +++ b/src/dc/dc.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/dc/lex.c b/src/dc/lex.c index 663a828dfe7c..b17f01bc990d 100644 --- a/src/dc/lex.c +++ b/src/dc/lex.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/dc/parse.c b/src/dc/parse.c index 9ec746b96f7f..86edc5f66505 100644 --- a/src/dc/parse.c +++ b/src/dc/parse.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -230,7 +230,7 @@ void dc_parse_parse(BcParse *p) { exit: BC_SIG_MAYLOCK; - if (BC_ERR(vm.status)) bc_parse_reset(p); + if (BC_ERR(vm.status || vm.sig)) bc_parse_reset(p); BC_LONGJMP_CONT; } #endif // DC_ENABLED diff --git a/src/file.c b/src/file.c index ce878a018ca5..01997399f452 100644 --- a/src/file.c +++ b/src/file.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/history/history.c b/src/history/history.c index ad917e65ba08..b94fbb7b3fdf 100644 --- a/src/history/history.c +++ b/src/history/history.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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,8 +47,6 @@ * Copyright (c) 2010-2016, Salvatore Sanfilippo * Copyright (c) 2010-2013, Pieter Noordhuis * - * All rights reserved. - * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -482,15 +480,17 @@ static void bc_history_enableRaw(BcHistory *h) { static void bc_history_disableRaw(BcHistory *h) { + sig_atomic_t lock; + // Don't even check the return value as it's too late. if (!h->rawMode) return; - BC_SIG_LOCK; + BC_SIG_TRYLOCK(lock); if (BC_ERR(tcsetattr(STDIN_FILENO, TCSAFLUSH, &h->orig_termios) != -1)) h->rawMode = false; - BC_SIG_UNLOCK; + BC_SIG_TRYUNLOCK(lock); } /** diff --git a/src/lang.c b/src/lang.c index 6959af80fbfe..bd287c75ee78 100644 --- a/src/lang.c +++ b/src/lang.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -96,37 +96,41 @@ void bc_func_init(BcFunc *f, const char *name) { bc_vec_init(&f->code, sizeof(uchar), NULL); - // This is necessary for not allocating memory where it isn't used. - // dc does not use strings except in the main function. The else part - // is necessary to stop uninitiazed data errors in valgrind. - if (BC_IS_BC || !strcmp(name, bc_func_main)) - bc_vec_init(&f->strs, sizeof(char*), bc_string_free); -#if BC_ENABLE_FUNC_FREE - else bc_vec_clear(&f->strs); -#endif // BC_ENABLE_FUNC_FREE - bc_vec_init(&f->consts, sizeof(BcConst), bc_const_free); + #if BC_ENABLED if (BC_IS_BC) { + + bc_vec_init(&f->strs, sizeof(char*), bc_string_free); + bc_vec_init(&f->autos, sizeof(BcLoc), NULL); bc_vec_init(&f->labels, sizeof(size_t), NULL); + f->nparams = 0; f->voidfn = false; } #endif // BC_ENABLED + f->name = name; } void bc_func_reset(BcFunc *f) { + BC_SIG_ASSERT_LOCKED; assert(f != NULL); + bc_vec_npop(&f->code, f->code.len); - bc_vec_npop(&f->strs, f->strs.len); + bc_vec_npop(&f->consts, f->consts.len); + #if BC_ENABLED if (BC_IS_BC) { + + bc_vec_npop(&f->strs, f->strs.len); + bc_vec_npop(&f->autos, f->autos.len); bc_vec_npop(&f->labels, f->labels.len); + f->nparams = 0; f->voidfn = false; } @@ -134,17 +138,24 @@ void bc_func_reset(BcFunc *f) { } void bc_func_free(void *func) { + #if BC_ENABLE_FUNC_FREE BcFunc *f = (BcFunc*) func; + BC_SIG_ASSERT_LOCKED; assert(f != NULL); + bc_vec_free(&f->code); - bc_vec_free(&f->strs); + bc_vec_free(&f->consts); + #if BC_ENABLED #ifndef NDEBUG if (BC_IS_BC) { + + bc_vec_free(&f->strs); + bc_vec_free(&f->autos); bc_vec_free(&f->labels); } @@ -245,13 +256,13 @@ void bc_result_copy(BcResult *d, BcResult *src) { break; } - case BC_RESULT_CONSTANT: case BC_RESULT_STR: { memcpy(&d->d.n, &src->d.n, sizeof(BcNum)); break; } + case BC_RESULT_ZERO: case BC_RESULT_ONE: { // Do nothing. @@ -299,7 +310,7 @@ void bc_result_free(void *result) { #endif // BC_ENABLED case BC_RESULT_ARRAY_ELEM: case BC_RESULT_STR: - case BC_RESULT_CONSTANT: + case BC_RESULT_ZERO: case BC_RESULT_ONE: #if BC_ENABLED case BC_RESULT_VOID: diff --git a/src/lex.c b/src/lex.c index 8bbc694c161f..2b705c8bc71b 100644 --- a/src/lex.c +++ b/src/lex.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/main.c b/src/main.c index 68941c5e24a5..7e5e2905cf75 100644 --- a/src/main.c +++ b/src/main.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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/src/num.c b/src/num.c index ac255295e970..05b4654f21f5 100644 --- a/src/num.c +++ b/src/num.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -2012,7 +2012,6 @@ void bc_num_init(BcNum *restrict n, size_t req) { if (req == BC_NUM_DEF_SIZE && vm.temps.len) { BcNum *nptr = bc_vec_top(&vm.temps); num = nptr->num; - req = nptr->cap; bc_vec_pop(&vm.temps); } else num = bc_vm_malloc(BC_NUM_SIZE(req)); @@ -2184,7 +2183,7 @@ void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val) { n->len = i; } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND void bc_num_rng(const BcNum *restrict n, BcRNG *rng) { BcNum pow, temp, temp2, intn, frac; @@ -2465,7 +2464,7 @@ void bc_num_irand(const BcNum *restrict a, BcNum *restrict b, bc_num_free(&cp); BC_LONGJMP_CONT; } -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND size_t bc_num_addReq(const BcNum *a, const BcNum *b, size_t scale) { diff --git a/src/opt.c b/src/opt.c index 730b1cd51f19..3a01a2657f15 100644 --- a/src/opt.c +++ b/src/opt.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -102,7 +102,7 @@ static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) { case BC_OPT_BC_ONLY: case BC_OPT_DC_ONLY: { - if (type == -1 || (type == BC_OPT_BC_ONLY && !BC_IS_BC) || + if (type == -1 || (type == BC_OPT_BC_ONLY && BC_IS_DC) || (type == BC_OPT_DC_ONLY && BC_IS_BC)) { char str[2] = {0, 0}; @@ -212,7 +212,7 @@ int bc_opt_parse(BcOpt *o, const BcOptLong *longopts) { o->optopt = longopts[i].val; arg = bc_opt_longoptsArg(option); - if ((longopts[i].type == BC_OPT_BC_ONLY && !BC_IS_BC) || + if ((longopts[i].type == BC_OPT_BC_ONLY && BC_IS_DC) || (longopts[i].type == BC_OPT_DC_ONLY && BC_IS_BC)) { bc_opt_error(BC_ERROR_FATAL_OPTION, o->optopt, name); diff --git a/src/parse.c b/src/parse.c index 5d35fe66d3b6..a48f5807e9ce 100644 --- a/src/parse.c +++ b/src/parse.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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,25 +64,20 @@ static void bc_parse_update(BcParse *p, uchar inst, size_t idx) { void bc_parse_addString(BcParse *p) { - BcFunc *f = BC_IS_BC ? p->func : bc_vec_item(&p->prog->fns, BC_PROG_MAIN); + BcVec *strs = BC_IS_BC ? &p->func->strs : p->prog->strs; size_t idx; BC_SIG_LOCK; if (BC_IS_BC) { const char *str = bc_vm_strdup(p->l.str.v); - idx = f->strs.len; - bc_vec_push(&f->strs, &str); + idx = strs->len; + bc_vec_push(strs, &str); } #if DC_ENABLED else idx = bc_program_insertFunc(p->prog, p->l.str.v) - BC_PROG_REQ_FUNCS; #endif // DC_ENABLED -#ifndef NDEBUG - f = BC_IS_BC ? p->func : bc_vec_item(&p->prog->fns, BC_PROG_MAIN); - assert(f->strs.len > idx); -#endif // NDEBUG - bc_parse_update(p, BC_INST_STR, idx); BC_SIG_UNLOCK; @@ -90,16 +85,20 @@ void bc_parse_addString(BcParse *p) { static void bc_parse_addNum(BcParse *p, const char *string) { - BcFunc *f = BC_IS_BC ? p->func : bc_vec_item(&p->prog->fns, BC_PROG_MAIN); + BcVec *consts = &p->func->consts; size_t idx; BcConst c; + if (bc_parse_zero[0] == string[0] && bc_parse_zero[1] == string[1]) { + bc_parse_push(p, BC_INST_ZERO); + return; + } if (bc_parse_one[0] == string[0] && bc_parse_one[1] == string[1]) { bc_parse_push(p, BC_INST_ONE); return; } - idx = f->consts.len; + idx = consts->len; BC_SIG_LOCK; @@ -107,7 +106,7 @@ static void bc_parse_addNum(BcParse *p, const char *string) { c.base = BC_NUM_BIGDIG_MAX; bc_num_clear(&c.num); - bc_vec_push(&f->consts, &c); + bc_vec_push(consts, &c); bc_parse_update(p, BC_INST_NUM, idx); diff --git a/src/program.c b/src/program.c index 8f2270f5e71d..1a8176c76f96 100644 --- a/src/program.c +++ b/src/program.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -52,10 +52,10 @@ static void bc_program_addFunc(BcProgram *p, BcFunc *f, BcId *id_ptr); static inline void bc_program_setVecs(BcProgram *p, BcFunc *f) { p->consts = &f->consts; - p->strs = &f->strs; + if (BC_IS_BC) p->strs = &f->strs; } -static void bc_program_type_num(BcResult *r, BcNum *n) { +static inline void bc_program_type_num(BcResult *r, BcNum *n) { #if BC_ENABLED assert(r->t != BC_RESULT_VOID); @@ -68,7 +68,7 @@ static void bc_program_type_num(BcResult *r, BcNum *n) { static void bc_program_type_match(BcResult *r, BcType t) { #if DC_ENABLED - assert(!BC_IS_BC || BC_NO_ERR(r->t != BC_RESULT_STR)); + assert(BC_IS_DC || BC_NO_ERR(r->t != BC_RESULT_STR)); #endif // DC_ENABLED if (BC_ERR((r->t != BC_RESULT_ARRAY) != (!t))) @@ -89,6 +89,7 @@ static size_t bc_program_index(const char *restrict code, size_t *restrict bgn) return res; } +#if BC_ENABLED static void bc_program_prepGlobals(BcProgram *p) { size_t i; @@ -96,9 +97,9 @@ static void bc_program_prepGlobals(BcProgram *p) { for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) bc_vec_push(p->globals_v + i, p->globals + i); -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_rand_push(&p->rng); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND } static void bc_program_popGlobals(BcProgram *p, bool reset) { @@ -111,10 +112,11 @@ static void bc_program_popGlobals(BcProgram *p, bool reset) { p->globals[i] = BC_PROG_GLOBAL(v); } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_rand_pop(&p->rng, reset); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND } +#endif // BC_ENABLED static void bc_program_pushBigdig(BcProgram *p, BcBigDig dig, BcResultType type) { @@ -182,38 +184,6 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { switch (r->t) { - case BC_RESULT_CONSTANT: - { - BcConst *c = bc_vec_item(p->consts, r->d.loc.loc); - BcBigDig base = BC_PROG_IBASE(p); - - if (c->base != base) { - - if (c->num.num == NULL) { - BC_SIG_LOCK; - bc_num_init(&c->num, BC_NUM_RDX(strlen(c->val))); - BC_SIG_UNLOCK; - } - - // bc_num_parse() should only do operations that cannot fail. - bc_num_parse(&c->num, c->val, base, !c->val[1]); - - c->base = base; - } - - BC_SIG_LOCK; - - n = &r->d.n; - - r->t = BC_RESULT_TEMP; - - bc_num_createCopy(n, &c->num); - - BC_SIG_UNLOCK; - - break; - } - case BC_RESULT_STR: case BC_RESULT_TEMP: case BC_RESULT_IBASE: @@ -263,6 +233,12 @@ static BcNum* bc_program_num(BcProgram *p, BcResult *r) { break; } + case BC_RESULT_ZERO: + { + n = &p->zero; + break; + } + case BC_RESULT_ONE: { n = &p->one; @@ -308,7 +284,7 @@ static void bc_program_binPrep(BcProgram *p, BcResult **l, BcNum **ln, assert(p != NULL && l != NULL && ln != NULL && r != NULL && rn != NULL); #ifndef BC_PROG_NO_STACK_CHECK - if (!BC_IS_BC) { + if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 2))) bc_vm_err(BC_ERROR_EXEC_STACK); } @@ -346,7 +322,7 @@ static void bc_program_assignPrep(BcProgram *p, BcResult **l, BcNum **ln, { BcResultType lt, min; - min = BC_RESULT_CONSTANT - ((unsigned int) (BC_IS_BC << 1)); + min = BC_RESULT_TEMP - ((unsigned int) (BC_IS_BC)); bc_program_binPrep(p, l, ln, r, rn, 0); @@ -356,7 +332,7 @@ static void bc_program_assignPrep(BcProgram *p, BcResult **l, BcNum **ln, bc_vm_err(BC_ERROR_EXEC_TYPE); #if DC_ENABLED - if(!BC_IS_BC) { + if(BC_IS_DC) { bool good = (((*r)->t == BC_RESULT_STR || BC_PROG_STR(*rn)) && lt <= BC_RESULT_ARRAY_ELEM); @@ -373,7 +349,7 @@ 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 - if (!BC_IS_BC) { + if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) bc_vm_err(BC_ERROR_EXEC_STACK); } @@ -400,6 +376,33 @@ static BcResult* bc_program_prepResult(BcProgram *p) { return bc_vec_top(&p->results); } +static void bc_program_const(BcProgram *p, const char *code, size_t *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); + + if (c->base != base) { + + if (c->num.num == NULL) { + BC_SIG_LOCK; + bc_num_init(&c->num, BC_NUM_RDX(strlen(c->val))); + BC_SIG_UNLOCK; + } + + // bc_num_parse() should only do operations that cannot fail. + bc_num_parse(&c->num, c->val, base, !c->val[1]); + + c->base = base; + } + + BC_SIG_LOCK; + + bc_num_createCopy(&r->d.n, &c->num); + + BC_SIG_UNLOCK; +} + static void bc_program_op(BcProgram *p, uchar inst) { BcResult *opd1, *opd2, *res; @@ -459,7 +462,9 @@ static void bc_program_read(BcProgram *p) { if (BC_ERR(parse.l.t != BC_LEX_NLINE && parse.l.t != BC_LEX_EOF)) bc_vm_err(BC_ERROR_EXEC_READ_EXPR); +#if BC_ENABLED if (BC_G) bc_program_prepGlobals(p); +#endif // BC_ENABLED ip.func = BC_PROG_READ; ip.idx = 0; @@ -470,8 +475,9 @@ static void bc_program_read(BcProgram *p) { bc_vec_pushByte(&f->code, vm.read_ret); bc_vec_push(&p->stack, &ip); + #if DC_ENABLED - if (!BC_IS_BC) { + if (BC_IS_DC) { size_t temp = 0; bc_vec_push(&p->tail_calls, &temp); } @@ -485,12 +491,12 @@ static void bc_program_read(BcProgram *p) { BC_LONGJMP_CONT; } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_rand(BcProgram *p) { BcRand rand = bc_rand_int(&p->rng); bc_program_pushBigdig(p, (BcBigDig) rand, BC_RESULT_TEMP); } -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_printChars(const char *str) { @@ -510,7 +516,7 @@ static void bc_program_printString(const char *restrict str) { size_t i, len = strlen(str); #if DC_ENABLED - if (!len && !BC_IS_BC) { + if (!len && BC_IS_DC) { bc_vm_putchar('\0'); return; } @@ -552,7 +558,7 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { assert(p != NULL); #ifndef BC_PROG_NO_STACK_CHECK - if (!BC_IS_BC) { + if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) bc_vm_err(BC_ERROR_EXEC_STACK); } @@ -560,9 +566,6 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { assert(BC_PROG_STACK(&p->results, idx + 1)); - assert(BC_IS_BC || - p->strs == &((BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN))->strs); - r = bc_vec_item_rev(&p->results, idx); #if BC_ENABLED @@ -586,6 +589,7 @@ static void bc_program_print(BcProgram *p, uchar inst, size_t idx) { size_t i = (r->t == BC_RESULT_STR) ? r->d.loc.loc : n->scale; + bc_file_flush(&vm.fout); str = *((char**) bc_vec_item(p->strs, i)); if (inst == BC_INST_PRINT_STR) bc_program_printChars(str); @@ -736,7 +740,7 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, bool var = (t == BC_TYPE_VAR); #if DC_ENABLED - if (!BC_IS_BC) { + if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); @@ -763,7 +767,7 @@ static void bc_program_copyToVar(BcProgram *p, size_t idx, vec = bc_program_vec(p, idx, t); #if DC_ENABLED - if (ptr->t == BC_RESULT_STR) { + if (BC_IS_DC && (ptr->t == BC_RESULT_STR || BC_PROG_STR(n))) { if (BC_ERR(!var)) bc_vm_err(BC_ERROR_EXEC_TYPE); bc_program_assignStr(p, ptr, vec, true); return; @@ -839,7 +843,7 @@ static void bc_program_assign(BcProgram *p, uchar inst) { if (right->t == BC_RESULT_STR || BC_PROG_STR(r)) { - size_t idx = right->d.loc.loc; + size_t idx = right->t == BC_RESULT_STR ? right->d.loc.loc : r->scale; if (left->t == BC_RESULT_ARRAY_ELEM) { BC_SIG_LOCK; @@ -891,7 +895,7 @@ static void bc_program_assign(BcProgram *p, uchar inst) { } else { min = BC_NUM_MIN_BASE; - if (BC_ENABLE_EXTRA_MATH && ob && (!BC_IS_BC || !BC_IS_POSIX)) + if (BC_ENABLE_EXTRA_MATH && ob && (BC_IS_DC || !BC_IS_POSIX)) min = 0; max = vm.maxes[ob + BC_PROG_GLOBALS_IBASE]; v = p->globals_v + BC_PROG_GLOBALS_IBASE + ob; @@ -904,9 +908,9 @@ static void bc_program_assign(BcProgram *p, uchar inst) { *ptr = val; *ptr_t = val; } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND else if (left->t == BC_RESULT_SEED) bc_num_rng(l, &p->rng); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_SIG_LOCK; @@ -931,7 +935,7 @@ static void bc_program_pushVar(BcProgram *p, const char *restrict code, r.d.loc.loc = idx; #if DC_ENABLED - if (!BC_IS_BC && (pop || copy)) { + if (BC_IS_DC && (pop || copy)) { BcVec *v = bc_program_vec(p, idx, BC_TYPE_VAR); BcNum *num = bc_vec_top(v); @@ -989,8 +993,13 @@ static void bc_program_pushArray(BcProgram *p, const char *restrict code, r.t = BC_RESULT_ARRAY_ELEM; r.d.loc.idx = (size_t) temp; + + BC_SIG_LOCK; + bc_vec_pop(&p->results); bc_vec_push(&p->results, &r); + + BC_SIG_UNLOCK; } #if BC_ENABLED @@ -1160,14 +1169,14 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { BcNum *num; bool len = (inst == BC_INST_LENGTH); -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND assert(inst >= BC_INST_LENGTH && inst <= BC_INST_IRAND); -#else // BC_ENABLE_EXTRA_MATH +#else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND assert(inst >= BC_INST_LENGTH && inst <= BC_INST_ABS); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #ifndef BC_PROG_NO_STACK_CHECK - if (!BC_IS_BC) { + if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); } @@ -1196,7 +1205,7 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { res->d.n.neg = false; } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND else if (inst == BC_INST_IRAND) { BC_SIG_LOCK; @@ -1207,7 +1216,7 @@ static void bc_program_builtin(BcProgram *p, uchar inst) { bc_num_irand(num, &res->d.n, &p->rng); } -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND else { BcBigDig val = 0; @@ -1582,7 +1591,7 @@ static void bc_program_pushGlobal(BcProgram *p, uchar inst) { bc_program_pushBigdig(p, p->globals[inst - BC_INST_IBASE], t); } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_pushSeed(BcProgram *p) { BcResult *res; @@ -1598,7 +1607,7 @@ static void bc_program_pushSeed(BcProgram *p) { bc_num_createFromRNG(&res->d.n, &p->rng); } -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_addFunc(BcProgram *p, BcFunc *f, BcId *id_ptr) { @@ -1610,11 +1619,10 @@ static void bc_program_addFunc(BcProgram *p, BcFunc *f, BcId *id_ptr) { bc_vec_push(&p->fns, f); // This is to make sure pointers are updated if the array was moved. - if (BC_IS_BC && p->stack.len) { - ip = bc_vec_item_rev(&p->stack, 0); + if (p->stack.len) { + ip = bc_vec_top(&p->stack); bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, ip->func)); } - else bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN)); } size_t bc_program_insertFunc(BcProgram *p, const char *name) { @@ -1643,9 +1651,7 @@ size_t bc_program_insertFunc(BcProgram *p, const char *name) { bc_program_addFunc(p, &f, id_ptr); #if DC_ENABLED - if (!BC_IS_BC && strcmp(name, bc_func_main) && - strcmp(name, bc_func_read)) - { + if (BC_IS_DC && idx >= BC_PROG_REQ_FUNCS) { bc_vec_push(p->strs, &id_ptr->name); assert(p->strs->len == p->fns.len - BC_PROG_REQ_FUNCS); } @@ -1679,12 +1685,15 @@ void bc_program_free(BcProgram *p) { if (BC_IS_BC) bc_num_free(&p->last); #endif // BC_ENABLED -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_rand_free(&p->rng); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #if DC_ENABLED - if (!BC_IS_BC) bc_vec_free(&p->tail_calls); + if (BC_IS_DC) { + bc_vec_free(&p->tail_calls); + bc_vec_free(&p->strs_v); + } #endif // DC_ENABLED } #endif // NDEBUG @@ -1710,7 +1719,10 @@ void bc_program_init(BcProgram *p) { } #if DC_ENABLED - if (!BC_IS_BC) { + if (BC_IS_DC) { + + bc_vec_init(&p->strs_v, sizeof(char*), bc_string_free); + p->strs = &p->strs_v; bc_vec_init(&p->tail_calls, sizeof(size_t), NULL); i = 0; @@ -1722,10 +1734,12 @@ void bc_program_init(BcProgram *p) { } #endif // DC_ENABLED -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND srand((unsigned int) time(NULL)); bc_rand_init(&p->rng); -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND + + bc_num_setup(&p->zero, p->zero_num, BC_PROG_ONE_CAP); bc_num_setup(&p->one, p->one_num, BC_PROG_ONE_CAP); bc_num_one(&p->one); @@ -1748,6 +1762,10 @@ void bc_program_init(BcProgram *p) { bc_vec_init(&p->results, sizeof(BcResult), bc_result_free); bc_vec_init(&p->stack, sizeof(BcInstPtr), NULL); bc_vec_push(&p->stack, &ip); + + bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN)); + + assert(p->consts != NULL && p->strs != NULL); } void bc_program_reset(BcProgram *p) { @@ -1760,11 +1778,13 @@ void bc_program_reset(BcProgram *p) { bc_vec_npop(&p->stack, p->stack.len - 1); bc_vec_npop(&p->results, p->results.len); +#if BC_ENABLED if (BC_G) bc_program_popGlobals(p, true); +#endif // BC_ENABLED f = bc_vec_item(&p->fns, BC_PROG_MAIN); ip = bc_vec_top(&p->stack); - if (BC_IS_BC) bc_program_setVecs(p, f); + bc_program_setVecs(p, f); ip->idx = f->code.len; if (vm.sig) { @@ -1779,7 +1799,7 @@ void bc_program_exec(BcProgram *p) { size_t idx; BcResult r, *ptr; BcInstPtr *ip = bc_vec_top(&p->stack); - BcFunc *func = bc_vec_item(&p->fns, ip->func); + BcFunc *func = (BcFunc*) bc_vec_item(&p->fns, ip->func); char *code = func->code.v; bool cond = false; #if BC_ENABLED @@ -1793,8 +1813,7 @@ void bc_program_exec(BcProgram *p) { jmp_bufs_len = vm.jmp_bufs.len; #endif // NDEBUG - if (BC_IS_BC) bc_program_setVecs(p, func); - else bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN)); + bc_program_setVecs(p, func); while (ip->idx < func->code.len) { @@ -1867,7 +1886,7 @@ void bc_program_exec(BcProgram *p) { func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - if (BC_IS_BC) bc_program_setVecs(p, func); + bc_program_setVecs(p, func); break; } @@ -1894,25 +1913,25 @@ void bc_program_exec(BcProgram *p) { func = bc_vec_item(&p->fns, ip->func); code = func->code.v; - if (BC_IS_BC) bc_program_setVecs(p, func); + bc_program_setVecs(p, func); break; } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_RAND: { bc_program_rand(p); break; } -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_MAXIBASE: case BC_INST_MAXOBASE: case BC_INST_MAXSCALE: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_MAXRAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { BcBigDig dig = vm.maxes[inst - BC_INST_MAXIBASE]; bc_program_pushBigdig(p, dig, BC_RESULT_TEMP); @@ -1942,21 +1961,21 @@ void bc_program_exec(BcProgram *p) { break; } -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_SEED: { bc_program_pushSeed(p); break; } -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_LENGTH: case BC_INST_SCALE_FUNC: case BC_INST_SQRT: case BC_INST_ABS: -#if BC_ENABLE_EXTRA_MATH +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_IRAND: -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { bc_program_builtin(p, inst); break; @@ -1964,18 +1983,17 @@ void bc_program_exec(BcProgram *p) { case BC_INST_NUM: { - r.t = BC_RESULT_CONSTANT; - r.d.loc.loc = bc_program_index(code, &ip->idx); - bc_vec_push(&p->results, &r); + bc_program_const(p, code, &ip->idx); break; } + case BC_INST_ZERO: case BC_INST_ONE: #if BC_ENABLED case BC_INST_LAST: #endif // BC_ENABLED { - r.t = BC_RESULT_ONE + (inst - BC_INST_ONE); + r.t = BC_RESULT_ZERO + (inst - BC_INST_ZERO); bc_vec_push(&p->results, &r); break; } @@ -2077,6 +2095,7 @@ void bc_program_exec(BcProgram *p) { ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; + bc_program_setVecs(p, func); break; } @@ -2100,6 +2119,7 @@ void bc_program_exec(BcProgram *p) { ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; + bc_program_setVecs(p, func); break; } @@ -2164,6 +2184,7 @@ void bc_program_exec(BcProgram *p) { ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; + bc_program_setVecs(p, func); break; } @@ -2195,6 +2216,7 @@ void bc_program_exec(BcProgram *p) { ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; + bc_program_setVecs(p, func); break; } #endif // DC_ENABLED diff --git a/src/rand/rand.c b/src/rand/rand.c index aa589bbd533d..b16061d711a1 100644 --- a/src/rand/rand.c +++ b/src/rand/rand.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2019 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2019 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,8 +66,6 @@ * */ -#if BC_ENABLE_EXTRA_MATH - #include #include #include @@ -80,6 +78,8 @@ #include #include +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND + #if !BC_RAND_BUILTIN static BcRandState bc_rand_addition(uint_fast64_t a, uint_fast64_t b) { @@ -412,4 +412,4 @@ void bc_rand_free(BcRNG *r) { } #endif // NDEBUG -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND diff --git a/src/read.c b/src/read.c index c63952523181..6886a7e13602 100644 --- a/src/read.c +++ b/src/read.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -61,29 +61,29 @@ static bool bc_read_binary(const char *buf, size_t size) { return false; } -static bool bc_read_buf(BcVec *vec) { +bool bc_read_buf(BcVec *vec, char *buf, size_t *buf_len) { char *nl; - if (!vm.buf_len) return false; + if (!*buf_len) return false; - nl = strchr(vm.buf, '\n'); + nl = strchr(buf, '\n'); if (nl != NULL) { - size_t nllen = (size_t) ((nl + 1) - vm.buf); + size_t nllen = (size_t) ((nl + 1) - buf); - nllen = vm.buf_len >= nllen ? nllen : vm.buf_len; + nllen = *buf_len >= nllen ? nllen : *buf_len; - bc_vec_npush(vec, nllen, vm.buf); - vm.buf_len -= nllen; - memmove(vm.buf, nl + 1, vm.buf_len); + bc_vec_npush(vec, nllen, buf); + *buf_len -= nllen; + memmove(buf, nl + 1, *buf_len + 1); return true; } - bc_vec_npush(vec, vm.buf_len, vm.buf); - vm.buf_len = 0; + bc_vec_npush(vec, *buf_len, buf); + *buf_len = 0; return false; } @@ -105,7 +105,7 @@ BcStatus bc_read_chars(BcVec *vec, const char *prompt) { } #endif // BC_ENABLE_PROMPT - if (bc_read_buf(vec)) { + if (bc_read_buf(vec, vm.buf, &vm.buf_len)) { bc_vec_pushByte(vec, '\0'); return BC_STATUS_SUCCESS; } @@ -154,8 +154,9 @@ BcStatus bc_read_chars(BcVec *vec, const char *prompt) { } vm.buf_len += (size_t) r; + vm.buf[vm.buf_len] = '\0'; - done = bc_read_buf(vec); + done = bc_read_buf(vec, vm.buf, &vm.buf_len); } bc_vec_pushByte(vec, '\0'); diff --git a/src/vector.c b/src/vector.c index 28c7440693eb..f45bcb198a25 100644 --- a/src/vector.c +++ b/src/vector.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -86,20 +86,19 @@ void bc_vec_expand(BcVec *restrict v, size_t req) { void bc_vec_npop(BcVec *restrict v, size_t n) { + sig_atomic_t lock; + assert(v != NULL && n <= v->len); + BC_SIG_TRYLOCK(lock); + if (v->dtor == NULL) v->len -= n; else { - - sig_atomic_t lock; size_t len = v->len - n; - - BC_SIG_TRYLOCK(lock); - while (v->len > len) v->dtor(v->v + (v->size * --v->len)); - - BC_SIG_TRYUNLOCK(lock); } + + BC_SIG_TRYUNLOCK(lock); } void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx) { @@ -112,26 +111,35 @@ void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx) { ptr = bc_vec_item(v, idx); data = bc_vec_item(v, idx + n); + BC_SIG_LOCK; + if (v->dtor != NULL) { size_t i; - BC_SIG_LOCK; - for (i = 0; i < n; ++i) v->dtor(bc_vec_item(v, idx + i)); - - BC_SIG_UNLOCK; } v->len -= n; memmove(ptr, data, (v->len - idx) * v->size); + + BC_SIG_UNLOCK; } void bc_vec_npush(BcVec *restrict v, size_t n, const void *data) { + + sig_atomic_t lock; + assert(v != NULL && data != NULL); + + BC_SIG_TRYLOCK(lock); + if (v->len + n > v->cap) bc_vec_grow(v, n); + memcpy(v->v + (v->size * v->len), data, v->size * n); v->len += n; + + BC_SIG_TRYUNLOCK(lock); } inline void bc_vec_push(BcVec *restrict v, const void *data) { @@ -140,32 +148,35 @@ inline void bc_vec_push(BcVec *restrict v, const void *data) { void bc_vec_pushByte(BcVec *restrict v, uchar data) { assert(v != NULL && v->size == sizeof(uchar)); - if (v->len == v->cap) bc_vec_grow(v, 1); - v->v[v->len] = (char) data; - v->len += 1; + bc_vec_npush(v, 1, &data); } void bc_vec_pushIndex(BcVec *restrict v, size_t idx) { - uchar amt, nums[sizeof(size_t)]; + uchar amt, nums[sizeof(size_t) + 1]; assert(v != NULL); assert(v->size == sizeof(uchar)); for (amt = 0; idx; ++amt) { - nums[amt] = (uchar) idx; + nums[amt + 1] = (uchar) idx; idx &= ((size_t) ~(UCHAR_MAX)); idx >>= sizeof(uchar) * CHAR_BIT; } - bc_vec_push(v, &amt); - bc_vec_npush(v, amt, nums); + nums[0] = amt; + + bc_vec_npush(v, amt + 1, nums); } static void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx) { + sig_atomic_t lock; + assert(v != NULL && data != NULL && idx <= v->len); + BC_SIG_TRYLOCK(lock); + if (idx == v->len) bc_vec_push(v, data); else { @@ -178,40 +189,62 @@ static void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx) { memmove(ptr + v->size, ptr, v->size * (v->len++ - idx)); memmove(ptr, data, v->size); } + + BC_SIG_TRYUNLOCK(lock); } void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str) { + sig_atomic_t lock; + assert(v != NULL && v->size == sizeof(char)); assert(v->dtor == NULL); assert(!v->len || !v->v[v->len - 1]); assert(v->v != str); + BC_SIG_TRYLOCK(lock); + bc_vec_npop(v, v->len); bc_vec_expand(v, bc_vm_growSize(len, 1)); memcpy(v->v, str, len); v->len = len; bc_vec_pushByte(v, '\0'); + + BC_SIG_TRYUNLOCK(lock); } void bc_vec_concat(BcVec *restrict v, const char *restrict str) { + sig_atomic_t lock; + assert(v != NULL && v->size == sizeof(char)); assert(v->dtor == NULL); assert(!v->len || !v->v[v->len - 1]); assert(v->v != str); + BC_SIG_TRYLOCK(lock); + if (v->len) v->len -= 1; bc_vec_npush(v, strlen(str) + 1, str); + + BC_SIG_TRYUNLOCK(lock); } void bc_vec_empty(BcVec *restrict v) { + + sig_atomic_t lock; + assert(v != NULL && v->size == sizeof(char)); assert(v->dtor == NULL); + + BC_SIG_TRYLOCK(lock); + bc_vec_npop(v, v->len); bc_vec_pushByte(v, '\0'); + + BC_SIG_TRYUNLOCK(lock); } #if BC_ENABLE_HISTORY @@ -242,6 +275,7 @@ inline void* bc_vec_item_rev(const BcVec *restrict v, size_t idx) { } inline void bc_vec_clear(BcVec *restrict v) { + BC_SIG_ASSERT_LOCKED; v->v = NULL; v->len = 0; v->dtor = NULL; diff --git a/src/vm.c b/src/vm.c index d569cc70a008..b3dee16b2e28 100644 --- a/src/vm.c +++ b/src/vm.c @@ -1,9 +1,9 @@ /* * ***************************************************************************** * - * Copyright (c) 2018-2020 Gavin D. Howard and contributors. + * SPDX-License-Identifier: BSD-2-Clause * - * All rights reserved. + * Copyright (c) 2018-2020 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: @@ -69,7 +69,7 @@ BC_NORETURN void bc_vm_jmp(const char* f) { BC_NORETURN void bc_vm_jmp(void) { #endif - assert(vm.status != BC_STATUS_SUCCESS || vm.sig); + assert(BC_SIG_EXC); BC_SIG_MAYLOCK; @@ -191,11 +191,13 @@ void bc_vm_error(BcError e, size_t line, ...) { bc_file_putchar(&vm.ferr, ' '); bc_file_puts(&vm.ferr, f->name); +#if BC_ENABLED if (BC_IS_BC && ip->func != BC_PROG_MAIN && ip->func != BC_PROG_READ) { bc_file_puts(&vm.ferr, "()"); } +#endif // BC_ENABLED } } @@ -327,14 +329,14 @@ void bc_vm_shutdown(void) { bc_file_free(&vm.ferr); } -size_t bc_vm_arraySize(size_t n, size_t size) { +inline size_t bc_vm_arraySize(size_t n, size_t size) { size_t res = n * size; if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size))) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return res; } -size_t bc_vm_growSize(size_t a, size_t b) { +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 || res < b)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); @@ -402,11 +404,10 @@ void bc_vm_putchar(int c) { static void bc_vm_clean(void) { - BcProgram *prog = &vm.prog; - BcVec *fns = &prog->fns; + BcVec *fns = &vm.prog.fns; BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN); - BcInstPtr *ip = bc_vec_item(&prog->stack, 0); - bool good = (vm.status && vm.status != BC_STATUS_QUIT); + BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0); + bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig); if (good) bc_program_reset(&vm.prog); @@ -415,53 +416,38 @@ static void bc_vm_clean(void) { #endif // BC_ENABLED #if DC_ENABLED - if (!BC_IS_BC) { + if (BC_IS_DC) { size_t i; - for (i = 0; i < vm.prog.vars.len; ++i) { - BcVec *arr = bc_vec_item(&vm.prog.vars, i); - BcNum *n = bc_vec_top(arr); - if (arr->len != 1 || BC_PROG_STR(n)) break; - } + good = true; - if (i == vm.prog.vars.len) { - - for (i = 0; i < vm.prog.arrs.len; ++i) { - - BcVec *arr = bc_vec_item(&vm.prog.arrs, i); - size_t j; - - assert(arr->len == 1); - - arr = bc_vec_top(arr); - - for (j = 0; j < arr->len; ++j) { - BcNum *n = bc_vec_item(arr, j); - if (BC_PROG_STR(n)) break; - } - - if (j != arr->len) break; - } - - good = (i == vm.prog.arrs.len); + 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); } } #endif // DC_ENABLED // If this condition is true, we can get rid of strings, // constants, and code. This is an idea from busybox. - if (good && prog->stack.len == 1 && !prog->results.len && - ip->idx == f->code.len) - { + if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) { + #if BC_ENABLED if (BC_IS_BC) { bc_vec_npop(&f->labels, f->labels.len); bc_vec_npop(&f->strs, f->strs.len); + bc_vec_npop(&f->consts, f->consts.len); } #endif // BC_ENABLED - bc_vec_npop(&f->consts, f->consts.len); + +#if DC_ENABLED + // Note to self: you cannot delete strings and functions. Deal with it. + if (BC_IS_DC) bc_vec_npop(vm.prog.consts, vm.prog.consts->len); +#endif // DC_ENABLED + bc_vec_npop(&f->code, f->code.len); + ip->idx = 0; } } @@ -494,6 +480,9 @@ static void bc_vm_process(const char *text, bool is_stdin) { #endif // BC_ENABLED bc_program_exec(&vm.prog); + + assert(BC_IS_DC || vm.prog.results.len == 0); + if (BC_I) bc_file_flush(&vm.fout); } while (vm.prs.l.t != BC_LEX_EOF); @@ -604,6 +593,7 @@ static void bc_vm_stdin(void) { bc_vec_empty(&buffer); if (vm.eof) break; + else bc_vm_clean(); } if (!BC_STATUS_IS_ERROR(s)) { @@ -707,6 +697,7 @@ static void bc_vm_exec(const char* env_exp_exit) { size_t i; bool has_file = false; + BcVec buf; #if BC_ENABLED if (BC_IS_BC && (vm.flags & BC_FLAG_L)) { @@ -720,8 +711,40 @@ static void bc_vm_exec(const char* env_exp_exit) { #endif // BC_ENABLED if (vm.exprs.len) { + + size_t len = vm.exprs.len - 1; + bool more; + + BC_SIG_LOCK; + bc_vec_init(&buf, sizeof(uchar), NULL); + +#ifndef NDEBUG + BC_SETJMP_LOCKED(err); +#endif // NDEBUG + + BC_SIG_UNLOCK; + bc_lex_file(&vm.prs.l, bc_program_exprs_name); - bc_vm_process(vm.exprs.v, false); + + do { + + more = bc_read_buf(&buf, vm.exprs.v, &len); + bc_vec_pushByte(&buf, '\0'); + bc_vm_process(buf.v, false); + + bc_vec_npop(&buf, buf.len); + + } while (more); + + BC_SIG_LOCK; + bc_vec_free(&buf); + +#ifndef NDEBUG + BC_UNSETJMP; +#endif // NDEBUG + + BC_SIG_UNLOCK; + if (getenv(env_exp_exit) != NULL) return; } @@ -733,6 +756,18 @@ static void bc_vm_exec(const char* env_exp_exit) { } if (BC_IS_BC || !has_file) bc_vm_stdin(); + +// These are all protected by ifndef NDEBUG because if these are needed, bc is +// goingi 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; + +err: + BC_SIG_MAYLOCK; + bc_vec_free(&buf); + BC_LONGJMP_CONT; +#endif // NDEBUG } void bc_vm_boot(int argc, char *argv[], const char *env_len, @@ -798,18 +833,22 @@ void bc_vm_boot(int argc, char *argv[], const char *env_len, bc_vm_envArgs(env_args); bc_args(argc, argv); +#if BC_ENABLED if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G); +#endif // BC_ENABLED 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 +#if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1; -#endif // BC_ENABLE_EXTRA_MATH +#endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND +#if BC_ENABLED if (BC_IS_BC && !BC_IS_POSIX) vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; +#endif // BC_ENABLED if (BC_IS_BC && BC_I && !(vm.flags & BC_FLAG_Q)) bc_vm_info(NULL); diff --git a/tests/afl.py b/tests/afl.py index a67e086c3dd1..ff3b9229c1c2 100755 --- a/tests/afl.py +++ b/tests/afl.py @@ -1,8 +1,8 @@ #! /usr/bin/python3 -B # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/all.sh b/tests/all.sh index bd39caf8dcbd..07fd346f04c5 100755 --- a/tests/all.sh +++ b/tests/all.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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: @@ -138,6 +138,10 @@ printf '%s\n' "$halt" | "$exe" "$@" > /dev/null 2>&1 if [ "$d" = bc ]; then printf '%s\n' "quit" | "$exe" "$@" > /dev/null 2>&1 + two=$("$exe" "$@" -e 1+1 -e quit) + if [ "$two" != "2" ]; then + err_exit "$d failed a quit test" 1 + fi fi printf 'pass\n' diff --git a/tests/bc/errors/23.txt b/tests/bc/errors/23.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a42997385eaff0242314944a3589df30c3bdc55 GIT binary patch literal 5141 zcmaJ_!A=`75KWKx)KBoC2Pn$2-raV&s3{Co)nm+X*+&?_-e?G*&r*}8EXYpS+dHnS|p6=r|wpVc-2z8g2) zW(hG=d318+CRcA-yDV36awR8Kb0br8^mst3 zYCx)NK&oy)s&GK6azLtdK&o~?s(3)8dfjt`B~ricyTlO%y7v-CH0b_I98sY?kT|WQ zB{l%lI)G^-fN34Tv=zX#4q)00V9Vp#YJh1wfH57$5Cj@W1Y}b5ZjfgiQzV_KF}6sg z_C-J@$n1|6p=w*_lW_LScmvQV0%+U;XzT%K6ah2_0W^vL8btt&M*yu!f>KRp=M?!= zl{HG%rMj$D5=)htT~unY+OUMROBU8MElXI#5NovoJ+kcEbiV?%+JIWqfLd)pt!+TL zHfJ1y?fxna;_~bsE73;++joKb?s?Pg?2}5kMrWWzJC(qlg%WN(1ng7-b}j;TDgiqm z0XriBJC%T)m4GWMy_pF2ZVFxz>iv}Xid65Y#8qWfx7P!|7-0KDI?FC-bOAJN=aaf3&Wa6=8)I<}PC8H*r_$(PU;qJbi zEMc!RvsLuoe9Iupv6SD(@(iLJ8N_c8L^%lJI0&K~1o0dMGhG;azrJaAckDY;RqyWF z_nfMJIkYdPP#p333$|1{Kz4b_VLiZdWT%%Tzt@Ff1Ax_755TYy0K<9!h7AE2)&nqX z48YWTKnDRyZ2y=3)Z4($fRa^j1Um;x*7vFz>?|l*^=8oXK+@<)NIO^=plCNh(WwAM zy8(*M1t>Zgpy*_PqTK*RX9E-;4&m52QJPO1vRHgtezHbisIiSc~}<{sYastsnpZ literal 0 HcmV?d00001 diff --git a/tests/bc/errors/24.txt b/tests/bc/errors/24.txt new file mode 100644 index 000000000000..0fbfe2762504 --- /dev/null +++ b/tests/bc/errors/24.txt @@ -0,0 +1,9 @@ +perm(10, 2) +comb(10, 2) +perm(6, 2) +comb(6, ++i[]) +} + +define m(*x[], *y[]) { + r@turn x[0]) +z \ No newline at end of file diff --git a/tests/bc/misc2.txt b/tests/bc/misc2.txt index 7cf162435c1b..3b3aa683402c 100644 --- a/tests/bc/misc2.txt +++ b/tests/bc/misc2.txt @@ -87,6 +87,7 @@ if(x == 1) { for (;;) { 123 ; break; } for (i = 0;; ++i) { i ; if (i == 2) break; else i; } +for (i = 0;;!++i) { i ; if (i == 2) break; else i; } for (i = 0;; ++i) { i ; if (i != 2) i else break } while (i > 0) if (i == 1) break else i-- diff --git a/tests/bc/misc2_results.txt b/tests/bc/misc2_results.txt index 986a3a2a13e1..93b15e508170 100644 --- a/tests/bc/misc2_results.txt +++ b/tests/bc/misc2_results.txt @@ -47,6 +47,11 @@ zx16 1 1 2 +0 +0 +1 +1 +2 2 1 1 diff --git a/tests/bc/timeconst.sh b/tests/bc/timeconst.sh index 17e765d159ec..32e1e743d9e4 100755 --- a/tests/bc/timeconst.sh +++ b/tests/bc/timeconst.sh @@ -2,8 +2,6 @@ # # Copyright (c) 2018-2020 Gavin D. Howard and contributors. # -# All rights reserved. -# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # diff --git a/tests/dc/errors/25.txt b/tests/dc/errors/25.txt new file mode 100644 index 000000000000..24740cab6f4c --- /dev/null +++ b/tests/dc/errors/25.txt @@ -0,0 +1,7 @@ +#! /bin/dc +0si[lid:rli1;rd:rli1;rpRli1+sili10>x]dsxx0sx0si +1 2 +si[lid:rli1;rd:rli1;rpRli1+sili10>x]dsxx0sx0si +1 2 +ÿ€ + diff --git a/tests/dc/errors/26.txt b/tests/dc/errors/26.txt new file mode 100644 index 000000000000..0d68e5db9454 --- /dev/null +++ b/tests/dc/errors/26.txt @@ -0,0 +1,222 @@ +0bpR +1bp0 +.23bpR +138963.9873645bpR +_19bpR +_.1298[li;i;rpRli1+sili10>x]dsxx0sx0si +1 2+p+p +3+p +4+p +5+p +6+p +7+p +8+p +9+p +10+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+o +72+p +73+p +74+p +75+p +22+p +23+p +24+p +25+p +26+p +27+p +28+p +29+p +30+p +31+p +32+p +33+p +34+p +35+p +36+p +37+p +38+p +39+p +40+1+p +42+p +43+p +44+p +45+p +46+p +47+p +48+p +49+p +50+p +51+p +52+p +53+p +54+p +55+p +56+p +57+p +58+p +59+p +60+p +61+p +60bpR +1bp0 +.23bpR +138963.9873645bpR +_19bpR +_.1298[li;i;rpRli1+sili10>x]dsxx0sx0si +1 2+p+p +3+p +4+p +5+p +6+p +7+p +8+p +9+p +10+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+o +72+p +73+p +74+p +75+p +22+p +23+p +24+p +25+p +26+p +27+p +28+p +29+p +30+p +31+p +32+p +33+p +34+p +35+p +36+p +37+p +38+p +39+p +40+1+p +42+p +43+p +44+p +45+p +46+p +47+p +48+p +49+p +50+p +51+p +52+p +53+p +54+p +55+p +56+p +57+p +58+p +59+p +60+p +61+p +62+p +63+p +64+p +65+p +66+p +67 +73+p +74+p +75+p +76+p +77+p +78+p +79+p +80+p +È1+p +82+p +83+p +84+p +85+pç86+p +87+p +88+p +89+p +90+p +91+p +92+p +93+p +94+p +95+p +96+p +97+p +98+p +99+p +100+p +101+p +102+p +103+p +104+p +105+p +106+p +107+p +108+p +109–––––––––––––––––––––––––––3+p2+p +63+p +64+p +65+p +66+p +67 +73+p +74+p +75+p +76+p +77+p +78+p +79+pþ80+p +81+p +82+p +83+p +84+p +85+pç86+p +87+p +88+p +89+p +90+p +91+p +92+p +93+p +94+p +95+p +96+p +97+p +98+p +99+p +100+p +101+p +102+p +103+p +304+p +105+p +106+p +107+p +108+p +109–––––––––––––––––––––––––––3+p diff --git a/tests/dc/errors/27.txt b/tests/dc/errors/27.txt new file mode 100644 index 000000000000..32a3088db8aa --- /dev/null +++ b/tests/dc/errors/27.txt @@ -0,0 +1,2 @@ +" 1(pR,129bp\ + diff --git a/tests/dc/errors/28.txt b/tests/dc/errors/28.txt new file mode 100644 index 000000000000..b6dd1d3695cb --- /dev/null +++ b/tests/dc/errors/28.txt @@ -0,0 +1,2 @@ +15 4%0:i [2nd] 1:b 0;C p 1;b0:b [2nd] 1:b 0;b p 1;b~~~b 0;b p 1;b~~~0k +1 diff --git a/tests/dc/errors/29.txt b/tests/dc/errors/29.txt new file mode 100644 index 000000000000..696260536798 --- /dev/null +++ b/tests/dc/errors/29.txt @@ -0,0 +1,20 @@ +15 4%0:b [2nd] 1:b 0;b 1;b X + 27239 1%pR +3460:b [2nd] 1:b 0;b p bpR +.2 1%pR +6 4%pR +15 4%0:b [2nd] 1:b 0;b p 1;b X + 27239 1%pR +b 0;b p 1;b2 +1bpb [2nd] 1:u 0;b p 1;b X + 2 +[1st] 0:b [2nd] 1:b 0;b p S;b p +[string]XpR +[3 4^p]silix +[[[q 1 3+pR]Ú]x]x4 5^pR +4xpR +5 112ax 90ax 112ax 82ax + pR +[q\\] pR +[\\] pR +92 a pR diff --git a/tests/dc/stdin.txt b/tests/dc/stdin.txt index e7a575207f69..1cf64f9fc740 100644 --- a/tests/dc/stdin.txt +++ b/tests/dc/stdin.txt @@ -1,3 +1,1005 @@ 0si[lid:rli1+sili10>x]dsxxli1-si[li;rpRli1-sili0!>x]dsxxli1+si[li;rpRli1+sili10>x]dsxx0sx0si 1 2+p [foo] +0 +1+p +2+p +3+p +4+p +5+p +6+p +7+p +8+p +9+p +10+p +11+p +12+p +13+p +14+p +15+p +16+p +17+p +18+p +19+p +20+p +21+p +22+p +23+p +24+p +25+p +26+p +27+p +28+p +29+p +30+p +31+p +32+p +33+p +34+p +35+p +36+p +37+p +38+p +39+p +40+p +41+p +42+p +43+p +44+p +45+p +46+p +47+p +48+p +49+p +50+p +51+p +52+p +53+p +54+p +55+p +56+p +57+p +58+p +59+p +60+p +61+p +62+p +63+p +64+p +65+p +66+p +67+p +68+p +69+p +70+p +71+p +72+p +73+p +74+p +75+p +76+p +77+p +78+p +79+p +80+p +81+p +82+p +83+p +84+p +85+p +86+p +87+p +88+p +89+p +90+p +91+p +92+p +93+p +94+p +95+p +96+p +97+p +98+p +99+p +100+p +101+p +102+p +103+p +104+p +105+p +106+p +107+p +108+p +109+p +110+p +111+p +112+p +113+p +114+p +115+p +116+p +117+p +118+p +119+p +120+p +121+p +122+p +123+p +124+p +125+p +126+p +127+p +128+p +129+p +130+p +131+p +132+p +133+p +134+p +135+p +136+p +137+p +138+p +139+p +140+p +141+p +142+p +143+p +144+p +145+p +146+p +147+p +148+p +149+p +150+p +151+p +152+p +153+p +154+p +155+p +156+p +157+p +158+p +159+p +160+p +161+p +162+p +163+p +164+p +165+p +166+p +167+p +168+p +169+p +170+p +171+p +172+p +173+p +174+p +175+p +176+p +177+p +178+p +179+p +180+p +181+p +182+p +183+p +184+p +185+p +186+p +187+p +188+p +189+p +190+p +191+p +192+p +193+p +194+p +195+p +196+p +197+p +198+p +199+p +200+p +201+p +202+p +203+p +204+p +205+p +206+p +207+p +208+p +209+p +210+p +211+p +212+p +213+p +214+p +215+p +216+p +217+p +218+p +219+p +220+p +221+p +222+p +223+p +224+p +225+p +226+p +227+p +228+p +229+p +230+p +231+p +232+p +233+p +234+p +235+p +236+p +237+p +238+p +239+p +240+p +241+p +242+p +243+p +244+p +245+p +246+p +247+p +248+p +249+p +250+p +251+p +252+p +253+p +254+p +255+p +256+p +257+p +258+p +259+p +260+p +261+p +262+p +263+p +264+p +265+p +266+p +267+p +268+p +269+p +270+p +271+p +272+p +273+p +274+p +275+p +276+p +277+p +278+p +279+p +280+p +281+p +282+p +283+p +284+p +285+p +286+p +287+p +288+p +289+p +290+p +291+p +292+p +293+p +294+p +295+p +296+p +297+p +298+p +299+p +300+p +301+p +302+p +303+p +304+p +305+p +306+p +307+p +308+p +309+p +310+p +311+p +312+p +313+p +314+p +315+p +316+p +317+p +318+p +319+p +320+p +321+p +322+p +323+p +324+p +325+p +326+p +327+p +328+p +329+p +330+p +331+p +332+p +333+p +334+p +335+p +336+p +337+p +338+p +339+p +340+p +341+p +342+p +343+p +344+p +345+p +346+p +347+p +348+p +349+p +350+p +351+p +352+p +353+p +354+p +355+p +356+p +357+p +358+p +359+p +360+p +361+p +362+p +363+p +364+p +365+p +366+p +367+p +368+p +369+p +370+p +371+p +372+p +373+p +374+p +375+p +376+p +377+p +378+p +379+p +380+p +381+p +382+p +383+p +384+p +385+p +386+p +387+p +388+p +389+p +390+p +391+p +392+p +393+p +394+p +395+p +396+p +397+p +398+p +399+p +400+p +401+p +402+p +403+p +404+p +405+p +406+p +407+p +408+p +409+p +410+p +411+p +412+p +413+p +414+p +415+p +416+p +417+p +418+p +419+p +420+p +421+p +422+p +423+p +424+p +425+p +426+p +427+p +428+p +429+p +430+p +431+p +432+p +433+p +434+p +435+p +436+p +437+p +438+p +439+p +440+p +441+p +442+p +443+p +444+p +445+p +446+p +447+p +448+p +449+p +450+p +451+p +452+p +453+p +454+p +455+p +456+p +457+p +458+p +459+p +460+p +461+p +462+p +463+p +464+p +465+p +466+p +467+p +468+p +469+p +470+p +471+p +472+p +473+p +474+p +475+p +476+p +477+p +478+p +479+p +480+p +481+p +482+p +483+p +484+p +485+p +486+p +487+p +488+p +489+p +490+p +491+p +492+p +493+p +494+p +495+p +496+p +497+p +498+p +499+p +500+p +501+p +502+p +503+p +504+p +505+p +506+p +507+p +508+p +509+p +510+p +511+p +512+p +513+p +514+p +515+p +516+p +517+p +518+p +519+p +520+p +521+p +522+p +523+p +524+p +525+p +526+p +527+p +528+p +529+p +530+p +531+p +532+p +533+p +534+p +535+p +536+p +537+p +538+p +539+p +540+p +541+p +542+p +543+p +544+p +545+p +546+p +547+p +548+p +549+p +550+p +551+p +552+p +553+p +554+p +555+p +556+p +557+p +558+p +559+p +560+p +561+p +562+p +563+p +564+p +565+p +566+p +567+p +568+p +569+p +570+p +571+p +572+p +573+p +574+p +575+p +576+p +577+p +578+p +579+p +580+p +581+p +582+p +583+p +584+p +585+p +586+p +587+p +588+p +589+p +590+p +591+p +592+p +593+p +594+p +595+p +596+p +597+p +598+p +599+p +600+p +601+p +602+p +603+p +604+p +605+p +606+p +607+p +608+p +609+p +610+p +611+p +612+p +613+p +614+p +615+p +616+p +617+p +618+p +619+p +620+p +621+p +622+p +623+p +624+p +625+p +626+p +627+p +628+p +629+p +630+p +631+p +632+p +633+p +634+p +635+p +636+p +637+p +638+p +639+p +640+p +641+p +642+p +643+p +644+p +645+p +646+p +647+p +648+p +649+p +650+p +651+p +652+p +653+p +654+p +655+p +656+p +657+p +658+p +659+p +660+p +661+p +662+p +663+p +664+p +665+p +666+p +667+p +668+p +669+p +670+p +671+p +672+p +673+p +674+p +675+p +676+p +677+p +678+p +679+p +680+p +681+p +682+p +683+p +684+p +685+p +686+p +687+p +688+p +689+p +690+p +691+p +692+p +693+p +694+p +695+p +696+p +697+p +698+p +699+p +700+p +701+p +702+p +703+p +704+p +705+p +706+p +707+p +708+p +709+p +710+p +711+p +712+p +713+p +714+p +715+p +716+p +717+p +718+p +719+p +720+p +721+p +722+p +723+p +724+p +725+p +726+p +727+p +728+p +729+p +730+p +731+p +732+p +733+p +734+p +735+p +736+p +737+p +738+p +739+p +740+p +741+p +742+p +743+p +744+p +745+p +746+p +747+p +748+p +749+p +750+p +751+p +752+p +753+p +754+p +755+p +756+p +757+p +758+p +759+p +760+p +761+p +762+p +763+p +764+p +765+p +766+p +767+p +768+p +769+p +770+p +771+p +772+p +773+p +774+p +775+p +776+p +777+p +778+p +779+p +780+p +781+p +782+p +783+p +784+p +785+p +786+p +787+p +788+p +789+p +790+p +791+p +792+p +793+p +794+p +795+p +796+p +797+p +798+p +799+p +800+p +801+p +802+p +803+p +804+p +805+p +806+p +807+p +808+p +809+p +810+p +811+p +812+p +813+p +814+p +815+p +816+p +817+p +818+p +819+p +820+p +821+p +822+p +823+p +824+p +825+p +826+p +827+p +828+p +829+p +830+p +831+p +832+p +833+p +834+p +835+p +836+p +837+p +838+p +839+p +840+p +841+p +842+p +843+p +844+p +845+p +846+p +847+p +848+p +849+p +850+p +851+p +852+p +853+p +854+p +855+p +856+p +857+p +858+p +859+p +860+p +861+p +862+p +863+p +864+p +865+p +866+p +867+p +868+p +869+p +870+p +871+p +872+p +873+p +874+p +875+p +876+p +877+p +878+p +879+p +880+p +881+p +882+p +883+p +884+p +885+p +886+p +887+p +888+p +889+p +890+p +891+p +892+p +893+p +894+p +895+p +896+p +897+p +898+p +899+p +900+p +901+p +902+p +903+p +904+p +905+p +906+p +907+p +908+p +909+p +910+p +911+p +912+p +913+p +914+p +915+p +916+p +917+p +918+p +919+p +920+p +921+p +922+p +923+p +924+p +925+p +926+p +927+p +928+p +929+p +930+p +931+p +932+p +933+p +934+p +935+p +936+p +937+p +938+p +939+p +940+p +941+p +942+p +943+p +944+p +945+p +946+p +947+p +948+p +949+p +950+p +951+p +952+p +953+p +954+p +955+p +956+p +957+p +958+p +959+p +960+p +961+p +962+p +963+p +964+p +965+p +966+p +967+p +968+p +969+p +970+p +971+p +972+p +973+p +974+p +975+p +976+p +977+p +978+p +979+p +980+p +981+p +982+p +983+p +984+p +985+p +986+p +987+p +988+p +989+p +990+p +991+p +992+p +993+p +994+p +995+p +996+p +997+p +998+p +999+p +1000+p +p diff --git a/tests/dc/stdin_results.txt b/tests/dc/stdin_results.txt index 52f23dbb4a90..56a33e5cf82d 100644 --- a/tests/dc/stdin_results.txt +++ b/tests/dc/stdin_results.txt @@ -19,3 +19,1004 @@ 8 9 3 +1 +3 +6 +10 +15 +21 +28 +36 +45 +55 +66 +78 +91 +105 +120 +136 +153 +171 +190 +210 +231 +253 +276 +300 +325 +351 +378 +406 +435 +465 +496 +528 +561 +595 +630 +666 +703 +741 +780 +820 +861 +903 +946 +990 +1035 +1081 +1128 +1176 +1225 +1275 +1326 +1378 +1431 +1485 +1540 +1596 +1653 +1711 +1770 +1830 +1891 +1953 +2016 +2080 +2145 +2211 +2278 +2346 +2415 +2485 +2556 +2628 +2701 +2775 +2850 +2926 +3003 +3081 +3160 +3240 +3321 +3403 +3486 +3570 +3655 +3741 +3828 +3916 +4005 +4095 +4186 +4278 +4371 +4465 +4560 +4656 +4753 +4851 +4950 +5050 +5151 +5253 +5356 +5460 +5565 +5671 +5778 +5886 +5995 +6105 +6216 +6328 +6441 +6555 +6670 +6786 +6903 +7021 +7140 +7260 +7381 +7503 +7626 +7750 +7875 +8001 +8128 +8256 +8385 +8515 +8646 +8778 +8911 +9045 +9180 +9316 +9453 +9591 +9730 +9870 +10011 +10153 +10296 +10440 +10585 +10731 +10878 +11026 +11175 +11325 +11476 +11628 +11781 +11935 +12090 +12246 +12403 +12561 +12720 +12880 +13041 +13203 +13366 +13530 +13695 +13861 +14028 +14196 +14365 +14535 +14706 +14878 +15051 +15225 +15400 +15576 +15753 +15931 +16110 +16290 +16471 +16653 +16836 +17020 +17205 +17391 +17578 +17766 +17955 +18145 +18336 +18528 +18721 +18915 +19110 +19306 +19503 +19701 +19900 +20100 +20301 +20503 +20706 +20910 +21115 +21321 +21528 +21736 +21945 +22155 +22366 +22578 +22791 +23005 +23220 +23436 +23653 +23871 +24090 +24310 +24531 +24753 +24976 +25200 +25425 +25651 +25878 +26106 +26335 +26565 +26796 +27028 +27261 +27495 +27730 +27966 +28203 +28441 +28680 +28920 +29161 +29403 +29646 +29890 +30135 +30381 +30628 +30876 +31125 +31375 +31626 +31878 +32131 +32385 +32640 +32896 +33153 +33411 +33670 +33930 +34191 +34453 +34716 +34980 +35245 +35511 +35778 +36046 +36315 +36585 +36856 +37128 +37401 +37675 +37950 +38226 +38503 +38781 +39060 +39340 +39621 +39903 +40186 +40470 +40755 +41041 +41328 +41616 +41905 +42195 +42486 +42778 +43071 +43365 +43660 +43956 +44253 +44551 +44850 +45150 +45451 +45753 +46056 +46360 +46665 +46971 +47278 +47586 +47895 +48205 +48516 +48828 +49141 +49455 +49770 +50086 +50403 +50721 +51040 +51360 +51681 +52003 +52326 +52650 +52975 +53301 +53628 +53956 +54285 +54615 +54946 +55278 +55611 +55945 +56280 +56616 +56953 +57291 +57630 +57970 +58311 +58653 +58996 +59340 +59685 +60031 +60378 +60726 +61075 +61425 +61776 +62128 +62481 +62835 +63190 +63546 +63903 +64261 +64620 +64980 +65341 +65703 +66066 +66430 +66795 +67161 +67528 +67896 +68265 +68635 +69006 +69378 +69751 +70125 +70500 +70876 +71253 +71631 +72010 +72390 +72771 +73153 +73536 +73920 +74305 +74691 +75078 +75466 +75855 +76245 +76636 +77028 +77421 +77815 +78210 +78606 +79003 +79401 +79800 +80200 +80601 +81003 +81406 +81810 +82215 +82621 +83028 +83436 +83845 +84255 +84666 +85078 +85491 +85905 +86320 +86736 +87153 +87571 +87990 +88410 +88831 +89253 +89676 +90100 +90525 +90951 +91378 +91806 +92235 +92665 +93096 +93528 +93961 +94395 +94830 +95266 +95703 +96141 +96580 +97020 +97461 +97903 +98346 +98790 +99235 +99681 +100128 +100576 +101025 +101475 +101926 +102378 +102831 +103285 +103740 +104196 +104653 +105111 +105570 +106030 +106491 +106953 +107416 +107880 +108345 +108811 +109278 +109746 +110215 +110685 +111156 +111628 +112101 +112575 +113050 +113526 +114003 +114481 +114960 +115440 +115921 +116403 +116886 +117370 +117855 +118341 +118828 +119316 +119805 +120295 +120786 +121278 +121771 +122265 +122760 +123256 +123753 +124251 +124750 +125250 +125751 +126253 +126756 +127260 +127765 +128271 +128778 +129286 +129795 +130305 +130816 +131328 +131841 +132355 +132870 +133386 +133903 +134421 +134940 +135460 +135981 +136503 +137026 +137550 +138075 +138601 +139128 +139656 +140185 +140715 +141246 +141778 +142311 +142845 +143380 +143916 +144453 +144991 +145530 +146070 +146611 +147153 +147696 +148240 +148785 +149331 +149878 +150426 +150975 +151525 +152076 +152628 +153181 +153735 +154290 +154846 +155403 +155961 +156520 +157080 +157641 +158203 +158766 +159330 +159895 +160461 +161028 +161596 +162165 +162735 +163306 +163878 +164451 +165025 +165600 +166176 +166753 +167331 +167910 +168490 +169071 +169653 +170236 +170820 +171405 +171991 +172578 +173166 +173755 +174345 +174936 +175528 +176121 +176715 +177310 +177906 +178503 +179101 +179700 +180300 +180901 +181503 +182106 +182710 +183315 +183921 +184528 +185136 +185745 +186355 +186966 +187578 +188191 +188805 +189420 +190036 +190653 +191271 +191890 +192510 +193131 +193753 +194376 +195000 +195625 +196251 +196878 +197506 +198135 +198765 +199396 +200028 +200661 +201295 +201930 +202566 +203203 +203841 +204480 +205120 +205761 +206403 +207046 +207690 +208335 +208981 +209628 +210276 +210925 +211575 +212226 +212878 +213531 +214185 +214840 +215496 +216153 +216811 +217470 +218130 +218791 +219453 +220116 +220780 +221445 +222111 +222778 +223446 +224115 +224785 +225456 +226128 +226801 +227475 +228150 +228826 +229503 +230181 +230860 +231540 +232221 +232903 +233586 +234270 +234955 +235641 +236328 +237016 +237705 +238395 +239086 +239778 +240471 +241165 +241860 +242556 +243253 +243951 +244650 +245350 +246051 +246753 +247456 +248160 +248865 +249571 +250278 +250986 +251695 +252405 +253116 +253828 +254541 +255255 +255970 +256686 +257403 +258121 +258840 +259560 +260281 +261003 +261726 +262450 +263175 +263901 +264628 +265356 +266085 +266815 +267546 +268278 +269011 +269745 +270480 +271216 +271953 +272691 +273430 +274170 +274911 +275653 +276396 +277140 +277885 +278631 +279378 +280126 +280875 +281625 +282376 +283128 +283881 +284635 +285390 +286146 +286903 +287661 +288420 +289180 +289941 +290703 +291466 +292230 +292995 +293761 +294528 +295296 +296065 +296835 +297606 +298378 +299151 +299925 +300700 +301476 +302253 +303031 +303810 +304590 +305371 +306153 +306936 +307720 +308505 +309291 +310078 +310866 +311655 +312445 +313236 +314028 +314821 +315615 +316410 +317206 +318003 +318801 +319600 +320400 +321201 +322003 +322806 +323610 +324415 +325221 +326028 +326836 +327645 +328455 +329266 +330078 +330891 +331705 +332520 +333336 +334153 +334971 +335790 +336610 +337431 +338253 +339076 +339900 +340725 +341551 +342378 +343206 +344035 +344865 +345696 +346528 +347361 +348195 +349030 +349866 +350703 +351541 +352380 +353220 +354061 +354903 +355746 +356590 +357435 +358281 +359128 +359976 +360825 +361675 +362526 +363378 +364231 +365085 +365940 +366796 +367653 +368511 +369370 +370230 +371091 +371953 +372816 +373680 +374545 +375411 +376278 +377146 +378015 +378885 +379756 +380628 +381501 +382375 +383250 +384126 +385003 +385881 +386760 +387640 +388521 +389403 +390286 +391170 +392055 +392941 +393828 +394716 +395605 +396495 +397386 +398278 +399171 +400065 +400960 +401856 +402753 +403651 +404550 +405450 +406351 +407253 +408156 +409060 +409965 +410871 +411778 +412686 +413595 +414505 +415416 +416328 +417241 +418155 +419070 +419986 +420903 +421821 +422740 +423660 +424581 +425503 +426426 +427350 +428275 +429201 +430128 +431056 +431985 +432915 +433846 +434778 +435711 +436645 +437580 +438516 +439453 +440391 +441330 +442270 +443211 +444153 +445096 +446040 +446985 +447931 +448878 +449826 +450775 +451725 +452676 +453628 +454581 +455535 +456490 +457446 +458403 +459361 +460320 +461280 +462241 +463203 +464166 +465130 +466095 +467061 +468028 +468996 +469965 +470935 +471906 +472878 +473851 +474825 +475800 +476776 +477753 +478731 +479710 +480690 +481671 +482653 +483636 +484620 +485605 +486591 +487578 +488566 +489555 +490545 +491536 +492528 +493521 +494515 +495510 +496506 +497503 +498501 +499500 +500500 +500500 diff --git a/tests/errors.sh b/tests/errors.sh index dd38b5d28c6b..17c84ca24ef3 100755 --- a/tests/errors.sh +++ b/tests/errors.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/radamsa.sh b/tests/radamsa.sh index 3d7c763c5827..537ee10255c3 100755 --- a/tests/radamsa.sh +++ b/tests/radamsa.sh @@ -1,8 +1,8 @@ #! /bin/bash # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/randmath.py b/tests/randmath.py index f350ef357f6b..7f14a345be3e 100755 --- a/tests/randmath.py +++ b/tests/randmath.py @@ -1,8 +1,8 @@ #! /usr/bin/python3 -B # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/read.sh b/tests/read.sh index 635291221465..0440a078d36c 100755 --- a/tests/read.sh +++ b/tests/read.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/script.sh b/tests/script.sh index 4d1b2354f42c..279295829f75 100755 --- a/tests/script.sh +++ b/tests/script.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/scripts.sh b/tests/scripts.sh index 13932fc4db17..ff17260c909c 100755 --- a/tests/scripts.sh +++ b/tests/scripts.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/stdin.sh b/tests/stdin.sh index cfd45805face..7b821d749ba9 100755 --- a/tests/stdin.sh +++ b/tests/stdin.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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/tests/test.sh b/tests/test.sh index a8e7ddeb9f63..20f95413597b 100755 --- a/tests/test.sh +++ b/tests/test.sh @@ -1,8 +1,8 @@ #! /bin/sh # -# Copyright (c) 2018-2020 Gavin D. Howard and contributors. +# SPDX-License-Identifier: BSD-2-Clause # -# All rights reserved. +# Copyright (c) 2018-2020 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: