diff --git a/NEWS.md b/NEWS.md index 0f28d552df18..3a388b0dc316 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,1244 +1,1254 @@ # News +## 5.2.4 + +This is a production release that fixes two bugs in history: + +* Without prompt, the cursor could not be placed on the first character in a + line. +* Home and End key handling in `tmux` was fixed. + +Any users that do not care about these improvements do not need to upgrade. + ## 5.2.3 This is a production release that fixes one bug, a parse error when passing a file to `bc` using `-f` if that file had a multiline comment or string in it. ## 5.2.2 This is a production release that fixes one bug, a segmentation fault if `argv[0]` equals `NULL`. This is not a critical bug; there will be no vulnerability as far as I can tell. There is no need to update if you do not wish to. ## 5.2.1 This is a production release that fixes two parse bugs when in POSIX standard mode. One of these bugs was due to a quirk of the POSIX grammar, and the other was because `bc` was too strict. ## 5.2.0 This is a production release that adds a new feature, fixes some bugs, and adds out-of-source builds and a `pkg-config` file for `bcl`. The new feature is the ability to turn off exiting on expressions. It is also possible to set the default using `configure.sh`. This behavior used to exist with the `BC_EXPR_EXIT` environment variable, which is now used again. Bugs fixed include: * Some possible race conditions with error handling. * Install and uninstall targets for `bcl` did not work. ## 5.1.1 This is a production release that completes a bug fix from `5.1.0`. The bug exists in all versions of `bc`. The bug was that `if` statements without `else` statements would not be handled correctly at the end of files or right before a function definition. ## 5.1.0 This is a production release with some fixes and new features. * Fixed a bug where an `if` statement without an `else` before defining a function caused an error. * Fixed a bug with the `bc` banner and `-q`. * Fixed a bug on Windows where files were not read correctly. * Added a command-line flag (`-z`) to make `bc` and `dc` print leading zeroes on numbers `-1 < x < 1`. * Added four functions to `lib2.bc` (`plz()`, `plznl()`, `pnlz()`, and `pnlznl()`) to allow printing numbers with or without leading zeros, despite the use of `-z` or not. * Added builtin functions to query global state like line length, global stacks, and leading zeroes. * Added a command-line flag (`-L`) to disable wrapping when printing numbers. * Improved builds on Windows. ## 5.0.2 This is a production release with one fix for a flaky test. If you have not experienced problems with the test suite, you do ***NOT*** need to upgrade. The test was one that tested whether `bc` fails gracefully when it can't allocate memory. Unfortunately, there are cases when Linux and FreeBSD lie and pretend to allocate the memory. The reason they do this is because a lot of programs don't use all of the memory they allocate, so those OS's usually get away with it. However, this `bc` uses all of the memory it allocates (at least at page granularity), so when it tries to use the memory, FreeBSD and Linux kill it. This only happens sometimes, however. Other times (on my machine), they do, in fact, refuse the request. So I changed the test to not test for that because I think the graceful failure code won't really change much. ## 5.0.1 This is a production release with two fixes: * Fix for the build on Mac OSX. * Fix for the build on Android. Users that do not use those platforms do ***NOT*** need to update. ## 5.0.0 This is a major production release with several changes: * Added support for OpenBSD's `pledge()` and `unveil()`. * Fixed print bug where a backslash newline combo was printed even if only one digit was left, something I blindly copied from GNU `bc`, like a fool. * Fixed bugs in the manuals. * Fixed a possible multiplication overflow in power. * Temporary numbers are garbage collected if allocation fails, and the allocation is retried. This is to make `bc` and `dc` more resilient to running out of memory. * Limited the number of temporary numbers and made the space for them static so that allocating more space for them cannot fail. * Allowed integers with non-zero `scale` to be used with power, places, and shift operators. * Added greatest common divisor and least common multiple to `lib2.bc`. * Added `SIGQUIT` handling to history. * Added a command to `dc` (`y`) to get the length of register stacks. * Fixed multi-digit bugs in `lib2.bc`. * Removed the no prompt build option. * Created settings that builders can set defaults for and users can set their preferences for. This includes the `bc` banner, resetting on `SIGINT`, TTY mode, and prompt. * Added history support to Windows. * Fixed bugs with the handling of register names in `dc`. * Fixed bugs with multi-line comments and strings in both calculators. * Added a new error type and message for `dc` when register stacks don't have enough items. * Optimized string allocation. * Made `bc` and `dc` UTF-8 capable. * Fixed a bug with `void` functions. * Fixed a misspelled symbol in `bcl`. This is technically a breaking change, which requires this to be `5.0.0`. * Added the ability for users to get the copyright banner back. * Added the ability for users to have `bc` and `dc` quit on `SIGINT`. * Added the ability for users to disable prompt and TTY mode by environment variables. * Added the ability for users to redefine keywords. This is another reason this is `5.0.0`. * Added `dc`'s modular exponentiation and divmod to `bc`. * Added the ability to assign strings to variables and array elements and pass them to functions in `bc`. * Added `dc`'s asciify command and stream printing to `bc`. * Added a command to `dc` (`Y`) to get the length of an array. * Added a command to `dc` (`,`) to get the depth of the execution stack. * Added bitwise and, or, xor, left shift, right shift, reverse, left rotate, right rotate, and mod functions to `lib2.bc`. * Added the functions `s2u(x)` and `s2un(x,n)`, to `lib2.bc`. ## 4.0.2 This is a production release that fixes two bugs: 1. If no files are used and the first statement on `stdin` is invalid, `scale` would not be set to `20` even if `-l` was used. 2. When using history, `bc` failed to respond properly to `SIGSTOP` and `SIGTSTP`. ## 4.0.1 This is a production release that only adds one thing: flushing output when it is printed with a print statement. ## 4.0.0 This is a production release with many fixes, a new command-line option, and a big surprise: * A bug was fixed in `dc`'s `P` command where the item on the stack was *not* popped. * Various bugs in the manuals have been fixed. * A known bug was fixed where history did not interact well with prompts printed by user code without newlines. * A new command-line option, `-R` and `--no-read-prompt` was added to disable just the prompt when using `read()` (`bc`) or `?` (`dc`). * And finally, **official support for Windows was added**. The last item is why this is a major version bump. Currently, only one set of build options (extra math and prompt enabled, history and NLS/locale support disabled, both calculators enabled) is supported on Windows. However, both debug and release builds are supported. In addition, Windows builds are supported for the the library (`bcl`). For more details about how to build on Windows, see the [README][5] or the [build manual][13]. ## 3.3.4 This is a production release that fixes a small bug. The bug was that output was not flushed before a `read()` call, so prompts without a newline on the end were not flushed before the `read()` call. This is such a tiny bug that users only need to upgrade if they are affected. ## 3.3.3 This is a production release with one tweak and fixes for manuals. The tweak is that `length(0)` returns `1` instead of `0`. In `3.3.1`, I changed it so `length(0.x)`, where `x` could be any number of digits, returned the `scale`, but `length(0)` still returned `0` because I believe that `0` has `0` significant digits. After request of FreeBSD and considering the arguments of a mathematician, compatibility with other `bc`'s, and the expectations of users, I decided to make the change. The fixes for manuals fixed a bug where `--` was rendered as `-`. ## 3.3.2 This is a production release that fixes a divide-by-zero bug in `root()` in the [extended math library][16]. All previous versions with `root()` have the bug. ## 3.3.1 This is a production release that fixes a bug. The bug was in the reporting of number length when the value was 0. ## 3.3.0 This is a production release that changes one behavior and fixes documentation bugs. The changed behavior is the treatment of `-e` and `-f` when given through `BC_ENV_ARGS` or `DC_ENV_ARGS`. Now `bc` and `dc` do not exit when those options (or their equivalents) are given through those environment variables. However, `bc` and `dc` still exit when they or their equivalents are given on the command-line. ## 3.2.7 This is a production release that removes a small non-portable shell operation in `configure.sh`. This problem was only noticed on OpenBSD, not FreeBSD or Linux. Non-OpenBSD users do ***NOT*** need to upgrade, although NetBSD users may also need to upgrade. ## 3.2.6 This is a production release that fixes the build on FreeBSD. There was a syntax error in `configure.sh` that the Linux shell did not catch, and FreeBSD depends on the existence of `tests/all.sh`. All users that already upgraded to `3.2.5` should update to this release, with my apologies for the poor release of `3.2.5`. Other users should skip `3.2.5` in favor of this version. ## 3.2.5 This is a production release that fixes several bugs and adds a couple small things. The two most important bugs were bugs that causes `dc` to access memory out-of-bounds (crash in debug builds). This was found by upgrading to `afl++` from `afl`. Both were caused by a failure to distinguish between the same two cases. Another bug was the failure to put all of the licenses in the `LICENSE.md` file. Third, some warnings by `scan-build` were found and eliminated. This needed one big change: `bc` and `dc` now bail out as fast as possible on fatal errors instead of unwinding the stack. Fourth, the pseudo-random number now attempts to seed itself with `/dev/random` if `/dev/urandom` fails. Finally, this release has a few quality-of-life changes to the build system. The usage should not change at all; the only thing that changed was making sure the `Makefile.in` was written to rebuild properly when headers changed and to not rebuild when not necessary. ## 3.2.4 This is a production release that fixes a warning on `gcc` 6 or older, which does not have an attribute that is used. Users do ***NOT*** need to upgrade if they don't use `gcc` 6 or older. ## 3.2.3 This is a production release that fixes a bug in `gen/strgen.sh`. I recently changed `gen/strgen.c`, but I did not change `gen/strgen.sh`. Users that do not use `gen/strgen.sh` do not need to upgrade. ## 3.2.2 This is a production release that fixes a portability bug in `configure.sh`. The bug was using the GNU `find` extension `-wholename`. ## 3.2.1 This is a production release that has one fix for `bcl(3)`. It is technically not a bug fix since the behavior is undefined, but the `BclNumber`s that `bcl_divmod()` returns will be set to `BCL_ERROR_INVALID_NUM` if there is an error. Previously, they were not set. ## 3.2.0 This is a production release that has one bug fix and a major addition. The bug fix was a missing `auto` variable in the bessel `j()` function in the math library. The major addition is a way to build a version of `bc`'s math code as a library. This is done with the `-a` option to `configure.sh`. The API for the library can be read in `./manuals/bcl.3.md` or `man bcl` once the library is installed with `make install`. This library was requested by developers before I even finished version 1.0, but I could not figure out how to do it until now. If the library has API breaking changes, the major version of `bc` will be incremented. ## 3.1.6 This is a production release that fixes a new warning from Clang 12 for FreeBSD and also removes some possible undefined behavior found by UBSan that compilers did not seem to take advantage of. Users do ***NOT*** need to upgrade, if they do not want to. ## 3.1.5 This is a production release that fixes the Chinese locales (which caused `bc` to crash) and a crash caused by `bc` executing code when it should not have been able to. ***ALL USERS SHOULD UPGRADE.*** ## 3.1.4 This is a production release that fixes one bug, changes two behaviors, and removes one environment variable. The bug is like the one in the last release except it applies if files are being executed. I also made the fix more general. The behavior that was changed is that `bc` now exits when given `-e`, `-f`, `--expression` or `--file`. However, if the last one of those is `-f-` (using `stdin` as the file), `bc` does not exit. If `-f-` exists and is not the last of the `-e` and `-f` options (and equivalents), `bc` gives a fatal error and exits. Next, I removed the `BC_EXPR_EXIT` and `DC_EXPR_EXIT` environment variables since their use is not needed with the behavior change. Finally, I made it so `bc` does not print the header, though the `-q` and `--quiet` options were kept for compatibility with GNU `bc`. ## 3.1.3 This is a production release that fixes one minor bug: if `bc` was invoked like the following, it would error: ``` echo "if (1 < 3) 1" | bc ``` Unless users run into this bug, they do not need to upgrade, but it is suggested that they do. ## 3.1.2 This is a production release that adds a way to install *all* locales. Users do ***NOT*** need to upgrade. For package maintainers wishing to make use of the change, just pass `-l` to `configure.sh`. ## 3.1.1 This is a production release that adds two Spanish locales. Users do ***NOT*** need to upgrade, unless they want those locales. ## 3.1.0 This is a production release that adjusts one behavior, fixes eight bugs, and improves manpages for FreeBSD. Because this release fixes bugs, **users and package maintainers should update to this version as soon as possible**. The behavior that was adjusted was how code from the `-e` and `-f` arguments (and equivalents) were executed. They used to be executed as one big chunk, but in this release, they are now executed line-by-line. The first bug fix in how output to `stdout` was handled in `SIGINT`. If a `SIGINT` came in, the `stdout` buffer was not correctly flushed. In fact, a clean-up function was not getting called. This release fixes that bug. The second bug is in how `dc` handled input from `stdin`. This affected `bc` as well since it was a mishandling of the `stdin` buffer. The third fixed bug was that `bc` and `dc` could `abort()` (in debug mode) when receiving a `SIGTERM`. This one was a race condition with pushing and popping items onto and out of vectors. The fourth bug fixed was that `bc` could leave extra items on the stack and thus, not properly clean up some memory. (The memory would still get `free()`'ed, but it would not be `free()`'ed when it could have been.) The next two bugs were bugs in `bc`'s parser that caused crashes when executing the resulting code. The last two bugs were crashes in `dc` that resulted from mishandling of strings. The manpage improvement was done by switching from [ronn][20] to [Pandoc][21] to generate manpages. Pandoc generates much cleaner manpages and doesn't leave blank lines where they shouldn't be. ## 3.0.3 This is a production release that adds one new feature: specific manpages. Before this release, `bc` and `dc` only used one manpage each that referred to various build options. This release changes it so there is one manpage set per relevant build type. Each manual only has information about its particular build, and `configure.sh` selects the correct set for install. ## 3.0.2 This is a production release that adds `utf8` locale symlinks and removes an unused `auto` variable from the `ceil()` function in the [extended math library][16]. Users do ***NOT*** need to update unless they want the locales. ## 3.0.1 This is a production release with two small changes. Users do ***NOT*** need to upgrade to this release; however, if they haven't upgraded to `3.0.0` yet, it may be worthwhile to upgrade to this release. The first change is fixing a compiler warning on FreeBSD with strict warnings on. The second change is to make the new implementation of `ceil()` in `lib2.bc` much more efficient. ## 3.0.0 *Notes for package maintainers:* *First, the `2.7.0` release series saw a change in the option parsing. This made me change one error message and add a few others. The error message that was changed removed one format specifier. This means that `printf()` will seqfault on old locale files. Unfortunately, `bc` cannot use any locale files except the global ones that are already installed, so it will use the previous ones while running tests during install. **If `bc` segfaults while running arg tests when updating, it is because the global locale files have not been replaced. Make sure to either prevent the test suite from running on update or remove the old locale files before updating.** (Removing the locale files can be done with `make uninstall` or by running the [`locale_uninstall.sh`][22] script.) Once this is done, `bc` should install without problems.* *Second, **the option to build without signal support has been removed**. See below for the reasons why.* This is a production release with some small bug fixes, a few improvements, three major bug fixes, and a complete redesign of `bc`'s error and signal handling. **Users and package maintainers should update to this version as soon as possible.** The first major bug fix was in how `bc` executed files. Previously, a whole file was parsed before it was executed, but if a function is defined *after* code, especially if the function definition was actually a redefinition, and the code before the definition referred to the previous function, this `bc` would replace the function before executing any code. The fix was to make sure that all code that existed before a function definition was executed. The second major bug fix was in `bc`'s `lib2.bc`. The `ceil()` function had a bug where a `0` in the decimal place after the truncation position, caused it to output the wrong numbers if there was any non-zero digit after. The third major bug is that when passing parameters to functions, if an expression included an array (not an array element) as a parameter, it was accepted, when it should have been rejected. It is now correctly rejected. Beyond that, this `bc` got several improvements that both sped it up, improved the handling of signals, and improved the error handling. First, the requirements for `bc` were pushed back to POSIX 2008. `bc` uses one function, `strdup()`, which is not in POSIX 2001, and it is in the X/Open System Interfaces group 2001. It is, however, in POSIX 2008, and since POSIX 2008 is old enough to be supported anywhere that I care, that should be the requirement. Second, the BcVm global variable was put into `bss`. This actually slightly reduces the size of the executable from a massive code shrink, and it will stop `bc` from allocating a large set of memory when `bc` starts. Third, the default Karatsuba length was updated from 64 to 32 after making the optimization changes below, since 32 is going to be better than 64 after the changes. Fourth, Spanish translations were added. Fifth, the interpreter received a speedup to make performance on non-math-heavy scripts more competitive with GNU `bc`. While improvements did, in fact, get it much closer (see the [benchmarks][19]), it isn't quite there. There were several things done to speed up the interpreter: First, several small inefficiencies were removed. These inefficiencies included calling the function `bc_vec_pop(v)` twice instead of calling `bc_vec_npop(v, 2)`. They also included an extra function call for checking the size of the stack and checking the size of the stack more than once on several operations. Second, since the current `bc` function is the one that stores constants and strings, the program caches pointers to the current function's vectors of constants and strings to prevent needing to grab the current function in order to grab a constant or a string. Third, `bc` tries to reuse `BcNum`'s (the internal representation of arbitary-precision numbers). If a `BcNum` has the default capacity of `BC_NUM_DEF_SIZE` (32 on 64-bit and 16 on 32-bit) when it is freed, it is added to a list of available `BcNum`'s. And then, when a `BcNum` is allocated with a capacity of `BC_NUM_DEF_SIZE` and any `BcNum`'s exist on the list of reusable ones, one of those ones is grabbed instead. In order to support these changes, the `BC_NUM_DEF_SIZE` was changed. It used to be 16 bytes on all systems, but it was changed to more closely align with the minimum allocation size on Linux, which is either 32 bytes (64-bit musl), 24 bytes (64-bit glibc), 16 bytes (32-bit musl), or 12 bytes (32-bit glibc). Since these are the minimum allocation sizes, these are the sizes that would be allocated anyway, making it worth it to just use the whole space, so the value of `BC_NUM_DEF_SIZE` on 64-bit systems was changed to 32 bytes. On top of that, at least on 64-bit, `BC_NUM_DEF_SIZE` supports numbers with either 72 integer digits or 45 integer digits and 27 fractional digits. This should be more than enough for most cases since `bc`'s default `scale` values are 0 or 20, meaning that, by default, it has at most 20 fractional digits. And 45 integer digits are *a lot*; it's enough to calculate the amount of mass in the Milky Way galaxy in kilograms. Also, 72 digits is enough to calculate the diameter of the universe in Planck lengths. (For 32-bit, these numbers are either 32 integer digits or 12 integer digits and 20 fractional digits. These are also quite big, and going much bigger on a 32-bit system seems a little pointless since 12 digits is just under a trillion and 20 fractional digits is still enough for about any use since `10^-20` light years is just under a millimeter.) All of this together means that for ordinary uses, and even uses in scientific work, the default number size will be all that is needed, which means that nearly all, if not all, numbers will be reused, relieving pressure on the system allocator. I did several experiments to find the changes that had the most impact, especially with regard to reusing `BcNum`'s. One was putting `BcNum`'s into buckets according to their capacity in powers of 2 up to 512. That performed worse than `bc` did in `2.7.2`. Another was putting any `BcNum` on the reuse list that had a capacity of `BC_NUM_DEF_SIZE * 2` and reusing them for `BcNum`'s that requested `BC_NUM_DEF_SIZE`. This did reduce the amount of time spent, but it also spent a lot of time in the system allocator for an unknown reason. (When using `strace`, a bunch more `brk` calls showed up.) Just reusing `BcNum`'s that had exactly `BC_NUM_DEF_SIZE` capacity spent the smallest amount of time in both user and system time. This makes sense, especially with the changes to make `BC_NUM_DEF_SIZE` bigger on 64-bit systems, since the vast majority of numbers will only ever use numbers with a size less than or equal to `BC_NUM_DEF_SIZE`. Last of all, `bc`'s signal handling underwent a complete redesign. (This is the reason that this version is `3.0.0` and not `2.8.0`.) The change was to move from a polling approach to signal handling to an interrupt-based approach. Previously, every single loop condition had a check for signals. I suspect that this could be expensive when in tight loops. Now, the signal handler just uses `longjmp()` (actually `siglongjmp()`) to start an unwinding of the stack until it is stopped or the stack is unwound to `main()`, which just returns. If `bc` is currently executing code that cannot be safely interrupted (according to POSIX), then signals are "locked." The signal handler checks if the lock is taken, and if it is, it just sets the status to indicate that a signal arrived. Later, when the signal lock is released, the status is checked to see if a signal came in. If so, the stack unwinding starts. This design eliminates polling in favor of maintaining a stack of `jmp_buf`'s. This has its own performance implications, but it gives better interaction. And the cost of pushing and popping a `jmp_buf` in a function is paid at most twice. Most functions do not pay that price, and most of the rest only pay it once. (There are only some 3 functions in `bc` that push and pop a `jmp_buf` twice.) As a side effect of this change, I had to eliminate the use of `stdio.h` in `bc` because `stdio` does not play nice with signals and `longjmp()`. I implemented custom I/O buffer code that takes a fraction of the size. This means that static builds will be smaller, but non-static builds will be bigger, though they will have less linking time. This change is also good because my history implementation was already bypassing `stdio` for good reasons, and unifying the architecture was a win. Another reason for this change is that my `bc` should *always* behave correctly in the presence of signals like `SIGINT`, `SIGTERM`, and `SIGQUIT`. With the addition of my own I/O buffering, I needed to also make sure that the buffers were correctly flushed even when such signals happened. For this reason, I **removed the option to build without signal support**. As a nice side effect of this change, the error handling code could be changed to take advantage of the stack unwinding that signals used. This means that signals and error handling use the same code paths, which means that the stack unwinding is well-tested. (Errors are tested heavily in the test suite.) It also means that functions do not need to return a status code that ***every*** caller needs to check. This eliminated over 100 branches that simply checked return codes and then passed that return code up the stack if necessary. The code bloat savings from this is at least 1700 bytes on `x86_64`, *before* taking into account the extra code from removing `stdio.h`. ## 2.7.2 This is a production release with one major bug fix. The `length()` built-in function can take either a number or an array. If it takes an array, it returns the length of the array. Arrays can be passed by reference. The bug is that the `length()` function would not properly dereference arrays that were references. This is a bug that affects all users. **ALL USERS SHOULD UPDATE `bc`**. ## 2.7.1 This is a production release with fixes for new locales and fixes for compiler warnings on FreeBSD. ## 2.7.0 This is a production release with a bug fix for Linux, new translations, and new features. Bug fixes: * Option parsing in `BC_ENV_ARGS` was broken on Linux in 2.6.1 because `glibc`'s `getopt_long()` is broken. To get around that, and to support long options on every platform, an adapted version of [`optparse`][17] was added. Now, `bc` does not even use `getopt()`. * Parsing `BC_ENV_ARGS` with quotes now works. It isn't the smartest, but it does the job if there are spaces in file names. The following new languages are supported: * Dutch * Polish * Russian * Japanes * Simplified Chinese All of these translations were generated using [DeepL][18], so improvements are welcome. There is only one new feature: **`bc` now has a built-in pseudo-random number generator** (PRNG). The PRNG is seeded, making it useful for applications where `/dev/urandom` does not work because output needs to be reproducible. However, it also uses `/dev/urandom` to seed itself by default, so it will start with a good seed by default. It also outputs 32 bits on 32-bit platforms and 64 bits on 64-bit platforms, far better than the 15 bits of C's `rand()` and `bash`'s `$RANDOM`. In addition, the PRNG can take a bound, and when it gets a bound, it automatically adjusts to remove bias. It can also generate numbers of arbitrary size. (As of the time of release, the largest pseudo-random number generated by this `bc` was generated with a bound of `2^(2^20)`.) ***IMPORTANT: read the [`bc` manual][9] and the [`dc` manual][10] to find out exactly what guarantees the PRNG provides. The underlying implementation is not guaranteed to stay the same, but the guarantees that it provides are guaranteed to stay the same regardless of the implementation.*** On top of that, four functions were added to `bc`'s [extended math library][16] to make using the PRNG easier: * `frand(p)`: Generates a number between `[0,1)` to `p` decimal places. * `ifrand(i, p)`: Generates an integer with bound `i` and adds it to `frand(p)`. * `srand(x)`: Randomizes the sign of `x`. In other words, it flips the sign of `x` with probability `0.5`. * `brand()`: Returns a random boolean value (either `0` or `1`). ## 2.6.1 This is a production release with a bug fix for FreeBSD. The bug was that when `bc` was built without long options, it would give a fatal error on every run. This was caused by a mishandling of `optind`. ## 2.6.0 This release is a production release ***with no bugfixes***. If you do not want to upgrade, you don't have to. No source code changed; the only thing that changed was `lib2.bc`. This release adds one function to the [extended math library][16]: `p(x, y)`, which calculates `x` to the power of `y`, whether or not `y` is an integer. (The `^` operator can only accept integer powers.) This release also includes a couple of small tweaks to the [extended math library][16], mostly to fix returning numbers with too high of `scale`. ## 2.5.3 This release is a production release which addresses inconsistencies in the Portuguese locales. No `bc` code was changed. The issues were that the ISO files used different naming, and also that the files that should have been symlinks were not. I did not catch that because GitHub rendered them the exact same way. ## 2.5.2 This release is a production release. No code was changed, but the build system was changed to allow `CFLAGS` to be given to `CC`, like this: ``` CC="gcc -O3 -march=native" ./configure.sh ``` If this happens, the flags are automatically put into `CFLAGS`, and the compiler is set appropriately. In the example above this means that `CC` will be "gcc" and `CFLAGS` will be "-O3 -march=native". This behavior was added to conform to GNU autotools practices. ## 2.5.1 This is a production release which addresses portability concerns discovered in the `bc` build system. No `bc` code was changed. * Support for Solaris SPARC and AIX were added. * Minor documentations edits were performed. * An option for `configure.sh` was added to disable long options if `getopt_long()` is missing. ## 2.5.0 This is a production release with new translations. No code changed. The translations were contributed by [bugcrazy][15], and they are for Portuguese, both Portugal and Brazil locales. ## 2.4.0 This is a production release primarily aimed at improving `dc`. * A couple of copy and paste errors in the [`dc` manual][10] were fixed. * `dc` startup was optimized by making sure it didn't have to set up `bc`-only things. * The `bc` `&&` and `||` operators were made available to `dc` through the `M` and `m` commands, respectively. * `dc` macros were changed to be tail call-optimized. The last item, tail call optimization, means that if the last thing in a macro is a call to another macro, then the old macro is popped before executing the new macro. This change was made to stop `dc` from consuming more and more memory as macros are executed in a loop. The `q` and `Q` commands still respect the "hidden" macros by way of recording how many macros were removed by tail call optimization. ## 2.3.2 This is a production release meant to fix warnings in the Gentoo `ebuild` by making it possible to disable binary stripping. Other users do *not* need to upgrade. ## 2.3.1 This is a production release. It fixes a bug that caused `-1000000000 < -1` to return `0`. This only happened with negative numbers and only if the value on the left was more negative by a certain amount. That said, this bug *is* a bad bug, and needs to be fixed. **ALL USERS SHOULD UPDATE `bc`**. ## 2.3.0 This is a production release with changes to the build system. ## 2.2.0 This release is a production release. It only has new features and performance improvements. 1. The performance of `sqrt(x)` was improved. 2. The new function `root(x, n)` was added to the extended math library to calculate `n`th roots. 3. The new function `cbrt(x)` was added to the extended math library to calculate cube roots. ## 2.1.3 This is a non-critical release; it just changes the build system, and in non-breaking ways: 1. Linked locale files were changed to link to their sources with a relative link. 2. A bug in `configure.sh` that caused long option parsing to fail under `bash` was fixed. ## 2.1.2 This release is not a critical release. 1. A few codes were added to history. 2. Multiplication was optimized a bit more. 3. Addition and subtraction were both optimized a bit more. ## 2.1.1 This release contains a fix for the test suite made for Linux from Scratch: now the test suite prints `pass` when a test is passed. Other than that, there is no change in this release, so distros and other users do not need to upgrade. ## 2.1.0 This release is a production release. The following bugs were fixed: 1. A `dc` bug that caused stack mishandling was fixed. 2. A warning on OpenBSD was fixed. 3. Bugs in `ctrl+arrow` operations in history were fixed. 4. The ability to paste multiple lines in history was added. 5. A `bc` bug, mishandling of array arguments to functions, was fixed. 6. A crash caused by freeing the wrong pointer was fixed. 7. A `dc` bug where strings, in a rare case, were mishandled in parsing was fixed. In addition, the following changes were made: 1. Division was slightly optimized. 2. An option was added to the build to disable printing of prompts. 3. The special case of empty arguments is now handled. This is to prevent errors in scripts that end up passing empty arguments. 4. A harmless bug was fixed. This bug was that, with the pop instructions (mostly) removed (see below), `bc` would leave extra values on its stack for `void` functions and in a few other cases. These extra items would not affect anything put on the stack and would not cause any sort of crash or even buggy behavior, but they would cause `bc` to take more memory than it needed. On top of the above changes, the following optimizations were added: 1. The need for pop instructions in `bc` was removed. 2. Extra tests on every iteration of the interpreter loop were removed. 3. Updating function and code pointers on every iteration of the interpreter loop was changed to only updating them when necessary. 4. Extra assignments to pointers were removed. Altogether, these changes sped up the interpreter by around 2x. ***NOTE***: This is the last release with new features because this `bc` is now considered complete. From now on, only bug fixes and new translations will be added to this `bc`. ## 2.0.3 This is a production, bug-fix release. Two bugs were fixed in this release: 1. A rare and subtle signal handling bug was fixed. 2. A misbehavior on `0` to a negative power was fixed. The last bug bears some mentioning. When I originally wrote power, I did not thoroughly check its error cases; instead, I had it check if the first number was `0` and then if so, just return `0`. However, `0` to a negative power means that `1` will be divided by `0`, which is an error. I caught this, but only after I stopped being cocky. You see, sometime later, I had noticed that GNU `bc` returned an error, correctly, but I thought it was wrong simply because that's not what my `bc` did. I saw it again later and had a double take. I checked for real, finally, and found out that my `bc` was wrong all along. That was bad on me. But the bug was easy to fix, so it is fixed now. There are two other things in this release: 1. Subtraction was optimized by [Stefan Eßer][14]. 2. Division was also optimized, also by Stefan Eßer. ## 2.0.2 This release contains a fix for a possible overflow in the signal handling. I would be surprised if any users ran into it because it would only happen after 2 billion (`2^31-1`) `SIGINT`'s, but I saw it and had to fix it. ## 2.0.1 This release contains very few things that will apply to any users. 1. A slight bug in `dc`'s interactive mode was fixed. 2. A bug in the test suite that was only triggered on NetBSD was fixed. 3. **The `-P`/`--no-prompt` option** was added for users that do not want a prompt. 4. A `make check` target was added as an alias for `make test`. 5. `dc` got its own read prompt: `?> `. ## 2.0.0 This release is a production release. This release is also a little different from previous releases. From here on out, I do not plan on adding any more features to this `bc`; I believe that it is complete. However, there may be bug fix releases in the future, if I or any others manage to find bugs. This release has only a few new features: 1. `atan2(y, x)` was added to the extended math library as both `a2(y, x)` and `atan2(y, x)`. 2. Locales were fixed. 3. A **POSIX shell-compatible script was added as an alternative to compiling `gen/strgen.c`** on a host machine. More details about making the choice between the two can be found by running `./configure.sh --help` or reading the [build manual][13]. 4. Multiplication was optimized by using **diagonal multiplication**, rather than straight brute force. 5. The `locale_install.sh` script was fixed. 6. `dc` was given the ability to **use the environment variable `DC_ENV_ARGS`**. 7. `dc` was also given the ability to **use the `-i` or `--interactive`** options. 8. Printing the prompt was fixed so that it did not print when it shouldn't. 9. Signal handling was fixed. 10. **Handling of `SIGTERM` and `SIGQUIT`** was fixed. 11. The **built-in functions `maxibase()`, `maxobase()`, and `maxscale()`** (the commands `T`, `U`, `V` in `dc`, respectively) were added to allow scripts to query for the max allowable values of those globals. 12. Some incompatibilities with POSIX were fixed. In addition, this release is `2.0.0` for a big reason: the internal format for numbers changed. They used to be a `char` array. Now, they are an array of larger integers, packing more decimal digits into each integer. This has delivered ***HUGE*** performance improvements, especially for multiplication, division, and power. This `bc` should now be the fastest `bc` available, but I may be wrong. ## 1.2.8 This release contains a fix for a harmless bug (it is harmless in that it still works, but it just copies extra data) in the [`locale_install.sh`][12] script. ## 1.2.7 This version contains fixes for the build on Arch Linux. ## 1.2.6 This release removes the use of `local` in shell scripts because it's not POSIX shell-compatible, and also updates a man page that should have been updated a long time ago but was missed. ## 1.2.5 This release contains some missing locale `*.msg` files. ## 1.2.4 This release contains a few bug fixes and new French translations. ## 1.2.3 This release contains a fix for a bug: use of uninitialized data. Such data was only used when outputting an error message, but I am striving for perfection. As Michelangelo said, "Trifles make perfection, and perfection is no trifle." ## 1.2.2 This release contains fixes for OpenBSD. ## 1.2.1 This release contains bug fixes for some rare bugs. ## 1.2.0 This is a production release. There have been several changes since `1.1.0`: 1. The build system had some changes. 2. Locale support has been added. (Patches welcome for translations.) 3. **The ability to turn `ibase`, `obase`, and `scale` into stacks** was added with the `-g` command-line option. (See the [`bc` manual][9] for more details.) 4. Support for compiling on Mac OSX out of the box was added. 5. The extended math library got `t(x)`, `ceil(x)`, and some aliases. 6. The extended math library also got `r2d(x)` (for converting from radians to degrees) and `d2r(x)` (for converting from degrees to radians). This is to allow using degrees with the standard library. 7. Both calculators now accept numbers in **scientific notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details. 8. Both calculators can **output in either scientific or engineering notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details. 9. Some inefficiencies were removed. 10. Some bugs were fixed. 11. Some bugs in the extended library were fixed. 12. Some defects from [Coverity Scan][11] were fixed. ## 1.1.4 This release contains a fix to the build system that allows it to build on older versions of `glibc`. ## 1.1.3 This release contains a fix for a bug in the test suite where `bc` tests and `dc` tests could not be run in parallel. ## 1.1.2 This release has a fix for a history bug; the down arrow did not work. ## 1.1.1 This release fixes a bug in the `1.1.0` build system. The source is exactly the same. The bug that was fixed was a failure to install if no `EXECSUFFIX` was used. ## 1.1.0 This is a production release. However, many new features were added since `1.0`. 1. **The build system has been changed** to use a custom, POSIX shell-compatible configure script ([`configure.sh`][6]) to generate a POSIX make-compatible `Makefile`, which means that `bc` and `dc` now build out of the box on any POSIX-compatible system. 2. Out-of-memory and output errors now cause the `bc` to report the error, clean up, and die, rather than just reporting and trying to continue. 3. **Strings and constants are now garbage collected** when possible. 4. Signal handling and checking has been made more simple and more thorough. 5. `BcGlobals` was refactored into `BcVm` and `BcVm` was made global. Some procedure names were changed to reflect its difference to everything else. 6. Addition got a speed improvement. 7. Some common code for addition and multiplication was refactored into its own procedure. 8. A bug was removed where `dc` could have been selected, but the internal `#define` that returned `true` for a query about `dc` would not have returned `true`. 9. Useless calls to `bc_num_zero()` were removed. 10. **History support was added.** The history support is based off of a [UTF-8 aware fork][7] of [`linenoise`][8], which has been customized with `bc`'s own data structures and signal handling. 11. Generating C source from the math library now removes tabs from the library, shrinking the size of the executable. 12. The math library was shrunk. 13. Error handling and reporting was improved. 14. Reallocations were reduced by giving access to the request size for each operation. 15. **`abs()` (`b` command for `dc`) was added as a builtin.** 16. Both calculators were tested on FreeBSD. 17. Many obscure parse bugs were fixed. 18. Markdown and man page manuals were added, and the man pages are installed by `make install`. 19. Executable size was reduced, though the added features probably made the executable end up bigger. 20. **GNU-style array references were added as a supported feature.** 21. Allocations were reduced. 22. **New operators were added**: `$` (`$` for `dc`), `@` (`@` for `dc`), `@=`, `<<` (`H` for `dc`), `<<=`, `>>` (`h` for `dc`), and `>>=`. See the [`bc` manual][9] and the [`dc` manual][10] for more details. 23. **An extended math library was added.** This library contains code that makes it so I can replace my desktop calculator with this `bc`. See the [`bc` manual][3] for more details. 24. Support for all capital letters as numbers was added. 25. **Support for GNU-style void functions was added.** 26. A bug fix for improper handling of function parameters was added. 27. Precedence for the or (`||`) operator was changed to match GNU `bc`. 28. `dc` was given an explicit negation command. 29. `dc` was changed to be able to handle strings in arrays. ## 1.1 Release Candidate 3 This release is the eighth release candidate for 1.1, though it is the third release candidate meant as a general release candidate. The new code has not been tested as thoroughly as it should for release. ## 1.1 Release Candidate 2 This release is the seventh release candidate for 1.1, though it is the second release candidate meant as a general release candidate. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 5 This release is the sixth release candidate for 1.1, though it is the fifth release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 4 This release is the fifth release candidate for 1.1, though it is the fourth release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 3 This release is the fourth release candidate for 1.1, though it is the third release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 2 This release is the third release candidate for 1.1, though it is the second release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 1 This release is the second release candidate for 1.1, though it is meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 Release Candidate 1 This is the first release candidate for 1.1. The new code has not been tested as thoroughly as it should for release. ## 1.0 This is the first non-beta release. `bc` is ready for production use. As such, a lot has changed since 0.5. 1. `dc` has been added. It has been tested even more thoroughly than `bc` was for `0.5`. It does not have the `!` command, and for security reasons, it never will, so it is complete. 2. `bc` has been more thoroughly tested. An entire section of the test suite (for both programs) has been added to test for errors. 3. A prompt (`>>> `) has been added for interactive mode, making it easier to see inputs and outputs. 4. Interrupt handling has been improved, including elimination of race conditions (as much as possible). 5. MinGW and [Windows Subsystem for Linux][1] support has been added (see [xstatic][2] for binaries). 6. Memory leaks and errors have been eliminated (as far as ASan and Valgrind can tell). 7. Crashes have been eliminated (as far as [afl][3] can tell). 8. Karatsuba multiplication was added (and thoroughly) tested, speeding up multiplication and power by orders of magnitude. 9. Performance was further enhanced by using a "divmod" function to reduce redundant divisions and by removing superfluous `memset()` calls. 10. To switch between Karatsuba and `O(n^2)` multiplication, the config variable `BC_NUM_KARATSUBA_LEN` was added. It is set to a sane default, but the optimal number can be found with [`karatsuba.py`][4] (requires Python 3) and then configured through `make`. 11. The random math test generator script was changed to Python 3 and improved. `bc` and `dc` have together been run through 30+ million random tests. 12. All known math bugs have been fixed, including out of control memory allocations in `sine` and `cosine` (that was actually a parse bug), certain cases of infinite loop on square root, and slight inaccuracies (as much as possible; see the [README][5]) in transcendental functions. 13. Parsing has been fixed as much as possible. 14. Test coverage was improved to 94.8%. The only paths not covered are ones that happen when `malloc()` or `realloc()` fails. 15. An extension to get the length of an array was added. 16. The boolean not (`!`) had its precedence change to match negation. 17. Data input was hardened. 18. `bc` was made fully compliant with POSIX when the `-s` flag is used or `POSIXLY_CORRECT` is defined. 19. Error handling was improved. 20. `bc` now checks that files it is given are not directories. ## 1.0 Release Candidate 7 This is the seventh release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 6. ## 1.0 Release Candidate 6 This is the sixth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 5. ## 1.0 Release Candidate 5 This is the fifth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 4. ## 1.0 Release Candidate 4 This is the fourth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 3. ## 1.0 Release Candidate 3 This is the third release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 2. ## 1.0 Release Candidate 2 This is the second release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 1. ## 1.0 Release Candidate 1 This is the first Release Candidate for 1.0. `bc` is complete, with `dc`, but it is not tested. ## 0.5 This beta release completes more features, but it is still not complete nor tested as thoroughly as necessary. ## 0.4.1 This beta release fixes a few bugs in 0.4. ## 0.4 This is a beta release. It does not have the complete set of features, and it is not thoroughly tested. [1]: https://docs.microsoft.com/en-us/windows/wsl/install-win10 [2]: https://pkg.musl.cc/bc/ [3]: http://lcamtuf.coredump.cx/afl/ [4]: ./scripts/karatsuba.py [5]: ./README.md [6]: ./configure.sh [7]: https://github.com/rain-1/linenoise-mob [8]: https://github.com/antirez/linenoise [9]: ./manuals/bc/A.1.md [10]: ./manuals/dc/A.1.md [11]: https://scan.coverity.com/projects/gavinhoward-bc [12]: ./scripts/locale_install.sh [13]: ./manuals/build.md [14]: https://github.com/stesser [15]: https://github.com/bugcrazy [16]: ./manuals/bc/A.1.md#extended-library [17]: https://github.com/skeeto/optparse [18]: https://www.deepl.com/translator [19]: ./manuals/benchmarks.md [20]: https://github.com/apjanke/ronn-ng [21]: https://pandoc.org/ [22]: ./scripts/locale_uninstall.sh diff --git a/include/version.h b/include/version.h index a7d1640a87a2..4621b50bcbeb 100644 --- a/include/version.h +++ b/include/version.h @@ -1,42 +1,42 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The version of bc. * */ #ifndef BC_VERSION_H #define BC_VERSION_H /// The current version. -#define VERSION 5.2.3 +#define VERSION 5.2.4 #endif // BC_VERSION_H diff --git a/src/data.c b/src/data.c index 959af600c1af..4dc77e7e746c 100644 --- a/src/data.c +++ b/src/data.c @@ -1,1321 +1,1321 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Constant data for bc. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #if !BC_ENABLE_LIBRARY #if BC_ENABLED /// The bc signal message and its length. const char bc_sig_msg[] = "\ninterrupt (type \"quit\" to exit)\n"; const uchar bc_sig_msg_len = (uchar) (sizeof(bc_sig_msg) - 1); #endif // BC_ENABLED #if DC_ENABLED /// The dc signal message and its length. const char dc_sig_msg[] = "\ninterrupt (type \"q\" to exit)\n"; const uchar dc_sig_msg_len = (uchar) (sizeof(dc_sig_msg) - 1); #endif // DC_ENABLED /// The copyright banner. const char bc_copyright[] = - "Copyright (c) 2018-2021 Gavin D. Howard and contributors\n" + "Copyright (c) 2018-2022 Gavin D. Howard and contributors\n" "Report bugs at: https://git.yzena.com/gavin/bc\n\n" "This is free software with ABSOLUTELY NO WARRANTY.\n"; #ifdef __OpenBSD__ #if BC_ENABLE_EXTRA_MATH #if BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio tty unveil"; /// The final pledges with history enabled. const char bc_pledge_end_history[] = "rpath stdio tty"; #else // BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio unveil"; #endif // BC_ENABLE_HISTORY /// The final pledges with history history disabled. const char bc_pledge_end[] = "rpath stdio"; #else // BC_ENABLE_EXTRA_MATH #if BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio tty"; /// The final pledges with history enabled. const char bc_pledge_end_history[] = "stdio tty"; #else // BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio"; #endif // BC_ENABLE_HISTORY /// The final pledges with history history disabled. const char bc_pledge_end[] = "stdio"; #endif // BC_ENABLE_EXTRA_MATH #else // __OpenBSD__ /// The pledges for starting bc. const char bc_pledge_start[] = ""; #if BC_ENABLE_HISTORY /// The final pledges with history enabled. const char bc_pledge_end_history[] = ""; #endif // BC_ENABLE_HISTORY /// The final pledges with history history disabled. const char bc_pledge_end[] = ""; #endif // __OpenBSD__ /// The list of long options. There is a zero set at the end for detecting the /// end. const BcOptLong bc_args_lopt[] = { { "expression", BC_OPT_REQUIRED, 'e' }, { "file", BC_OPT_REQUIRED, 'f' }, { "help", BC_OPT_NONE, 'h' }, { "interactive", BC_OPT_NONE, 'i' }, { "leading-zeroes", BC_OPT_NONE, 'z' }, { "no-line-length", BC_OPT_NONE, 'L' }, { "no-prompt", BC_OPT_NONE, 'P' }, { "no-read-prompt", BC_OPT_NONE, 'R' }, #if BC_ENABLED { "global-stacks", BC_OPT_BC_ONLY, 'g' }, { "mathlib", BC_OPT_BC_ONLY, 'l' }, { "quiet", BC_OPT_BC_ONLY, 'q' }, { "redefine", BC_OPT_REQUIRED_BC_ONLY, 'r' }, { "standard", BC_OPT_BC_ONLY, 's' }, { "warn", BC_OPT_BC_ONLY, 'w' }, #endif // BC_ENABLED { "version", BC_OPT_NONE, 'v' }, { "version", BC_OPT_NONE, 'V' }, #if DC_ENABLED { "extended-register", BC_OPT_DC_ONLY, 'x' }, #endif // DC_ENABLED { NULL, 0, 0 }, }; /// The function header for error messages. const char* const bc_err_func_header = "Function:"; /// The line format string for error messages. const char* const bc_err_line = ":%zu"; /// The default error category strings. const char *bc_errs[] = { "Math error:", "Parse error:", "Runtime error:", "Fatal error:", #if BC_ENABLED "Warning:", #endif // BC_ENABLED }; /// The error category for each error. const uchar bc_err_ids[] = { BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, #if BC_ENABLED BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, #endif // BC_ENABLED }; /// The default error messages. There are NULL pointers because the positions /// must be preserved for the locales. const char* const bc_err_msgs[] = { "negative number", "non-integer number", "overflow: number cannot fit", "divide by 0", "memory allocation failed", "I/O error", "cannot open file: %s", "file is not text: %s", "path is a directory: %s", "bad command-line option: \"%s\"", "option requires an argument: '%c' (\"%s\")", "option takes no arguments: '%c' (\"%s\")", "bad option argument: \"%s\"", "bad ibase: must be [%lu, %lu]", "bad obase: must be [%lu, %lu]", "bad scale: must be [%lu, %lu]", "bad read() expression", "read() call inside of a read() call", "variable or array element is the wrong type", #if DC_ENABLED "stack has too few elements", "stack for register \"%s\" has too few elements", #else // DC_ENABLED NULL, NULL, #endif // DC_ENABLED #if BC_ENABLED "wrong number of parameters; need %zu, have %zu", "undefined function: %s()", "cannot use a void value in an expression", #else NULL, NULL, NULL, #endif // BC_ENABLED "end of file", "bad character '%c'", "string end cannot be found", "comment end cannot be found", "bad token", #if BC_ENABLED "bad expression", "empty expression", "bad print or stream statement", "bad function definition", ("bad assignment: left side must be scale, ibase, " "obase, seed, last, var, or array element"), "no auto variable found", "function parameter or auto \"%s%s\" already exists", "block end cannot be found", "cannot return a value from void function: %s()", "var cannot be a reference: %s", "POSIX does not allow names longer than 1 character: %s", "POSIX does not allow '#' script comments", "POSIX does not allow the following keyword: %s", "POSIX does not allow a period ('.') as a shortcut for the last result", "POSIX requires parentheses around return expressions", "POSIX does not allow the following operator: %s", "POSIX does not allow comparison operators outside if statements or loops", "POSIX requires 0 or 1 comparison operators per condition", "POSIX requires all 3 parts of a for loop to be non-empty", "POSIX requires a newline between a semicolon and a function definition", #if BC_ENABLE_EXTRA_MATH "POSIX does not allow exponential notation", #else NULL, #endif // BC_ENABLE_EXTRA_MATH "POSIX does not allow array references as function parameters", "POSIX does not allow void functions", "POSIX requires the left brace be on the same line as the function header", "POSIX does not allow strings to be assigned to variables or arrays", #endif // BC_ENABLED }; #endif // !BC_ENABLE_LIBRARY /// The destructors corresponding to BcDtorType enum items. const BcVecFree bc_vec_dtors[] = { NULL, bc_vec_free, bc_num_free, #if !BC_ENABLE_LIBRARY #ifndef NDEBUG bc_func_free, #endif // NDEBUG bc_slab_free, bc_const_free, bc_result_free, #if BC_ENABLE_HISTORY bc_history_string_free, #endif // BC_ENABLE_HISTORY #else // !BC_ENABLE_LIBRARY bcl_num_destruct, #endif // !BC_ENABLE_LIBRARY }; #if !BC_ENABLE_LIBRARY #if BC_ENABLE_HISTORY /// A flush type for not clearing current extras but not saving new ones either. const BcFlushType bc_flush_none = BC_FLUSH_NO_EXTRAS_NO_CLEAR; /// A flush type for clearing extras and not saving new ones. const BcFlushType bc_flush_err = BC_FLUSH_NO_EXTRAS_CLEAR; /// A flush type for clearing previous extras and saving new ones. const BcFlushType bc_flush_save = BC_FLUSH_SAVE_EXTRAS_CLEAR; #endif // BC_ENABLE_HISTORY #if BC_ENABLE_HISTORY /// A list of known bad terminals. const char *bc_history_bad_terms[] = { "dumb", "cons25", "emacs", NULL }; /// A constant for tabs and its length. My tab handling is dumb and always /// outputs the entire thing. const char bc_history_tab[] = " "; const size_t bc_history_tab_len = sizeof(bc_history_tab) - 1; /// A list of wide chars. These are listed in ascending order for efficiency. const uint32_t bc_history_wchars[][2] = { { 0x1100, 0x115F }, { 0x231A, 0x231B }, { 0x2329, 0x232A }, { 0x23E9, 0x23EC }, { 0x23F0, 0x23F0 }, { 0x23F3, 0x23F3 }, { 0x25FD, 0x25FE }, { 0x2614, 0x2615 }, { 0x2648, 0x2653 }, { 0x267F, 0x267F }, { 0x2693, 0x2693 }, { 0x26A1, 0x26A1 }, { 0x26AA, 0x26AB }, { 0x26BD, 0x26BE }, { 0x26C4, 0x26C5 }, { 0x26CE, 0x26CE }, { 0x26D4, 0x26D4 }, { 0x26EA, 0x26EA }, { 0x26F2, 0x26F3 }, { 0x26F5, 0x26F5 }, { 0x26FA, 0x26FA }, { 0x26FD, 0x26FD }, { 0x2705, 0x2705 }, { 0x270A, 0x270B }, { 0x2728, 0x2728 }, { 0x274C, 0x274C }, { 0x274E, 0x274E }, { 0x2753, 0x2755 }, { 0x2757, 0x2757 }, { 0x2795, 0x2797 }, { 0x27B0, 0x27B0 }, { 0x27BF, 0x27BF }, { 0x2B1B, 0x2B1C }, { 0x2B50, 0x2B50 }, { 0x2B55, 0x2B55 }, { 0x2E80, 0x2E99 }, { 0x2E9B, 0x2EF3 }, { 0x2F00, 0x2FD5 }, { 0x2FF0, 0x2FFB }, { 0x3001, 0x303E }, { 0x3041, 0x3096 }, { 0x3099, 0x30FF }, { 0x3105, 0x312D }, { 0x3131, 0x318E }, { 0x3190, 0x31BA }, { 0x31C0, 0x31E3 }, { 0x31F0, 0x321E }, { 0x3220, 0x3247 }, { 0x3250, 0x32FE }, { 0x3300, 0x4DBF }, { 0x4E00, 0xA48C }, { 0xA490, 0xA4C6 }, { 0xA960, 0xA97C }, { 0xAC00, 0xD7A3 }, { 0xF900, 0xFAFF }, { 0xFE10, 0xFE19 }, { 0xFE30, 0xFE52 }, { 0xFE54, 0xFE66 }, { 0xFE68, 0xFE6B }, { 0x16FE0, 0x16FE0 }, { 0x17000, 0x187EC }, { 0x18800, 0x18AF2 }, { 0x1B000, 0x1B001 }, { 0x1F004, 0x1F004 }, { 0x1F0CF, 0x1F0CF }, { 0x1F18E, 0x1F18E }, { 0x1F191, 0x1F19A }, { 0x1F200, 0x1F202 }, { 0x1F210, 0x1F23B }, { 0x1F240, 0x1F248 }, { 0x1F250, 0x1F251 }, { 0x1F300, 0x1F320 }, { 0x1F32D, 0x1F335 }, { 0x1F337, 0x1F37C }, { 0x1F37E, 0x1F393 }, { 0x1F3A0, 0x1F3CA }, { 0x1F3CF, 0x1F3D3 }, { 0x1F3E0, 0x1F3F0 }, { 0x1F3F4, 0x1F3F4 }, { 0x1F3F8, 0x1F43E }, { 0x1F440, 0x1F440 }, { 0x1F442, 0x1F4FC }, { 0x1F4FF, 0x1F53D }, { 0x1F54B, 0x1F54E }, { 0x1F550, 0x1F567 }, { 0x1F57A, 0x1F57A }, { 0x1F595, 0x1F596 }, { 0x1F5A4, 0x1F5A4 }, { 0x1F5FB, 0x1F64F }, { 0x1F680, 0x1F6C5 }, { 0x1F6CC, 0x1F6CC }, { 0x1F6D0, 0x1F6D2 }, { 0x1F6EB, 0x1F6EC }, { 0x1F6F4, 0x1F6F6 }, { 0x1F910, 0x1F91E }, { 0x1F920, 0x1F927 }, { 0x1F930, 0x1F930 }, { 0x1F933, 0x1F93E }, { 0x1F940, 0x1F94B }, { 0x1F950, 0x1F95E }, { 0x1F980, 0x1F991 }, { 0x1F9C0, 0x1F9C0 }, { 0x20000, 0x2FFFD }, { 0x30000, 0x3FFFD }, }; /// The length of the wide chars list. const size_t bc_history_wchars_len = sizeof(bc_history_wchars) / sizeof(bc_history_wchars[0]); /// A list of combining characters in Unicode. These are listed in ascending /// order for efficiency. const uint32_t bc_history_combo_chars[] = { 0x0300,0x0301,0x0302,0x0303,0x0304,0x0305,0x0306,0x0307, 0x0308,0x0309,0x030A,0x030B,0x030C,0x030D,0x030E,0x030F, 0x0310,0x0311,0x0312,0x0313,0x0314,0x0315,0x0316,0x0317, 0x0318,0x0319,0x031A,0x031B,0x031C,0x031D,0x031E,0x031F, 0x0320,0x0321,0x0322,0x0323,0x0324,0x0325,0x0326,0x0327, 0x0328,0x0329,0x032A,0x032B,0x032C,0x032D,0x032E,0x032F, 0x0330,0x0331,0x0332,0x0333,0x0334,0x0335,0x0336,0x0337, 0x0338,0x0339,0x033A,0x033B,0x033C,0x033D,0x033E,0x033F, 0x0340,0x0341,0x0342,0x0343,0x0344,0x0345,0x0346,0x0347, 0x0348,0x0349,0x034A,0x034B,0x034C,0x034D,0x034E,0x034F, 0x0350,0x0351,0x0352,0x0353,0x0354,0x0355,0x0356,0x0357, 0x0358,0x0359,0x035A,0x035B,0x035C,0x035D,0x035E,0x035F, 0x0360,0x0361,0x0362,0x0363,0x0364,0x0365,0x0366,0x0367, 0x0368,0x0369,0x036A,0x036B,0x036C,0x036D,0x036E,0x036F, 0x0483,0x0484,0x0485,0x0486,0x0487,0x0591,0x0592,0x0593, 0x0594,0x0595,0x0596,0x0597,0x0598,0x0599,0x059A,0x059B, 0x059C,0x059D,0x059E,0x059F,0x05A0,0x05A1,0x05A2,0x05A3, 0x05A4,0x05A5,0x05A6,0x05A7,0x05A8,0x05A9,0x05AA,0x05AB, 0x05AC,0x05AD,0x05AE,0x05AF,0x05B0,0x05B1,0x05B2,0x05B3, 0x05B4,0x05B5,0x05B6,0x05B7,0x05B8,0x05B9,0x05BA,0x05BB, 0x05BC,0x05BD,0x05BF,0x05C1,0x05C2,0x05C4,0x05C5,0x05C7, 0x0610,0x0611,0x0612,0x0613,0x0614,0x0615,0x0616,0x0617, 0x0618,0x0619,0x061A,0x064B,0x064C,0x064D,0x064E,0x064F, 0x0650,0x0651,0x0652,0x0653,0x0654,0x0655,0x0656,0x0657, 0x0658,0x0659,0x065A,0x065B,0x065C,0x065D,0x065E,0x065F, 0x0670,0x06D6,0x06D7,0x06D8,0x06D9,0x06DA,0x06DB,0x06DC, 0x06DF,0x06E0,0x06E1,0x06E2,0x06E3,0x06E4,0x06E7,0x06E8, 0x06EA,0x06EB,0x06EC,0x06ED,0x0711,0x0730,0x0731,0x0732, 0x0733,0x0734,0x0735,0x0736,0x0737,0x0738,0x0739,0x073A, 0x073B,0x073C,0x073D,0x073E,0x073F,0x0740,0x0741,0x0742, 0x0743,0x0744,0x0745,0x0746,0x0747,0x0748,0x0749,0x074A, 0x07A6,0x07A7,0x07A8,0x07A9,0x07AA,0x07AB,0x07AC,0x07AD, 0x07AE,0x07AF,0x07B0,0x07EB,0x07EC,0x07ED,0x07EE,0x07EF, 0x07F0,0x07F1,0x07F2,0x07F3,0x0816,0x0817,0x0818,0x0819, 0x081B,0x081C,0x081D,0x081E,0x081F,0x0820,0x0821,0x0822, 0x0823,0x0825,0x0826,0x0827,0x0829,0x082A,0x082B,0x082C, 0x082D,0x0859,0x085A,0x085B,0x08D4,0x08D5,0x08D6,0x08D7, 0x08D8,0x08D9,0x08DA,0x08DB,0x08DC,0x08DD,0x08DE,0x08DF, 0x08E0,0x08E1,0x08E3,0x08E4,0x08E5,0x08E6,0x08E7,0x08E8, 0x08E9,0x08EA,0x08EB,0x08EC,0x08ED,0x08EE,0x08EF,0x08F0, 0x08F1,0x08F2,0x08F3,0x08F4,0x08F5,0x08F6,0x08F7,0x08F8, 0x08F9,0x08FA,0x08FB,0x08FC,0x08FD,0x08FE,0x08FF,0x0900, 0x0901,0x0902,0x093A,0x093C,0x0941,0x0942,0x0943,0x0944, 0x0945,0x0946,0x0947,0x0948,0x094D,0x0951,0x0952,0x0953, 0x0954,0x0955,0x0956,0x0957,0x0962,0x0963,0x0981,0x09BC, 0x09C1,0x09C2,0x09C3,0x09C4,0x09CD,0x09E2,0x09E3,0x0A01, 0x0A02,0x0A3C,0x0A41,0x0A42,0x0A47,0x0A48,0x0A4B,0x0A4C, 0x0A4D,0x0A51,0x0A70,0x0A71,0x0A75,0x0A81,0x0A82,0x0ABC, 0x0AC1,0x0AC2,0x0AC3,0x0AC4,0x0AC5,0x0AC7,0x0AC8,0x0ACD, 0x0AE2,0x0AE3,0x0B01,0x0B3C,0x0B3F,0x0B41,0x0B42,0x0B43, 0x0B44,0x0B4D,0x0B56,0x0B62,0x0B63,0x0B82,0x0BC0,0x0BCD, 0x0C00,0x0C3E,0x0C3F,0x0C40,0x0C46,0x0C47,0x0C48,0x0C4A, 0x0C4B,0x0C4C,0x0C4D,0x0C55,0x0C56,0x0C62,0x0C63,0x0C81, 0x0CBC,0x0CBF,0x0CC6,0x0CCC,0x0CCD,0x0CE2,0x0CE3,0x0D01, 0x0D41,0x0D42,0x0D43,0x0D44,0x0D4D,0x0D62,0x0D63,0x0DCA, 0x0DD2,0x0DD3,0x0DD4,0x0DD6,0x0E31,0x0E34,0x0E35,0x0E36, 0x0E37,0x0E38,0x0E39,0x0E3A,0x0E47,0x0E48,0x0E49,0x0E4A, 0x0E4B,0x0E4C,0x0E4D,0x0E4E,0x0EB1,0x0EB4,0x0EB5,0x0EB6, 0x0EB7,0x0EB8,0x0EB9,0x0EBB,0x0EBC,0x0EC8,0x0EC9,0x0ECA, 0x0ECB,0x0ECC,0x0ECD,0x0F18,0x0F19,0x0F35,0x0F37,0x0F39, 0x0F71,0x0F72,0x0F73,0x0F74,0x0F75,0x0F76,0x0F77,0x0F78, 0x0F79,0x0F7A,0x0F7B,0x0F7C,0x0F7D,0x0F7E,0x0F80,0x0F81, 0x0F82,0x0F83,0x0F84,0x0F86,0x0F87,0x0F8D,0x0F8E,0x0F8F, 0x0F90,0x0F91,0x0F92,0x0F93,0x0F94,0x0F95,0x0F96,0x0F97, 0x0F99,0x0F9A,0x0F9B,0x0F9C,0x0F9D,0x0F9E,0x0F9F,0x0FA0, 0x0FA1,0x0FA2,0x0FA3,0x0FA4,0x0FA5,0x0FA6,0x0FA7,0x0FA8, 0x0FA9,0x0FAA,0x0FAB,0x0FAC,0x0FAD,0x0FAE,0x0FAF,0x0FB0, 0x0FB1,0x0FB2,0x0FB3,0x0FB4,0x0FB5,0x0FB6,0x0FB7,0x0FB8, 0x0FB9,0x0FBA,0x0FBB,0x0FBC,0x0FC6,0x102D,0x102E,0x102F, 0x1030,0x1032,0x1033,0x1034,0x1035,0x1036,0x1037,0x1039, 0x103A,0x103D,0x103E,0x1058,0x1059,0x105E,0x105F,0x1060, 0x1071,0x1072,0x1073,0x1074,0x1082,0x1085,0x1086,0x108D, 0x109D,0x135D,0x135E,0x135F,0x1712,0x1713,0x1714,0x1732, 0x1733,0x1734,0x1752,0x1753,0x1772,0x1773,0x17B4,0x17B5, 0x17B7,0x17B8,0x17B9,0x17BA,0x17BB,0x17BC,0x17BD,0x17C6, 0x17C9,0x17CA,0x17CB,0x17CC,0x17CD,0x17CE,0x17CF,0x17D0, 0x17D1,0x17D2,0x17D3,0x17DD,0x180B,0x180C,0x180D,0x1885, 0x1886,0x18A9,0x1920,0x1921,0x1922,0x1927,0x1928,0x1932, 0x1939,0x193A,0x193B,0x1A17,0x1A18,0x1A1B,0x1A56,0x1A58, 0x1A59,0x1A5A,0x1A5B,0x1A5C,0x1A5D,0x1A5E,0x1A60,0x1A62, 0x1A65,0x1A66,0x1A67,0x1A68,0x1A69,0x1A6A,0x1A6B,0x1A6C, 0x1A73,0x1A74,0x1A75,0x1A76,0x1A77,0x1A78,0x1A79,0x1A7A, 0x1A7B,0x1A7C,0x1A7F,0x1AB0,0x1AB1,0x1AB2,0x1AB3,0x1AB4, 0x1AB5,0x1AB6,0x1AB7,0x1AB8,0x1AB9,0x1ABA,0x1ABB,0x1ABC, 0x1ABD,0x1B00,0x1B01,0x1B02,0x1B03,0x1B34,0x1B36,0x1B37, 0x1B38,0x1B39,0x1B3A,0x1B3C,0x1B42,0x1B6B,0x1B6C,0x1B6D, 0x1B6E,0x1B6F,0x1B70,0x1B71,0x1B72,0x1B73,0x1B80,0x1B81, 0x1BA2,0x1BA3,0x1BA4,0x1BA5,0x1BA8,0x1BA9,0x1BAB,0x1BAC, 0x1BAD,0x1BE6,0x1BE8,0x1BE9,0x1BED,0x1BEF,0x1BF0,0x1BF1, 0x1C2C,0x1C2D,0x1C2E,0x1C2F,0x1C30,0x1C31,0x1C32,0x1C33, 0x1C36,0x1C37,0x1CD0,0x1CD1,0x1CD2,0x1CD4,0x1CD5,0x1CD6, 0x1CD7,0x1CD8,0x1CD9,0x1CDA,0x1CDB,0x1CDC,0x1CDD,0x1CDE, 0x1CDF,0x1CE0,0x1CE2,0x1CE3,0x1CE4,0x1CE5,0x1CE6,0x1CE7, 0x1CE8,0x1CED,0x1CF4,0x1CF8,0x1CF9,0x1DC0,0x1DC1,0x1DC2, 0x1DC3,0x1DC4,0x1DC5,0x1DC6,0x1DC7,0x1DC8,0x1DC9,0x1DCA, 0x1DCB,0x1DCC,0x1DCD,0x1DCE,0x1DCF,0x1DD0,0x1DD1,0x1DD2, 0x1DD3,0x1DD4,0x1DD5,0x1DD6,0x1DD7,0x1DD8,0x1DD9,0x1DDA, 0x1DDB,0x1DDC,0x1DDD,0x1DDE,0x1DDF,0x1DE0,0x1DE1,0x1DE2, 0x1DE3,0x1DE4,0x1DE5,0x1DE6,0x1DE7,0x1DE8,0x1DE9,0x1DEA, 0x1DEB,0x1DEC,0x1DED,0x1DEE,0x1DEF,0x1DF0,0x1DF1,0x1DF2, 0x1DF3,0x1DF4,0x1DF5,0x1DFB,0x1DFC,0x1DFD,0x1DFE,0x1DFF, 0x20D0,0x20D1,0x20D2,0x20D3,0x20D4,0x20D5,0x20D6,0x20D7, 0x20D8,0x20D9,0x20DA,0x20DB,0x20DC,0x20E1,0x20E5,0x20E6, 0x20E7,0x20E8,0x20E9,0x20EA,0x20EB,0x20EC,0x20ED,0x20EE, 0x20EF,0x20F0,0x2CEF,0x2CF0,0x2CF1,0x2D7F,0x2DE0,0x2DE1, 0x2DE2,0x2DE3,0x2DE4,0x2DE5,0x2DE6,0x2DE7,0x2DE8,0x2DE9, 0x2DEA,0x2DEB,0x2DEC,0x2DED,0x2DEE,0x2DEF,0x2DF0,0x2DF1, 0x2DF2,0x2DF3,0x2DF4,0x2DF5,0x2DF6,0x2DF7,0x2DF8,0x2DF9, 0x2DFA,0x2DFB,0x2DFC,0x2DFD,0x2DFE,0x2DFF,0x302A,0x302B, 0x302C,0x302D,0x3099,0x309A,0xA66F,0xA674,0xA675,0xA676, 0xA677,0xA678,0xA679,0xA67A,0xA67B,0xA67C,0xA67D,0xA69E, 0xA69F,0xA6F0,0xA6F1,0xA802,0xA806,0xA80B,0xA825,0xA826, 0xA8C4,0xA8C5,0xA8E0,0xA8E1,0xA8E2,0xA8E3,0xA8E4,0xA8E5, 0xA8E6,0xA8E7,0xA8E8,0xA8E9,0xA8EA,0xA8EB,0xA8EC,0xA8ED, 0xA8EE,0xA8EF,0xA8F0,0xA8F1,0xA926,0xA927,0xA928,0xA929, 0xA92A,0xA92B,0xA92C,0xA92D,0xA947,0xA948,0xA949,0xA94A, 0xA94B,0xA94C,0xA94D,0xA94E,0xA94F,0xA950,0xA951,0xA980, 0xA981,0xA982,0xA9B3,0xA9B6,0xA9B7,0xA9B8,0xA9B9,0xA9BC, 0xA9E5,0xAA29,0xAA2A,0xAA2B,0xAA2C,0xAA2D,0xAA2E,0xAA31, 0xAA32,0xAA35,0xAA36,0xAA43,0xAA4C,0xAA7C,0xAAB0,0xAAB2, 0xAAB3,0xAAB4,0xAAB7,0xAAB8,0xAABE,0xAABF,0xAAC1,0xAAEC, 0xAAED,0xAAF6,0xABE5,0xABE8,0xABED,0xFB1E,0xFE00,0xFE01, 0xFE02,0xFE03,0xFE04,0xFE05,0xFE06,0xFE07,0xFE08,0xFE09, 0xFE0A,0xFE0B,0xFE0C,0xFE0D,0xFE0E,0xFE0F,0xFE20,0xFE21, 0xFE22,0xFE23,0xFE24,0xFE25,0xFE26,0xFE27,0xFE28,0xFE29, 0xFE2A,0xFE2B,0xFE2C,0xFE2D,0xFE2E,0xFE2F, 0x101FD,0x102E0,0x10376,0x10377,0x10378,0x10379,0x1037A,0x10A01, 0x10A02,0x10A03,0x10A05,0x10A06,0x10A0C,0x10A0D,0x10A0E,0x10A0F, 0x10A38,0x10A39,0x10A3A,0x10A3F,0x10AE5,0x10AE6,0x11001,0x11038, 0x11039,0x1103A,0x1103B,0x1103C,0x1103D,0x1103E,0x1103F,0x11040, 0x11041,0x11042,0x11043,0x11044,0x11045,0x11046,0x1107F,0x11080, 0x11081,0x110B3,0x110B4,0x110B5,0x110B6,0x110B9,0x110BA,0x11100, 0x11101,0x11102,0x11127,0x11128,0x11129,0x1112A,0x1112B,0x1112D, 0x1112E,0x1112F,0x11130,0x11131,0x11132,0x11133,0x11134,0x11173, 0x11180,0x11181,0x111B6,0x111B7,0x111B8,0x111B9,0x111BA,0x111BB, 0x111BC,0x111BD,0x111BE,0x111CA,0x111CB,0x111CC,0x1122F,0x11230, 0x11231,0x11234,0x11236,0x11237,0x1123E,0x112DF,0x112E3,0x112E4, 0x112E5,0x112E6,0x112E7,0x112E8,0x112E9,0x112EA,0x11300,0x11301, 0x1133C,0x11340,0x11366,0x11367,0x11368,0x11369,0x1136A,0x1136B, 0x1136C,0x11370,0x11371,0x11372,0x11373,0x11374,0x11438,0x11439, 0x1143A,0x1143B,0x1143C,0x1143D,0x1143E,0x1143F,0x11442,0x11443, 0x11444,0x11446,0x114B3,0x114B4,0x114B5,0x114B6,0x114B7,0x114B8, 0x114BA,0x114BF,0x114C0,0x114C2,0x114C3,0x115B2,0x115B3,0x115B4, 0x115B5,0x115BC,0x115BD,0x115BF,0x115C0,0x115DC,0x115DD,0x11633, 0x11634,0x11635,0x11636,0x11637,0x11638,0x11639,0x1163A,0x1163D, 0x1163F,0x11640,0x116AB,0x116AD,0x116B0,0x116B1,0x116B2,0x116B3, 0x116B4,0x116B5,0x116B7,0x1171D,0x1171E,0x1171F,0x11722,0x11723, 0x11724,0x11725,0x11727,0x11728,0x11729,0x1172A,0x1172B,0x11C30, 0x11C31,0x11C32,0x11C33,0x11C34,0x11C35,0x11C36,0x11C38,0x11C39, 0x11C3A,0x11C3B,0x11C3C,0x11C3D,0x11C3F,0x11C92,0x11C93,0x11C94, 0x11C95,0x11C96,0x11C97,0x11C98,0x11C99,0x11C9A,0x11C9B,0x11C9C, 0x11C9D,0x11C9E,0x11C9F,0x11CA0,0x11CA1,0x11CA2,0x11CA3,0x11CA4, 0x11CA5,0x11CA6,0x11CA7,0x11CAA,0x11CAB,0x11CAC,0x11CAD,0x11CAE, 0x11CAF,0x11CB0,0x11CB2,0x11CB3,0x11CB5,0x11CB6,0x16AF0,0x16AF1, 0x16AF2,0x16AF3,0x16AF4,0x16B30,0x16B31,0x16B32,0x16B33,0x16B34, 0x16B35,0x16B36,0x16F8F,0x16F90,0x16F91,0x16F92,0x1BC9D,0x1BC9E, 0x1D167,0x1D168,0x1D169,0x1D17B,0x1D17C,0x1D17D,0x1D17E,0x1D17F, 0x1D180,0x1D181,0x1D182,0x1D185,0x1D186,0x1D187,0x1D188,0x1D189, 0x1D18A,0x1D18B,0x1D1AA,0x1D1AB,0x1D1AC,0x1D1AD,0x1D242,0x1D243, 0x1D244,0x1DA00,0x1DA01,0x1DA02,0x1DA03,0x1DA04,0x1DA05,0x1DA06, 0x1DA07,0x1DA08,0x1DA09,0x1DA0A,0x1DA0B,0x1DA0C,0x1DA0D,0x1DA0E, 0x1DA0F,0x1DA10,0x1DA11,0x1DA12,0x1DA13,0x1DA14,0x1DA15,0x1DA16, 0x1DA17,0x1DA18,0x1DA19,0x1DA1A,0x1DA1B,0x1DA1C,0x1DA1D,0x1DA1E, 0x1DA1F,0x1DA20,0x1DA21,0x1DA22,0x1DA23,0x1DA24,0x1DA25,0x1DA26, 0x1DA27,0x1DA28,0x1DA29,0x1DA2A,0x1DA2B,0x1DA2C,0x1DA2D,0x1DA2E, 0x1DA2F,0x1DA30,0x1DA31,0x1DA32,0x1DA33,0x1DA34,0x1DA35,0x1DA36, 0x1DA3B,0x1DA3C,0x1DA3D,0x1DA3E,0x1DA3F,0x1DA40,0x1DA41,0x1DA42, 0x1DA43,0x1DA44,0x1DA45,0x1DA46,0x1DA47,0x1DA48,0x1DA49,0x1DA4A, 0x1DA4B,0x1DA4C,0x1DA4D,0x1DA4E,0x1DA4F,0x1DA50,0x1DA51,0x1DA52, 0x1DA53,0x1DA54,0x1DA55,0x1DA56,0x1DA57,0x1DA58,0x1DA59,0x1DA5A, 0x1DA5B,0x1DA5C,0x1DA5D,0x1DA5E,0x1DA5F,0x1DA60,0x1DA61,0x1DA62, 0x1DA63,0x1DA64,0x1DA65,0x1DA66,0x1DA67,0x1DA68,0x1DA69,0x1DA6A, 0x1DA6B,0x1DA6C,0x1DA75,0x1DA84,0x1DA9B,0x1DA9C,0x1DA9D,0x1DA9E, 0x1DA9F,0x1DAA1,0x1DAA2,0x1DAA3,0x1DAA4,0x1DAA5,0x1DAA6,0x1DAA7, 0x1DAA8,0x1DAA9,0x1DAAA,0x1DAAB,0x1DAAC,0x1DAAD,0x1DAAE,0x1DAAF, 0x1E000,0x1E001,0x1E002,0x1E003,0x1E004,0x1E005,0x1E006,0x1E008, 0x1E009,0x1E00A,0x1E00B,0x1E00C,0x1E00D,0x1E00E,0x1E00F,0x1E010, 0x1E011,0x1E012,0x1E013,0x1E014,0x1E015,0x1E016,0x1E017,0x1E018, 0x1E01B,0x1E01C,0x1E01D,0x1E01E,0x1E01F,0x1E020,0x1E021,0x1E023, 0x1E024,0x1E026,0x1E027,0x1E028,0x1E029,0x1E02A,0x1E8D0,0x1E8D1, 0x1E8D2,0x1E8D3,0x1E8D4,0x1E8D5,0x1E8D6,0x1E944,0x1E945,0x1E946, 0x1E947,0x1E948,0x1E949,0x1E94A,0xE0100,0xE0101,0xE0102,0xE0103, 0xE0104,0xE0105,0xE0106,0xE0107,0xE0108,0xE0109,0xE010A,0xE010B, 0xE010C,0xE010D,0xE010E,0xE010F,0xE0110,0xE0111,0xE0112,0xE0113, 0xE0114,0xE0115,0xE0116,0xE0117,0xE0118,0xE0119,0xE011A,0xE011B, 0xE011C,0xE011D,0xE011E,0xE011F,0xE0120,0xE0121,0xE0122,0xE0123, 0xE0124,0xE0125,0xE0126,0xE0127,0xE0128,0xE0129,0xE012A,0xE012B, 0xE012C,0xE012D,0xE012E,0xE012F,0xE0130,0xE0131,0xE0132,0xE0133, 0xE0134,0xE0135,0xE0136,0xE0137,0xE0138,0xE0139,0xE013A,0xE013B, 0xE013C,0xE013D,0xE013E,0xE013F,0xE0140,0xE0141,0xE0142,0xE0143, 0xE0144,0xE0145,0xE0146,0xE0147,0xE0148,0xE0149,0xE014A,0xE014B, 0xE014C,0xE014D,0xE014E,0xE014F,0xE0150,0xE0151,0xE0152,0xE0153, 0xE0154,0xE0155,0xE0156,0xE0157,0xE0158,0xE0159,0xE015A,0xE015B, 0xE015C,0xE015D,0xE015E,0xE015F,0xE0160,0xE0161,0xE0162,0xE0163, 0xE0164,0xE0165,0xE0166,0xE0167,0xE0168,0xE0169,0xE016A,0xE016B, 0xE016C,0xE016D,0xE016E,0xE016F,0xE0170,0xE0171,0xE0172,0xE0173, 0xE0174,0xE0175,0xE0176,0xE0177,0xE0178,0xE0179,0xE017A,0xE017B, 0xE017C,0xE017D,0xE017E,0xE017F,0xE0180,0xE0181,0xE0182,0xE0183, 0xE0184,0xE0185,0xE0186,0xE0187,0xE0188,0xE0189,0xE018A,0xE018B, 0xE018C,0xE018D,0xE018E,0xE018F,0xE0190,0xE0191,0xE0192,0xE0193, 0xE0194,0xE0195,0xE0196,0xE0197,0xE0198,0xE0199,0xE019A,0xE019B, 0xE019C,0xE019D,0xE019E,0xE019F,0xE01A0,0xE01A1,0xE01A2,0xE01A3, 0xE01A4,0xE01A5,0xE01A6,0xE01A7,0xE01A8,0xE01A9,0xE01AA,0xE01AB, 0xE01AC,0xE01AD,0xE01AE,0xE01AF,0xE01B0,0xE01B1,0xE01B2,0xE01B3, 0xE01B4,0xE01B5,0xE01B6,0xE01B7,0xE01B8,0xE01B9,0xE01BA,0xE01BB, 0xE01BC,0xE01BD,0xE01BE,0xE01BF,0xE01C0,0xE01C1,0xE01C2,0xE01C3, 0xE01C4,0xE01C5,0xE01C6,0xE01C7,0xE01C8,0xE01C9,0xE01CA,0xE01CB, 0xE01CC,0xE01CD,0xE01CE,0xE01CF,0xE01D0,0xE01D1,0xE01D2,0xE01D3, 0xE01D4,0xE01D5,0xE01D6,0xE01D7,0xE01D8,0xE01D9,0xE01DA,0xE01DB, 0xE01DC,0xE01DD,0xE01DE,0xE01DF,0xE01E0,0xE01E1,0xE01E2,0xE01E3, 0xE01E4,0xE01E5,0xE01E6,0xE01E7,0xE01E8,0xE01E9,0xE01EA,0xE01EB, 0xE01EC,0xE01ED,0xE01EE,0xE01EF, }; /// The length of the combining characters list. const size_t bc_history_combo_chars_len = sizeof(bc_history_combo_chars) / sizeof(bc_history_combo_chars[0]); #endif // BC_ENABLE_HISTORY /// The human-readable name of the main function in bc source code. const char bc_func_main[] = "(main)"; /// The human-readable name of the read function in bc source code. const char bc_func_read[] = "(read)"; #if BC_DEBUG_CODE /// A list of names of instructions for easy debugging output. const char* bc_inst_names[] = { #if BC_ENABLED "BC_INST_INC", "BC_INST_DEC", #endif // BC_ENABLED "BC_INST_NEG", "BC_INST_BOOL_NOT", #if BC_ENABLE_EXTRA_MATH "BC_INST_TRUNC", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_POWER", "BC_INST_MULTIPLY", "BC_INST_DIVIDE", "BC_INST_MODULUS", "BC_INST_PLUS", "BC_INST_MINUS", #if BC_ENABLE_EXTRA_MATH "BC_INST_PLACES", "BC_INST_LSHIFT", "BC_INST_RSHIFT", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_REL_EQ", "BC_INST_REL_LE", "BC_INST_REL_GE", "BC_INST_REL_NE", "BC_INST_REL_LT", "BC_INST_REL_GT", "BC_INST_BOOL_OR", "BC_INST_BOOL_AND", #if BC_ENABLED "BC_INST_ASSIGN_POWER", "BC_INST_ASSIGN_MULTIPLY", "BC_INST_ASSIGN_DIVIDE", "BC_INST_ASSIGN_MODULUS", "BC_INST_ASSIGN_PLUS", "BC_INST_ASSIGN_MINUS", #if BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN_PLACES", "BC_INST_ASSIGN_LSHIFT", "BC_INST_ASSIGN_RSHIFT", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN", "BC_INST_ASSIGN_POWER_NO_VAL", "BC_INST_ASSIGN_MULTIPLY_NO_VAL", "BC_INST_ASSIGN_DIVIDE_NO_VAL", "BC_INST_ASSIGN_MODULUS_NO_VAL", "BC_INST_ASSIGN_PLUS_NO_VAL", "BC_INST_ASSIGN_MINUS_NO_VAL", #if BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN_PLACES_NO_VAL", "BC_INST_ASSIGN_LSHIFT_NO_VAL", "BC_INST_ASSIGN_RSHIFT_NO_VAL", #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED "BC_INST_ASSIGN_NO_VAL", "BC_INST_NUM", "BC_INST_VAR", "BC_INST_ARRAY_ELEM", "BC_INST_ARRAY", "BC_INST_ZERO", "BC_INST_ONE", #if BC_ENABLED "BC_INST_LAST", #endif // BC_ENABLED "BC_INST_IBASE", "BC_INST_OBASE", "BC_INST_SCALE", #if BC_ENABLE_EXTRA_MATH "BC_INST_SEED", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_LENGTH", "BC_INST_SCALE_FUNC", "BC_INST_SQRT", "BC_INST_ABS", #if BC_ENABLE_EXTRA_MATH "BC_INST_IRAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_ASCIIFY", "BC_INST_READ", #if BC_ENABLE_EXTRA_MATH "BC_INST_RAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_MAXIBASE", "BC_INST_MAXOBASE", "BC_INST_MAXSCALE", #if BC_ENABLE_EXTRA_MATH "BC_INST_MAXRAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_PRINT", "BC_INST_PRINT_POP", "BC_INST_STR", #if BC_ENABLED "BC_INST_PRINT_STR", "BC_INST_JUMP", "BC_INST_JUMP_ZERO", "BC_INST_CALL", "BC_INST_RET", "BC_INST_RET0", "BC_INST_RET_VOID", "BC_INST_HALT", #endif // BC_ENABLED "BC_INST_POP", "BC_INST_SWAP", "BC_INST_MODEXP", "BC_INST_DIVMOD", "BC_INST_PRINT_STREAM", #if DC_ENABLED "BC_INST_POP_EXEC", "BC_INST_EXECUTE", "BC_INST_EXEC_COND", "BC_INST_PRINT_STACK", "BC_INST_CLEAR_STACK", "BC_INST_REG_STACK_LEN", "BC_INST_STACK_LEN", "BC_INST_DUPLICATE", "BC_INST_LOAD", "BC_INST_PUSH_VAR", "BC_INST_PUSH_TO_VAR", "BC_INST_QUIT", "BC_INST_NQUIT", "BC_INST_EXEC_STACK_LEN", #endif // DC_ENABLED "BC_INST_INVALID", }; #endif // BC_DEBUG_CODE /// A constant string for 0. const char bc_parse_zero[2] = "0"; /// A constant string for 1. const char bc_parse_one[2] = "1"; #if BC_ENABLED /// A list of keywords for bc. This needs to be updated if keywords change. const BcLexKeyword bc_lex_kws[] = { BC_LEX_KW_ENTRY("auto", 4, true), BC_LEX_KW_ENTRY("break", 5, true), BC_LEX_KW_ENTRY("continue", 8, false), BC_LEX_KW_ENTRY("define", 6, true), BC_LEX_KW_ENTRY("for", 3, true), BC_LEX_KW_ENTRY("if", 2, true), BC_LEX_KW_ENTRY("limits", 6, false), BC_LEX_KW_ENTRY("return", 6, true), BC_LEX_KW_ENTRY("while", 5, true), BC_LEX_KW_ENTRY("halt", 4, false), BC_LEX_KW_ENTRY("last", 4, false), BC_LEX_KW_ENTRY("ibase", 5, true), BC_LEX_KW_ENTRY("obase", 5, true), BC_LEX_KW_ENTRY("scale", 5, true), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("seed", 4, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("length", 6, true), BC_LEX_KW_ENTRY("print", 5, false), BC_LEX_KW_ENTRY("sqrt", 4, true), BC_LEX_KW_ENTRY("abs", 3, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("irand", 5, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("asciify", 7, false), BC_LEX_KW_ENTRY("modexp", 6, false), BC_LEX_KW_ENTRY("divmod", 6, false), BC_LEX_KW_ENTRY("quit", 4, true), BC_LEX_KW_ENTRY("read", 4, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("rand", 4, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("maxibase", 8, false), BC_LEX_KW_ENTRY("maxobase", 8, false), BC_LEX_KW_ENTRY("maxscale", 8, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("maxrand", 7, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("line_length", 11, false), BC_LEX_KW_ENTRY("global_stacks", 13, false), BC_LEX_KW_ENTRY("leading_zero", 12, false), BC_LEX_KW_ENTRY("stream", 6, false), BC_LEX_KW_ENTRY("else", 4, false), }; /// The length of the list of bc keywords. const size_t bc_lex_kws_len = sizeof(bc_lex_kws) / sizeof(BcLexKeyword); #if BC_C11 // This is here to ensure that BC_LEX_NKWS, which is needed for the // redefined_kws in BcVm, is correct. If it's correct under C11, it will be // correct under C99, and I did not know any other way of ensuring they remained // synchronized. static_assert(sizeof(bc_lex_kws) / sizeof(BcLexKeyword) == BC_LEX_NKWS, "BC_LEX_NKWS is wrong."); #endif // BC_C11 /// An array of booleans that correspond to token types. An entry is true if the /// token is valid in an expression, false otherwise. This will need to change /// if tokens change. const uint8_t bc_parse_exprs[] = { // Starts with BC_LEX_EOF. BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, true), // Starts with BC_LEX_OP_MULTIPLY if extra math is enabled, BC_LEX_OP_DIVIDE // otherwise. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), // Starts with BC_LEX_OP_REL_EQ if extra math is enabled, BC_LEX_OP_REL_LT // otherwise. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), #if BC_ENABLE_EXTRA_MATH // Starts with BC_LEX_OP_ASSIGN_POWER. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), // Starts with BC_LEX_OP_ASSIGN_RSHIFT. BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false), // Starts with BC_LEX_RBRACKET. BC_PARSE_EXPR_ENTRY(false, false, false, false, true, true, true, false), // Starts with BC_LEX_KW_BREAK. BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), // Starts with BC_LEX_KW_HALT. BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, false), // Starts with BC_LEX_KW_SQRT. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, false, true), // Starts with BC_LEX_KW_MAXIBASE. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), // Starts with BC_LEX_KW_STREAM. BC_PARSE_EXPR_ENTRY(false, false, 0, 0, 0, 0, 0, 0) #else // BC_ENABLE_EXTRA_MATH // Starts with BC_LEX_OP_ASSIGN_PLUS. BC_PARSE_EXPR_ENTRY(true, true, true, false, false, true, true, false), // Starts with BC_LEX_COMMA. BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, true), // Starts with BC_LEX_KW_AUTO. BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), // Starts with BC_LEX_KW_WHILE. BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, false), // Starts with BC_LEX_KW_SQRT. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, false, true, true), // Starts with BC_LEX_KW_MAXSCALE, BC_PARSE_EXPR_ENTRY(true, true, true, true, true, false, false, 0) #endif // BC_ENABLE_EXTRA_MATH }; /// An array of data for operators that correspond to token types. const uchar bc_parse_ops[] = { BC_PARSE_OP(0, false), BC_PARSE_OP(0, false), BC_PARSE_OP(1, false), BC_PARSE_OP(1, false), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(2, false), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(4, false), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(6, true), BC_PARSE_OP(6, true), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(3, false), BC_PARSE_OP(7, true), BC_PARSE_OP(7, true), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(11, true), BC_PARSE_OP(10, true), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(8, false), }; // These identify what tokens can come after expressions in certain cases. /// The valid next tokens for normal expressions. const BcParseNext bc_parse_next_expr = BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF); /// The valid next tokens for function argument expressions. const BcParseNext bc_parse_next_arg = BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA); /// The valid next tokens for expressions in print statements. const BcParseNext bc_parse_next_print = BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF); /// The valid next tokens for if statement conditions or loop conditions. This /// is used in for loops for the update expression and for builtin function. /// /// The name is an artifact of history, and is related to @a BC_PARSE_REL (see /// include/parse.h). It refers to how POSIX only allows some operators as part /// of the conditional of for loops, while loops, and if statements. const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN); /// The valid next tokens for array element expressions. const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET); /// The valid next tokens for for loop initialization expressions and condition /// expressions. const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON); /// The valid next tokens for read expressions. const BcParseNext bc_parse_next_read = BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF); /// The valid next tokens for the arguments of a builtin function with multiple /// arguments. const BcParseNext bc_parse_next_builtin = BC_PARSE_NEXT(1, BC_LEX_COMMA); #endif // BC_ENABLED #if DC_ENABLED /// A list of instructions that need register arguments in dc. const uint8_t dc_lex_regs[] = { BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE, BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON, BC_LEX_KW_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN, BC_LEX_STORE_PUSH, BC_LEX_REG_STACK_LEVEL, BC_LEX_ARRAY_LENGTH, }; /// The length of the list of register instructions. const size_t dc_lex_regs_len = sizeof(dc_lex_regs) / sizeof(uint8_t); /// A list corresponding to characters starting at double quote ("). If an entry /// is BC_LEX_INVALID, then that character needs extra lexing in dc. If it does /// not, the character can trivially be replaced by the entry. Positions are /// kept because it corresponds to the ASCII table. This may need to be changed /// if tokens change. const uchar dc_lex_tokens[] = { #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_IRAND, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_TRUNC, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_OP_MODULUS, BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_RAND, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_LPAREN, BC_LEX_RPAREN, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_EXEC_STACK_LENGTH, BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LT, BC_LEX_KW_READ, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_PLACES, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_LSHIFT, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_IBASE, #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_SEED, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_SCALE, BC_LEX_LOAD_POP, BC_LEX_OP_BOOL_AND, BC_LEX_OP_BOOL_NOT, BC_LEX_KW_OBASE, BC_LEX_KW_STREAM, BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_KW_MAXIBASE, BC_LEX_KW_MAXOBASE, BC_LEX_KW_MAXSCALE, #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_MAXRAND, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_SCALE_FACTOR, BC_LEX_ARRAY_LENGTH, BC_LEX_KW_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID, BC_LEX_KW_ASCIIFY, BC_LEX_KW_ABS, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE, BC_LEX_KW_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_RSHIFT, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_STORE_IBASE, #if BC_ENABLE_EXTRA_MATH BC_LEX_STORE_SEED, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_STORE_SCALE, BC_LEX_LOAD, BC_LEX_OP_BOOL_OR, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KW_PRINT, BC_LEX_KW_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_KW_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE, BC_LEX_REG_STACK_LEVEL, BC_LEX_STACK_LEVEL, BC_LEX_LBRACE, BC_LEX_KW_MODEXP, BC_LEX_RBRACE, BC_LEX_KW_DIVMOD, BC_LEX_INVALID }; /// A list of instructions that correspond to lex tokens. If an entry is /// BC_INST_INVALID, that lex token needs extra parsing in the dc parser. /// Otherwise, the token can trivially be replaced by the entry. This needs to /// be updated if the tokens change. const uchar dc_parse_insts[] = { BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED BC_INST_INVALID, BC_INST_BOOL_NOT, #if BC_ENABLE_EXTRA_MATH BC_INST_TRUNC, #endif // BC_ENABLE_EXTRA_MATH BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE, BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS, #if BC_ENABLE_EXTRA_MATH BC_INST_PLACES, BC_INST_LSHIFT, BC_INST_RSHIFT, #endif // BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_BOOL_OR, BC_INST_BOOL_AND, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_REL_LT, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE, BC_INST_INVALID, BC_INST_REL_LE, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED BC_INST_IBASE, BC_INST_OBASE, BC_INST_SCALE, #if BC_ENABLE_EXTRA_MATH BC_INST_SEED, #endif // BC_ENABLE_EXTRA_MATH BC_INST_LENGTH, BC_INST_PRINT, BC_INST_SQRT, BC_INST_ABS, #if BC_ENABLE_EXTRA_MATH BC_INST_IRAND, #endif // BC_ENABLE_EXTRA_MATH BC_INST_ASCIIFY, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_QUIT, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_RAND, #endif // BC_ENABLE_EXTRA_MATH BC_INST_MAXIBASE, BC_INST_MAXOBASE, BC_INST_MAXSCALE, #if BC_ENABLE_EXTRA_MATH BC_INST_MAXRAND, #endif // BC_ENABLE_EXTRA_MATH BC_INST_LINE_LENGTH, #if BC_ENABLED BC_INST_INVALID, #endif // BC_ENABLED BC_INST_LEADING_ZERO, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_REL_EQ, BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK, BC_INST_INVALID, BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_PRINT_POP, BC_INST_NQUIT, BC_INST_EXEC_STACK_LEN, BC_INST_SCALE_FUNC, BC_INST_INVALID, }; #endif // DC_ENABLED #endif // !BC_ENABLE_LIBRARY #if BC_ENABLE_EXTRA_MATH /// A constant for the rand multiplier. const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER; #endif // BC_ENABLE_EXTRA_MATH #if BC_LONG_BIT >= 64 /// A constant array for the max of a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax[] = { 709551616U, 446744073U, 18U, }; /// A constant array for the max of 2 times a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax2[] = { 768211456U, 374607431U, 938463463U, 282366920U, 340U, }; #else // BC_LONG_BIT >= 64 /// A constant array for the max of a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax[] = { 7296U, 9496U, 42U, }; /// A constant array for the max of 2 times a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax2[] = { 1616U, 955U, 737U, 6744U, 1844U, }; #endif // BC_LONG_BIT >= 64 /// The size of the bigdig max array. const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig); /// The size of the bigdig max times 2 array. const size_t bc_num_bigdigMax2_size = sizeof(bc_num_bigdigMax2) / sizeof(BcDig); /// A string of digits for easy conversion from characters to digits. const char bc_num_hex_digits[] = "0123456789ABCDEF"; /// An array for easy conversion from exponent to power of 10. const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1] = { 1, 10, 100, 1000, 10000, #if BC_BASE_DIGS > 4 100000, 1000000, 10000000, 100000000, 1000000000, #endif // BC_BASE_DIGS > 4 }; #if !BC_ENABLE_LIBRARY /// An array of functions for binary operators corresponding to the order of /// the instructions for the operators. const BcNumBinaryOp bc_program_ops[] = { bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub, #if BC_ENABLE_EXTRA_MATH bc_num_places, bc_num_lshift, bc_num_rshift, #endif // BC_ENABLE_EXTRA_MATH }; /// An array of functions for binary operators allocation requests corresponding /// to the order of the instructions for the operators. const BcNumBinaryOpReq bc_program_opReqs[] = { bc_num_powReq, bc_num_mulReq, bc_num_divReq, bc_num_divReq, bc_num_addReq, bc_num_addReq, #if BC_ENABLE_EXTRA_MATH bc_num_placesReq, bc_num_placesReq, bc_num_placesReq, #endif // BC_ENABLE_EXTRA_MATH }; /// An array of unary operator functions corresponding to the order of the /// instructions. const BcProgramUnary bc_program_unarys[] = { bc_program_negate, bc_program_not, #if BC_ENABLE_EXTRA_MATH bc_program_trunc, #endif // BC_ENABLE_EXTRA_MATH }; /// A filename for when parsing expressions. const char bc_program_exprs_name[] = ""; /// A filename for when parsing stdin.. const char bc_program_stdin_name[] = ""; /// A ready message for SIGINT catching. const char bc_program_ready_msg[] = "ready for more input\n"; /// The length of the ready message. const size_t bc_program_ready_msg_len = sizeof(bc_program_ready_msg) - 1; /// A list of escape characters that a print statement should treat specially. const char bc_program_esc_chars[] = "ab\\efnqrt"; /// A list of characters corresponding to the escape characters above. const char bc_program_esc_seqs[] = "\a\b\\\\\f\n\"\r\t"; #endif // !BC_ENABLE_LIBRARY diff --git a/src/history.c b/src/history.c index 9f158413efc2..7e2661486a8b 100644 --- a/src/history.c +++ b/src/history.c @@ -1,1818 +1,1848 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Adapted from the following: * * linenoise.c -- guerrilla line editing library against the idea that a * line editing lib needs to be 20,000 lines of C code. * * You can find the original source code at: * http://github.com/antirez/linenoise * * You can find the fork that this code is based on at: * https://github.com/rain-1/linenoise-mob * * ------------------------------------------------------------------------ * * This code is also under the following license: * * Copyright (c) 2010-2016, Salvatore Sanfilippo * Copyright (c) 2010-2013, Pieter Noordhuis * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ------------------------------------------------------------------------ * * Does a number of crazy assumptions that happen to be true in 99.9999% of * the 2010 UNIX computers around. * * References: * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html * * Todo list: * - Filter bogus Ctrl+ combinations. * - Win32 support * * Bloat: * - History search like Ctrl+r in readline? * * List of escape sequences used by this program, we do everything just * with three sequences. In order to be so cheap we may have some * flickering effect with some slow terminal, but the lesser sequences * the more compatible. * * EL (Erase Line) * Sequence: ESC [ n K * Effect: if n is 0 or missing, clear from cursor to end of line * Effect: if n is 1, clear from beginning of line to cursor * Effect: if n is 2, clear entire line * * CUF (CUrsor Forward) * Sequence: ESC [ n C * Effect: moves cursor forward n chars * * CUB (CUrsor Backward) * Sequence: ESC [ n D * Effect: moves cursor backward n chars * * The following is used to get the terminal width if getting * the width with the TIOCGWINSZ ioctl fails * * DSR (Device Status Report) * Sequence: ESC [ 6 n * Effect: reports the current cusor position as ESC [ n ; m R * where n is the row and m is the column * * When multi line mode is enabled, we also use two additional escape * sequences. However multi line editing is disabled by default. * * CUU (CUrsor Up) * Sequence: ESC [ n A * Effect: moves cursor up of n chars. * * CUD (CUrsor Down) * Sequence: ESC [ n B * Effect: moves cursor down of n chars. * * When bc_history_clearScreen() is called, two additional escape sequences * are used in order to clear the screen and position the cursor at home * position. * * CUP (CUrsor Position) * Sequence: ESC [ H * Effect: moves the cursor to upper left corner * * ED (Erase Display) * Sequence: ESC [ 2 J * Effect: clear the whole screen * * ***************************************************************************** * * Code for line history. * */ #if BC_ENABLE_HISTORY #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #include #include #include #include #endif // _WIN32 #include #include #include #include #include #include #if BC_DEBUG_CODE /// A file for outputting to when debugging. BcFile bc_history_debug_fp; /// A buffer for the above file. char *bc_history_debug_buf; #endif // BC_DEBUG_CODE /** * Checks if the code is a wide character. * @param cp The codepoint to check. * @return True if @a cp is a wide character, false otherwise. */ static bool bc_history_wchar(uint32_t cp) { size_t i; for (i = 0; i < bc_history_wchars_len; ++i) { // Ranges are listed in ascending order. Therefore, once the // whole range is higher than the codepoint we're testing, the // codepoint won't be found in any remaining range => bail early. if (bc_history_wchars[i][0] > cp) return false; // Test this range. if (bc_history_wchars[i][0] <= cp && cp <= bc_history_wchars[i][1]) return true; } return false; } /** * Checks if the code is a combining character. * @param cp The codepoint to check. * @return True if @a cp is a combining character, false otherwise. */ static bool bc_history_comboChar(uint32_t cp) { size_t i; for (i = 0; i < bc_history_combo_chars_len; ++i) { // Combining chars are listed in ascending order, so once we pass // the codepoint of interest, we know it's not a combining char. if (bc_history_combo_chars[i] > cp) return false; if (bc_history_combo_chars[i] == cp) return true; } return false; } /** * Gets the length of previous UTF8 character. * @param buf The buffer of characters. * @param pos The index into the buffer. */ static size_t bc_history_prevCharLen(const char *buf, size_t pos) { size_t end = pos; for (pos -= 1; pos < end && (buf[pos] & 0xC0) == 0x80; --pos); return end - (pos >= end ? 0 : pos); } /** * Converts UTF-8 to a Unicode code point. * @param s The string. * @param len The length of the string. * @param cp An out parameter for the codepoint. * @return The number of bytes eaten by the codepoint. */ static size_t bc_history_codePoint(const char *s, size_t len, uint32_t *cp) { if (len) { uchar byte = (uchar) s[0]; // This is literally the UTF-8 decoding algorithm. Look that up if you // don't understand this. if ((byte & 0x80) == 0) { *cp = byte; return 1; } else if ((byte & 0xE0) == 0xC0) { if (len >= 2) { *cp = (((uint32_t) (s[0] & 0x1F)) << 6) | ((uint32_t) (s[1] & 0x3F)); return 2; } } else if ((byte & 0xF0) == 0xE0) { if (len >= 3) { *cp = (((uint32_t) (s[0] & 0x0F)) << 12) | (((uint32_t) (s[1] & 0x3F)) << 6) | ((uint32_t) (s[2] & 0x3F)); return 3; } } else if ((byte & 0xF8) == 0xF0) { if (len >= 4) { *cp = (((uint32_t) (s[0] & 0x07)) << 18) | (((uint32_t) (s[1] & 0x3F)) << 12) | (((uint32_t) (s[2] & 0x3F)) << 6) | ((uint32_t) (s[3] & 0x3F)); return 4; } } else { *cp = 0xFFFD; return 1; } } *cp = 0; return 1; } /** * Gets the length of next grapheme. * @param buf The buffer. * @param buf_len The length of the buffer. * @param pos The index into the buffer. * @param col_len An out parameter for the length of the grapheme on screen. * @return The number of bytes in the grapheme. */ static size_t bc_history_nextLen(const char *buf, size_t buf_len, size_t pos, size_t *col_len) { uint32_t cp; size_t beg = pos; size_t len = bc_history_codePoint(buf + pos, buf_len - pos, &cp); if (bc_history_comboChar(cp)) { BC_UNREACHABLE if (col_len != NULL) *col_len = 0; return 0; } // Store the width of the character on screen. if (col_len != NULL) *col_len = bc_history_wchar(cp) ? 2 : 1; pos += len; // Find the first non-combining character. while (pos < buf_len) { len = bc_history_codePoint(buf + pos, buf_len - pos, &cp); if (!bc_history_comboChar(cp)) return pos - beg; pos += len; } return pos - beg; } /** * Gets the length of previous grapheme. * @param buf The buffer. * @param pos The index into the buffer. * @return The number of bytes in the grapheme. */ static size_t bc_history_prevLen(const char *buf, size_t pos) { size_t end = pos; // Find the first non-combining character. while (pos > 0) { uint32_t cp; size_t len = bc_history_prevCharLen(buf, pos); pos -= len; bc_history_codePoint(buf + pos, len, &cp); // The original linenoise-mob had an extra parameter col_len, like // bc_history_nextLen(), which, if not NULL, was set in this if // statement. However, we always passed NULL, so just skip that. if (!bc_history_comboChar(cp)) return end - pos; } BC_UNREACHABLE return 0; } /** * Reads @a n characters from stdin. * @param buf The buffer to read into. The caller is responsible for making * sure this is big enough for @a n. * @param n The number of characters to read. * @return The number of characters read or less than 0 on error. */ static ssize_t bc_history_read(char *buf, size_t n) { ssize_t ret; BC_SIG_ASSERT_LOCKED; #ifndef _WIN32 do { // We don't care about being interrupted. ret = read(STDIN_FILENO, buf, n); } while (ret == EINTR); #else // _WIN32 bool good; DWORD read; HANDLE hn = GetStdHandle(STD_INPUT_HANDLE); good = ReadConsole(hn, buf, (DWORD) n, &read, NULL); ret = (read != n) ? -1 : 1; #endif // _WIN32 return ret; } /** * Reads a Unicode code point into a buffer. * @param buf The buffer to read into. * @param buf_len The length of the buffer. * @param cp An out parameter for the codepoint. * @param nread An out parameter for the number of bytes read. * @return BC_STATUS_EOF or BC_STATUS_SUCCESS. */ static BcStatus bc_history_readCode(char *buf, size_t buf_len, uint32_t *cp, size_t *nread) { ssize_t n; assert(buf_len >= 1); BC_SIG_LOCK; // Read a byte. n = bc_history_read(buf, 1); BC_SIG_UNLOCK; if (BC_ERR(n <= 0)) goto err; // Get the byte. uchar byte = ((uchar*) buf)[0]; // Once again, this is the UTF-8 decoding algorithm, but it has reads // instead of actual decoding. if ((byte & 0x80) != 0) { if ((byte & 0xE0) == 0xC0) { assert(buf_len >= 2); BC_SIG_LOCK; n = bc_history_read(buf + 1, 1); BC_SIG_UNLOCK; if (BC_ERR(n <= 0)) goto err; } else if ((byte & 0xF0) == 0xE0) { assert(buf_len >= 3); BC_SIG_LOCK; n = bc_history_read(buf + 1, 2); BC_SIG_UNLOCK; if (BC_ERR(n <= 0)) goto err; } else if ((byte & 0xF8) == 0xF0) { assert(buf_len >= 3); BC_SIG_LOCK; n = bc_history_read(buf + 1, 3); BC_SIG_UNLOCK; if (BC_ERR(n <= 0)) goto err; } else { n = -1; goto err; } } // Convert to the codepoint. *nread = bc_history_codePoint(buf, buf_len, cp); return BC_STATUS_SUCCESS; err: // If we get here, we either had a fatal error of EOF. if (BC_ERR(n < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); else *nread = (size_t) n; return BC_STATUS_EOF; } /** * Gets the column length from beginning of buffer to current byte position. * @param buf The buffer. * @param buf_len The length of the buffer. * @param pos The index into the buffer. * @return The number of columns between the beginning of @a buffer to * @a pos. */ static size_t bc_history_colPos(const char *buf, size_t buf_len, size_t pos) { size_t ret = 0, off = 0; // While we haven't reached the offset, get the length of the next grapheme. while (off < pos && off < buf_len) { size_t col_len, len; len = bc_history_nextLen(buf, buf_len, off, &col_len); off += len; ret += col_len; } return ret; } /** * Returns true if the terminal name is in the list of terminals we know are * not able to understand basic escape sequences. * @return True if the terminal is a bad terminal. */ static inline bool bc_history_isBadTerm(void) { size_t i; bool ret = false; char *term = bc_vm_getenv("TERM"); if (term == NULL) return false; for (i = 0; !ret && bc_history_bad_terms[i]; ++i) ret = (!strcasecmp(term, bc_history_bad_terms[i])); bc_vm_getenvFree(term); return ret; } /** * Enables raw mode (1960's black magic). * @param h The history data. */ static void bc_history_enableRaw(BcHistory *h) { // I don't do anything for Windows because in Windows, you set their // equivalent of raw mode and leave it, so I do it in bc_history_init(). #ifndef _WIN32 struct termios raw; int err; assert(BC_TTYIN); if (h->rawMode) return; BC_SIG_LOCK; if (BC_ERR(tcgetattr(STDIN_FILENO, &h->orig_termios) == -1)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); BC_SIG_UNLOCK; // Modify the original mode. raw = h->orig_termios; // Input modes: no break, no CR to NL, no parity check, no strip char, // no start/stop output control. raw.c_iflag &= (unsigned int) (~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)); // Control modes: set 8 bit chars. raw.c_cflag |= (CS8); // Local modes - choing off, canonical off, no extended functions, // no signal chars (^Z,^C). raw.c_lflag &= (unsigned int) (~(ECHO | ICANON | IEXTEN | ISIG)); // Control chars - set return condition: min number of bytes and timer. // We want read to give every single byte, w/o timeout (1 byte, no timer). raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; BC_SIG_LOCK; // Put terminal in raw mode after flushing. do { err = tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); } while (BC_ERR(err < 0) && errno == EINTR); BC_SIG_UNLOCK; if (BC_ERR(err < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); #endif // _WIN32 h->rawMode = true; } /** * Disables raw mode. * @param h The history data. */ static void bc_history_disableRaw(BcHistory *h) { sig_atomic_t lock; if (!h->rawMode) return; BC_SIG_TRYLOCK(lock); #ifndef _WIN32 if (BC_ERR(tcsetattr(STDIN_FILENO, TCSAFLUSH, &h->orig_termios) != -1)) h->rawMode = false; #endif // _WIN32 BC_SIG_TRYUNLOCK(lock); } /** * Uses the ESC [6n escape sequence to query the horizontal cursor position * and return it. On error -1 is returned, on success the position of the * cursor. * @return The horizontal cursor position. */ static size_t bc_history_cursorPos(void) { char buf[BC_HIST_SEQ_SIZE]; char *ptr, *ptr2; size_t cols, rows, i; BC_SIG_ASSERT_LOCKED; // Report cursor location. bc_file_write(&vm.fout, bc_flush_none, "\x1b[6n", 4); bc_file_flush(&vm.fout, bc_flush_none); // Read the response: ESC [ rows ; cols R. for (i = 0; i < sizeof(buf) - 1; ++i) { if (bc_history_read(buf + i, 1) != 1 || buf[i] == 'R') break; } buf[i] = '\0'; // This is basically an error; we didn't get what we were expecting. if (BC_ERR(buf[0] != BC_ACTION_ESC || buf[1] != '[')) return SIZE_MAX; // Parse the rows. ptr = buf + 2; rows = strtoul(ptr, &ptr2, 10); // Here we also didn't get what we were expecting. if (BC_ERR(!rows || ptr2[0] != ';')) return SIZE_MAX; // Parse the columns. ptr = ptr2 + 1; cols = strtoul(ptr, NULL, 10); if (BC_ERR(!cols)) return SIZE_MAX; return cols <= UINT16_MAX ? cols : 0; } /** * Tries to get the number of columns in the current terminal, or assume 80 * if it fails. * @return The number of columns in the terminal. */ static size_t bc_history_columns(void) { #ifndef _WIN32 struct winsize ws; int ret; ret = ioctl(vm.fout.fd, TIOCGWINSZ, &ws); if (BC_ERR(ret == -1 || !ws.ws_col)) { // Calling ioctl() failed. Try to query the terminal itself. size_t start, cols; // Get the initial position so we can restore it later. start = bc_history_cursorPos(); if (BC_ERR(start == SIZE_MAX)) return BC_HIST_DEF_COLS; // Go to right margin and get position. bc_file_write(&vm.fout, bc_flush_none, "\x1b[999C", 6); bc_file_flush(&vm.fout, bc_flush_none); cols = bc_history_cursorPos(); if (BC_ERR(cols == SIZE_MAX)) return BC_HIST_DEF_COLS; // Restore position. if (cols > start) { bc_file_printf(&vm.fout, "\x1b[%zuD", cols - start); bc_file_flush(&vm.fout, bc_flush_none); } return cols; } return ws.ws_col; #else // _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) return 80; return ((size_t) (csbi.srWindow.Right)) - csbi.srWindow.Left + 1; #endif // _WIN32 } /** * Gets the column length of prompt text. This is probably unnecessary because * the prompts that I use are ASCII, but I kept it just in case. * @param prompt The prompt. * @param plen The length of the prompt. * @return The column length of the prompt. */ static size_t bc_history_promptColLen(const char *prompt, size_t plen) { char buf[BC_HIST_MAX_LINE + 1]; size_t buf_len = 0, off = 0; // The original linenoise-mob checked for ANSI escapes here on the prompt. I // know the prompts do not have ANSI escapes. I deleted the code. while (off < plen) buf[buf_len++] = prompt[off++]; return bc_history_colPos(buf, buf_len, buf_len); } /** * Rewrites the currently edited line accordingly to the buffer content, * cursor position, and number of columns of the terminal. * @param h The history data. */ static void bc_history_refresh(BcHistory *h) { char* buf = h->buf.v; size_t colpos, len = BC_HIST_BUF_LEN(h), pos = h->pos, extras_len = 0; BC_SIG_ASSERT_LOCKED; bc_file_flush(&vm.fout, bc_flush_none); // Get to the prompt column position from the left. while(h->pcol + bc_history_colPos(buf, len, pos) >= h->cols) { size_t chlen = bc_history_nextLen(buf, len, 0, NULL); buf += chlen; len -= chlen; pos -= chlen; } // Get to the prompt column position from the right. while (h->pcol + bc_history_colPos(buf, len, len) > h->cols) len -= bc_history_prevLen(buf, len); // Cursor to left edge. bc_file_write(&vm.fout, bc_flush_none, "\r", 1); // Take the extra stuff into account. This is where history makes sure to // preserve stuff that was printed without a newline. if (h->extras.len > 1) { extras_len = h->extras.len - 1; bc_vec_grow(&h->buf, extras_len); len += extras_len; pos += extras_len; bc_file_write(&vm.fout, bc_flush_none, h->extras.v, extras_len); } // Write the prompt, if desired. if (BC_PROMPT) bc_file_write(&vm.fout, bc_flush_none, h->prompt, h->plen); bc_file_write(&vm.fout, bc_flush_none, h->buf.v, len - extras_len); // Erase to right. bc_file_write(&vm.fout, bc_flush_none, "\x1b[0K", 4); // We need to be sure to grow this. if (pos >= h->buf.len - extras_len) bc_vec_grow(&h->buf, pos + extras_len); - // Move cursor to original position. + // Move cursor to original position. Do NOT move the putchar of '\r' to the + // printf with colpos. That causes a bug where the cursor will go to the end + // of the line when there is no prompt. + bc_file_putchar(&vm.fout, bc_flush_none, '\r'); colpos = bc_history_colPos(h->buf.v, len - extras_len, pos) + h->pcol; // Set the cursor position again. - if (colpos) bc_file_printf(&vm.fout, "\r\x1b[%zuC", colpos); + if (colpos) bc_file_printf(&vm.fout, "\x1b[%zuC", colpos); bc_file_flush(&vm.fout, bc_flush_none); } /** * Inserts the character(s) 'c' at cursor current position. * @param h The history data. * @param cbuf The character buffer to copy from. * @param clen The number of characters to copy. */ static void bc_history_edit_insert(BcHistory *h, const char *cbuf, size_t clen) { BC_SIG_ASSERT_LOCKED; bc_vec_grow(&h->buf, clen); // If we are at the end of the line... if (h->pos == BC_HIST_BUF_LEN(h)) { size_t colpos = 0, len; // Copy into the buffer. memcpy(bc_vec_item(&h->buf, h->pos), cbuf, clen); // Adjust the buffer. h->pos += clen; h->buf.len += clen - 1; bc_vec_pushByte(&h->buf, '\0'); // Set the length and column position. len = BC_HIST_BUF_LEN(h) + h->extras.len - 1; colpos = bc_history_promptColLen(h->prompt, h->plen); colpos += bc_history_colPos(h->buf.v, len, len); // Do we have the trivial case? if (colpos < h->cols) { // Avoid a full update of the line in the trivial case. bc_file_write(&vm.fout, bc_flush_none, cbuf, clen); bc_file_flush(&vm.fout, bc_flush_none); } else bc_history_refresh(h); } else { // Amount that we need to move. size_t amt = BC_HIST_BUF_LEN(h) - h->pos; // Move the stuff. memmove(h->buf.v + h->pos + clen, h->buf.v + h->pos, amt); memcpy(h->buf.v + h->pos, cbuf, clen); // Adjust the buffer. h->pos += clen; h->buf.len += clen; h->buf.v[BC_HIST_BUF_LEN(h)] = '\0'; bc_history_refresh(h); } } /** * Moves the cursor to the left. * @param h The history data. */ static void bc_history_edit_left(BcHistory *h) { BC_SIG_ASSERT_LOCKED; // Stop at the left end. if (h->pos <= 0) return; h->pos -= bc_history_prevLen(h->buf.v, h->pos); bc_history_refresh(h); } /** * Moves the cursor to the right. * @param h The history data. */ static void bc_history_edit_right(BcHistory *h) { BC_SIG_ASSERT_LOCKED; // Stop at the right end. if (h->pos == BC_HIST_BUF_LEN(h)) return; h->pos += bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL); bc_history_refresh(h); } /** * Moves the cursor to the end of the current word. * @param h The history data. */ static void bc_history_edit_wordEnd(BcHistory *h) { size_t len = BC_HIST_BUF_LEN(h); BC_SIG_ASSERT_LOCKED; // Don't overflow. if (!len || h->pos >= len) return; // Find the word, then find the end of it. while (h->pos < len && isspace(h->buf.v[h->pos])) h->pos += 1; while (h->pos < len && !isspace(h->buf.v[h->pos])) h->pos += 1; bc_history_refresh(h); } /** * Moves the cursor to the start of the current word. * @param h The history data. */ static void bc_history_edit_wordStart(BcHistory *h) { size_t len = BC_HIST_BUF_LEN(h); BC_SIG_ASSERT_LOCKED; // Stop with no data. if (!len) return; // Find the word, the find the beginning of the word. while (h->pos > 0 && isspace(h->buf.v[h->pos - 1])) h->pos -= 1; while (h->pos > 0 && !isspace(h->buf.v[h->pos - 1])) h->pos -= 1; bc_history_refresh(h); } /** * Moves the cursor to the start of the line. * @param h The history data. */ static void bc_history_edit_home(BcHistory *h) { BC_SIG_ASSERT_LOCKED; // Stop at the beginning. if (!h->pos) return; h->pos = 0; bc_history_refresh(h); } /** * Moves the cursor to the end of the line. * @param h The history data. */ static void bc_history_edit_end(BcHistory *h) { BC_SIG_ASSERT_LOCKED; // Stop at the end of the line. if (h->pos == BC_HIST_BUF_LEN(h)) return; h->pos = BC_HIST_BUF_LEN(h); bc_history_refresh(h); } /** * Substitutes the currently edited line with the next or previous history * entry as specified by 'dir' (direction). * @param h The history data. * @param dir The direction to substitute; true means previous, false next. */ static void bc_history_edit_next(BcHistory *h, bool dir) { const char *dup, *str; BC_SIG_ASSERT_LOCKED; // Stop if there is no history. if (h->history.len <= 1) return; // Duplicate the buffer. if (h->buf.v[0]) dup = bc_vm_strdup(h->buf.v); else dup = ""; // Update the current history entry before overwriting it with the next one. bc_vec_replaceAt(&h->history, h->history.len - 1 - h->idx, &dup); // Show the new entry. h->idx += (dir == BC_HIST_PREV ? 1 : SIZE_MAX); // Se the index appropriately at the ends. if (h->idx == SIZE_MAX) { h->idx = 0; return; } else if (h->idx >= h->history.len) { h->idx = h->history.len - 1; return; } // Get the string. str = *((char**) bc_vec_item(&h->history, h->history.len - 1 - h->idx)); bc_vec_string(&h->buf, strlen(str), str); assert(h->buf.len > 0); // Set the position at the end. h->pos = BC_HIST_BUF_LEN(h); bc_history_refresh(h); } /** * Deletes the character at the right of the cursor without altering the cursor * position. Basically, this is what happens with the "Delete" keyboard key. * @param h The history data. */ static void bc_history_edit_delete(BcHistory *h) { size_t chlen, len = BC_HIST_BUF_LEN(h); BC_SIG_ASSERT_LOCKED; // If there is no character, skip. if (!len || h->pos >= len) return; // Get the length of the character. chlen = bc_history_nextLen(h->buf.v, len, h->pos, NULL); // Move characters after it into its place. memmove(h->buf.v + h->pos, h->buf.v + h->pos + chlen, len - h->pos - chlen); // Make the buffer valid again. h->buf.len -= chlen; h->buf.v[BC_HIST_BUF_LEN(h)] = '\0'; bc_history_refresh(h); } /** * Deletes the character to the left of the cursor and moves the cursor back one * space. Basically, this is what happens with the "Backspace" keyboard key. * @param h The history data. */ static void bc_history_edit_backspace(BcHistory *h) { size_t chlen, len = BC_HIST_BUF_LEN(h); BC_SIG_ASSERT_LOCKED; // If there are no characters, skip. if (!h->pos || !len) return; // Get the length of the previous character. chlen = bc_history_prevLen(h->buf.v, h->pos); // Move everything back one. memmove(h->buf.v + h->pos - chlen, h->buf.v + h->pos, len - h->pos); // Make the buffer valid again. h->pos -= chlen; h->buf.len -= chlen; h->buf.v[BC_HIST_BUF_LEN(h)] = '\0'; bc_history_refresh(h); } /** * Deletes the previous word, maintaining the cursor at the start of the * current word. * @param h The history data. */ static void bc_history_edit_deletePrevWord(BcHistory *h) { size_t diff, old_pos = h->pos; BC_SIG_ASSERT_LOCKED; // If at the beginning of the line, skip. if (!old_pos) return; // Find the word, then the beginning of the word. while (h->pos > 0 && isspace(h->buf.v[h->pos - 1])) --h->pos; while (h->pos > 0 && !isspace(h->buf.v[h->pos - 1])) --h->pos; // Get the difference in position. diff = old_pos - h->pos; // Move the data back. memmove(h->buf.v + h->pos, h->buf.v + old_pos, BC_HIST_BUF_LEN(h) - old_pos + 1); // Make the buffer valid again. h->buf.len -= diff; bc_history_refresh(h); } /** * Deletes the next word, maintaining the cursor at the same position. * @param h The history data. */ static void bc_history_edit_deleteNextWord(BcHistory *h) { size_t next_end = h->pos, len = BC_HIST_BUF_LEN(h); BC_SIG_ASSERT_LOCKED; // If at the end of the line, skip. if (next_end == len) return; // Find the word, then the end of the word. while (next_end < len && isspace(h->buf.v[next_end])) ++next_end; while (next_end < len && !isspace(h->buf.v[next_end])) ++next_end; // Move the stuff into position. memmove(h->buf.v + h->pos, h->buf.v + next_end, len - next_end); // Make the buffer valid again. h->buf.len -= next_end - h->pos; bc_history_refresh(h); } /** * Swaps two characters, the one under the cursor and the one to the left. * @param h The history data. */ static void bc_history_swap(BcHistory *h) { size_t pcl, ncl; char auxb[5]; BC_SIG_ASSERT_LOCKED; // Get the length of the previous and next characters. pcl = bc_history_prevLen(h->buf.v, h->pos); ncl = bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL); // To perform a swap we need: // * Nonzero char length to the left. // * To not be at the end of the line. if (pcl && h->pos != BC_HIST_BUF_LEN(h) && pcl < 5 && ncl < 5) { // Swap. memcpy(auxb, h->buf.v + h->pos - pcl, pcl); memcpy(h->buf.v + h->pos - pcl, h->buf.v + h->pos, ncl); memcpy(h->buf.v + h->pos - pcl + ncl, auxb, pcl); // Reset the position. h->pos += ((~pcl) + 1) + ncl; bc_history_refresh(h); } } /** * Raises the specified signal. This is a convenience function. * @param h The history data. * @param sig The signal to raise. */ static void bc_history_raise(BcHistory *h, int sig) { // We really don't want to be in raw mode when longjmp()'s are flying. bc_history_disableRaw(h); raise(sig); } /** * Handles escape sequences. This function will make sense if you know VT100 * escape codes; otherwise, it will be confusing. * @param h The history data. */ static void bc_history_escape(BcHistory *h) { char c, seq[3]; BC_SIG_ASSERT_LOCKED; // Read a character into seq. if (BC_ERR(BC_HIST_READ(seq, 1))) return; c = seq[0]; // ESC ? sequences. if (c != '[' && c != 'O') { if (c == 'f') bc_history_edit_wordEnd(h); else if (c == 'b') bc_history_edit_wordStart(h); else if (c == 'd') bc_history_edit_deleteNextWord(h); } else { // Read a character into seq. if (BC_ERR(BC_HIST_READ(seq + 1, 1))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); // ESC [ sequences. if (c == '[') { c = seq[1]; if (c >= '0' && c <= '9') { // Extended escape, read additional byte. if (BC_ERR(BC_HIST_READ(seq + 2, 1))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); - if (seq[2] == '~' && c == '3') bc_history_edit_delete(h); + if (seq[2] == '~') { + + switch(c) { + + case '1': + { + bc_history_edit_home(h); + break; + } + + case '3': + { + bc_history_edit_delete(h); + break; + } + + case '4': + { + bc_history_edit_end(h); + break; + } + + default: + { + break; + } + } + } else if(seq[2] == ';') { // Read two characters into seq. if (BC_ERR(BC_HIST_READ(seq, 2))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); if (seq[0] != '5') return; else if (seq[1] == 'C') bc_history_edit_wordEnd(h); else if (seq[1] == 'D') bc_history_edit_wordStart(h); } } else { switch(c) { // Up. case 'A': { bc_history_edit_next(h, BC_HIST_PREV); break; } // Down. case 'B': { bc_history_edit_next(h, BC_HIST_NEXT); break; } // Right. case 'C': { bc_history_edit_right(h); break; } // Left. case 'D': { bc_history_edit_left(h); break; } // Home. case 'H': case '1': { bc_history_edit_home(h); break; } // End. case 'F': case '4': { bc_history_edit_end(h); break; } case 'd': { bc_history_edit_deleteNextWord(h); break; } } } } // ESC O sequences. else { switch (seq[1]) { case 'A': { bc_history_edit_next(h, BC_HIST_PREV); break; } case 'B': { bc_history_edit_next(h, BC_HIST_NEXT); break; } case 'C': { bc_history_edit_right(h); break; } case 'D': { bc_history_edit_left(h); break; } case 'F': { bc_history_edit_end(h); break; } case 'H': { bc_history_edit_home(h); break; } } } } } /** * Adds a line to the history. * @param h The history data. * @param line The line to add. */ static void bc_history_add(BcHistory *h, char *line) { BC_SIG_ASSERT_LOCKED; // If there is something already there... if (h->history.len) { // Get the previous. char *s = *((char**) bc_vec_item_rev(&h->history, 0)); // Check for, and discard, duplicates. if (!strcmp(s, line)) { free(line); return; } } bc_vec_push(&h->history, &line); } /** * Adds an empty line to the history. This is separate from bc_history_add() * because we don't want it allocating. * @param h The history data. */ static void bc_history_add_empty(BcHistory *h) { BC_SIG_ASSERT_LOCKED; const char *line = ""; // If there is something already there... if (h->history.len) { // Get the previous. char *s = *((char**) bc_vec_item_rev(&h->history, 0)); // Check for, and discard, duplicates. if (!s[0]) return; } bc_vec_push(&h->history, &line); } /** * Resets the history state to nothing. * @param h The history data. */ static void bc_history_reset(BcHistory *h) { BC_SIG_ASSERT_LOCKED; h->oldcolpos = h->pos = h->idx = 0; h->cols = bc_history_columns(); // The latest history entry is always our current buffer, that // initially is just an empty string. bc_history_add_empty(h); // Buffer starts empty. bc_vec_empty(&h->buf); } /** * Prints a control character. * @param h The history data. * @param c The control character to print. */ static void bc_history_printCtrl(BcHistory *h, unsigned int c) { char str[3] = "^A"; const char newline[2] = "\n"; BC_SIG_ASSERT_LOCKED; // Set the correct character. str[1] = (char) (c + 'A' - BC_ACTION_CTRL_A); // Concatenate the string. bc_vec_concat(&h->buf, str); bc_history_refresh(h); // Pop the string. bc_vec_npop(&h->buf, sizeof(str)); bc_vec_pushByte(&h->buf, '\0'); #ifndef _WIN32 if (c != BC_ACTION_CTRL_C && c != BC_ACTION_CTRL_D) #endif // _WIN32 { // We sometimes want to print a newline; for the times we don't; it's // because newlines are taken care of elsewhere. bc_file_write(&vm.fout, bc_flush_none, newline, sizeof(newline) - 1); bc_history_refresh(h); } } /** * Edits a line of history. This function is the core of the line editing * capability of bc history. It expects 'fd' to be already in "raw mode" so that * every key pressed will be returned ASAP to read(). * @param h The history data. * @param prompt The prompt. * @return BC_STATUS_SUCCESS or BC_STATUS_EOF. */ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { BC_SIG_LOCK; bc_history_reset(h); // Don't write the saved output the first time. This is because it has // already been written to output. In other words, don't uncomment the // line below or add anything like it. // bc_file_write(&vm.fout, bc_flush_none, h->extras.v, h->extras.len - 1); // Write the prompt if desired. if (BC_PROMPT) { h->prompt = prompt; h->plen = strlen(prompt); h->pcol = bc_history_promptColLen(prompt, h->plen); bc_file_write(&vm.fout, bc_flush_none, prompt, h->plen); bc_file_flush(&vm.fout, bc_flush_none); } // This is the input loop. for (;;) { BcStatus s; char cbuf[32]; unsigned int c = 0; size_t nread = 0; BC_SIG_UNLOCK; // Read a code. s = bc_history_readCode(cbuf, sizeof(cbuf), &c, &nread); if (BC_ERR(s)) return s; BC_SIG_LOCK; switch (c) { case BC_ACTION_LINE_FEED: case BC_ACTION_ENTER: { // Return the line. bc_vec_pop(&h->history); BC_SIG_UNLOCK; return s; } case BC_ACTION_TAB: { // My tab handling is dumb; it just prints 8 spaces every time. memcpy(cbuf, bc_history_tab, bc_history_tab_len + 1); bc_history_edit_insert(h, cbuf, bc_history_tab_len); break; } #ifndef _WIN32 case BC_ACTION_CTRL_C: { bc_history_printCtrl(h, c); // Quit if the user wants it. if (!BC_SIGINT) { vm.status = BC_STATUS_QUIT; BC_SIG_UNLOCK; BC_JMP; } // Print the ready message. bc_file_write(&vm.fout, bc_flush_none, vm.sigmsg, vm.siglen); bc_file_write(&vm.fout, bc_flush_none, bc_program_ready_msg, bc_program_ready_msg_len); bc_history_reset(h); bc_history_refresh(h); break; } #endif // _WIN32 case BC_ACTION_BACKSPACE: case BC_ACTION_CTRL_H: { bc_history_edit_backspace(h); break; } #ifndef _WIN32 // Act as end-of-file. case BC_ACTION_CTRL_D: { bc_history_printCtrl(h, c); BC_SIG_UNLOCK; return BC_STATUS_EOF; } #endif // _WIN32 // Swaps current character with previous. case BC_ACTION_CTRL_T: { bc_history_swap(h); break; } case BC_ACTION_CTRL_B: { bc_history_edit_left(h); break; } case BC_ACTION_CTRL_F: { bc_history_edit_right(h); break; } case BC_ACTION_CTRL_P: { bc_history_edit_next(h, BC_HIST_PREV); break; } case BC_ACTION_CTRL_N: { bc_history_edit_next(h, BC_HIST_NEXT); break; } case BC_ACTION_ESC: { bc_history_escape(h); break; } // Delete the whole line. case BC_ACTION_CTRL_U: { bc_vec_string(&h->buf, 0, ""); h->pos = 0; bc_history_refresh(h); break; } // Delete from current to end of line. case BC_ACTION_CTRL_K: { bc_vec_npop(&h->buf, h->buf.len - h->pos); bc_vec_pushByte(&h->buf, '\0'); bc_history_refresh(h); break; } // Go to the start of the line. case BC_ACTION_CTRL_A: { bc_history_edit_home(h); break; } // Go to the end of the line. case BC_ACTION_CTRL_E: { bc_history_edit_end(h); break; } // Clear screen. case BC_ACTION_CTRL_L: { bc_file_write(&vm.fout, bc_flush_none, "\x1b[H\x1b[2J", 7); bc_history_refresh(h); break; } // Delete previous word. case BC_ACTION_CTRL_W: { bc_history_edit_deletePrevWord(h); break; } default: { // If we have a control character, print it and raise signals as // needed. if ((c >= BC_ACTION_CTRL_A && c <= BC_ACTION_CTRL_Z) || c == BC_ACTION_CTRL_BSLASH) { bc_history_printCtrl(h, c); #ifndef _WIN32 if (c == BC_ACTION_CTRL_Z) bc_history_raise(h, SIGTSTP); if (c == BC_ACTION_CTRL_S) bc_history_raise(h, SIGSTOP); if (c == BC_ACTION_CTRL_BSLASH) bc_history_raise(h, SIGQUIT); #else // _WIN32 vm.status = BC_STATUS_QUIT; BC_SIG_UNLOCK; BC_JMP; #endif // _WIN32 } // Otherwise, just insert. else bc_history_edit_insert(h, cbuf, nread); break; } } } BC_SIG_UNLOCK; return BC_STATUS_SUCCESS; } /** * Returns true if stdin has more data. This is for multi-line pasting, and it * does not work on Windows. * @param h The history data. */ static inline bool bc_history_stdinHasData(BcHistory *h) { #ifndef _WIN32 int n; return pselect(1, &h->rdset, NULL, NULL, &h->ts, &h->sigmask) > 0 || (ioctl(STDIN_FILENO, FIONREAD, &n) >= 0 && n > 0); #else // _WIN32 return false; #endif // _WIN32 } BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt) { BcStatus s; char* line; assert(vm.fout.len == 0); bc_history_enableRaw(h); do { // Do the edit. s = bc_history_edit(h, prompt); // Print a newline and flush. bc_file_write(&vm.fout, bc_flush_none, "\n", 1); bc_file_flush(&vm.fout, bc_flush_none); BC_SIG_LOCK; // If we actually have data... if (h->buf.v[0]) { // Duplicate it. line = bc_vm_strdup(h->buf.v); // Store it. bc_history_add(h, line); } // Add an empty string. else bc_history_add_empty(h); BC_SIG_UNLOCK; // Concatenate the line to the return vector. bc_vec_concat(vec, h->buf.v); bc_vec_concat(vec, "\n"); } while (!s && bc_history_stdinHasData(h)); assert(!s || s == BC_STATUS_EOF); bc_history_disableRaw(h); return s; } void bc_history_string_free(void *str) { char *s = *((char**) str); BC_SIG_ASSERT_LOCKED; if (s[0]) free(s); } void bc_history_init(BcHistory *h) { #ifdef _WIN32 HANDLE out, in; #endif // _WIN32 BC_SIG_ASSERT_LOCKED; h->rawMode = false; h->badTerm = bc_history_isBadTerm(); #ifdef _WIN32 h->orig_in = 0; h->orig_out = 0; in = GetStdHandle(STD_INPUT_HANDLE); out = GetStdHandle(STD_OUTPUT_HANDLE); if (!h->badTerm) { SetConsoleCP(CP_UTF8); SetConsoleOutputCP(CP_UTF8); if (!GetConsoleMode(in, &h->orig_in) || !GetConsoleMode(out, &h->orig_out)) { h->badTerm = true; return; } else { DWORD reqOut = ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN; DWORD reqIn = ENABLE_VIRTUAL_TERMINAL_INPUT; if (!SetConsoleMode(in, h->orig_in | reqIn) || !SetConsoleMode(out, h->orig_out | reqOut)) { h->badTerm = true; } } } #endif // _WIN32 bc_vec_init(&h->buf, sizeof(char), BC_DTOR_NONE); bc_vec_init(&h->history, sizeof(char*), BC_DTOR_HISTORY_STRING); bc_vec_init(&h->extras, sizeof(char), BC_DTOR_NONE); #ifndef _WIN32 FD_ZERO(&h->rdset); FD_SET(STDIN_FILENO, &h->rdset); h->ts.tv_sec = 0; h->ts.tv_nsec = 0; sigemptyset(&h->sigmask); sigaddset(&h->sigmask, SIGINT); #endif // _WIN32 } void bc_history_free(BcHistory *h) { BC_SIG_ASSERT_LOCKED; #ifndef _WIN32 bc_history_disableRaw(h); #else // _WIN32 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), h->orig_in); SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), h->orig_out); #endif // _WIN32 #ifndef NDEBUG bc_vec_free(&h->buf); bc_vec_free(&h->history); bc_vec_free(&h->extras); #endif // NDEBUG } #if BC_DEBUG_CODE /** * Prints scan codes. This special mode is used by bc history in order to print * scan codes on screen for debugging / development purposes. * @param h The history data. */ void bc_history_printKeyCodes(BcHistory *h) { char quit[4]; bc_vm_printf("Linenoise key codes debugging mode.\n" "Press keys to see scan codes. " "Type 'quit' at any time to exit.\n"); bc_history_enableRaw(h); memset(quit, ' ', 4); while(true) { char c; ssize_t nread; nread = bc_history_read(&c, 1); if (nread <= 0) continue; // Shift string to left. memmove(quit, quit + 1, sizeof(quit) - 1); // Insert current char on the right. quit[sizeof(quit) - 1] = c; if (!memcmp(quit, "quit", sizeof(quit))) break; bc_vm_printf("'%c' %lu (type quit to exit)\n", isprint(c) ? c : '?', (unsigned long) c); // Go left edge manually, we are in raw mode. bc_vm_putchar('\r', bc_flush_none); bc_file_flush(&vm.fout, bc_flush_none); } bc_history_disableRaw(h); } #endif // BC_DEBUG_CODE #endif // BC_ENABLE_HISTORY diff --git a/tests/script.sh b/tests/script.sh index 162437af8f22..5942e13159fe 100755 --- a/tests/script.sh +++ b/tests/script.sh @@ -1,185 +1,200 @@ #! /bin/sh # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2021 Gavin D. Howard and contributors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # set -e script="$0" testdir=$(dirname "${script}") . "$testdir/../scripts/functions.sh" outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} # Command-line processing. if [ "$#" -lt 2 ]; then printf 'usage: %s dir script [run_extra_tests] [run_stack_tests] [generate_tests] [time_tests] [exec args...]\n' "$script" exit 1 fi d="$1" shift f="$1" shift if [ "$#" -gt 0 ]; then run_extra_tests="$1" shift else run_extra_tests=1 fi if [ "$#" -gt 0 ]; then run_stack_tests="$1" shift else run_stack_tests=1 fi if [ "$#" -gt 0 ]; then generate="$1" shift else generate=1 fi if [ "$#" -gt 0 ]; then time_tests="$1" shift else time_tests=0 fi if [ "$#" -gt 0 ]; then exe="$1" shift else exe="$testdir/../bin/$d" fi # Set stuff for the correct calculator. if [ "$d" = "bc" ]; then if [ "$run_stack_tests" -ne 0 ]; then options="-lgq" else options="-lq" fi halt="halt" else options="-x" halt="q" fi scriptdir="$testdir/$d/scripts" name="${f%.*}" # We specifically want to skip this because it is handled specially. if [ "$f" = "timeconst.bc" ]; then exit 0 fi # Skip the tests that require extra math if we don't have it. if [ "$run_extra_tests" -eq 0 ]; then if [ "$f" = "rand.bc" ]; then printf 'Skipping %s script: %s\n' "$d" "$f" exit 0 fi fi # Skip the tests that require global stacks flag if we are not allowed to run # them. if [ "$run_stack_tests" -eq 0 ]; then if [ "$f" = "globals.bc" ] || [ "$f" = "references.bc" ] || [ "$f" = "rand.bc" ]; then printf 'Skipping %s script: %s\n' "$d" "$f" exit 0 fi fi out="$outputdir/${d}_outputs/${name}_script_results.txt" outdir=$(dirname "$out") # Make sure the directory exists. if [ ! -d "$outdir" ]; then mkdir -p "$outdir" fi # I use these, so unset them to make the tests work. unset BC_ENV_ARGS unset BC_LINE_LENGTH unset DC_ENV_ARGS unset DC_LINE_LENGTH s="$scriptdir/$f" orig="$testdir/$name.txt" results="$scriptdir/$name.txt" if [ -f "$orig" ]; then res="$orig" elif [ -f "$results" ]; then res="$results" elif [ "$generate" -eq 0 ]; then printf 'Skipping %s script %s\n' "$d" "$f" exit 0 else + + set +e + + # This is to check that the command exists. If not, we should not try to + # generate the test. Instead, we should just skip. + command -v "$d" + err="$?" + + set -e + + if [ "$err" -ne 0 ]; then + printf 'Could not find %s to generate results; skipping %s script %s\n' "$d" "$d" "$f" + exit 0 + fi + # This sed, and the script, are to remove an incompatibility with GNU bc, # where GNU bc is wrong. See the development manual # (manuals/development.md#script-tests) for more information. printf 'Generating %s results...' "$f" printf '%s\n' "$halt" | "$d" "$s" | sed -n -f "$testdir/script.sed" > "$results" printf 'done\n' res="$results" fi set +e printf 'Running %s script %s...' "$d" "$f" # Yes this is poor timing, but it works. if [ "$time_tests" -ne 0 ]; then printf '\n' printf '%s\n' "$halt" | /usr/bin/time -p "$exe" "$@" $options "$s" > "$out" err="$?" printf '\n' else printf '%s\n' "$halt" | "$exe" "$@" $options "$s" > "$out" err="$?" fi checktest "$d" "$err" "script $f" "$res" "$out" rm -f "$out" exec printf 'pass\n'