-
Notifications
You must be signed in to change notification settings - Fork 10
/
cxxforth.cpp
3331 lines (2586 loc) · 91.8 KB
/
cxxforth.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****
cxxforth: A Simple Forth Implementation in C++
==============================================
by Kristopher Johnson
<https://github.com/kristopherjohnson/cxxforth>
----
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
----
`cxxforth` is a simple implementation of [Forth][forth] in C++.
There are many examples of Forth implementations available on the Internet, but
most of them are written in assembly language or low-level C, with a focus in
maximizing efficiency and demonstrating traditional Forth implementation
techniques. This Forth is different: My goal is to use modern C++ to create a
Forth implementation that is easy to understand, easy to port, and easy to
extend. I'm not going to talk about register assignments or addressing modes
or opcodes or the trade-offs between indirect threaded code, direct threaded
code, subroutine threaded code, and token threaded code. I'm just going to
build a working Forth system in a couple thousand lines of C++ and Forth.
An inspiration for this implementation is Richard W.M. Jones's
[JONESFORTH][jonesforth]. JONESFORTH is a Forth implementation written as a
very readable tutorial, and I am adopting its style for our higher-level
implementation. This Forth kernel is written as a [C++ file](cxxforth.cpp)
with large comment blocks, and there is a utility, [cpp2md](cpp2md.fs),
that takes that C++ file and converts it to a [Markdown][markdown]-format
document [cxxforth.cpp.md](cxxforth.cpp.md) with nicely formatted commentary
sections between the C++ code blocks.
As in other Forth systems, the basic design of this Forth is to create a small
kernel in native code (C++, in this case), and then implement the rest of the
system with Forth code. The kernel has to provide the basic primitives needed
for memory access, arithmetic, logical operations, and operating system access.
With those primitives, we can then write Forth code to extend the system.
I am writing C++ conforming to the C++14 standard. If your C++ compiler does
not support C++14 yet, you may need to make some modifications to the code to
get it built.
The Forth words provided by cxxforth are based on those in the [ANS Forth draft
standard][dpans] and [Forth 2012 standard][forth2012]. I don't claim
conformance to any standard, but you can use these standards as a crude form of
documentation for the Forth words that are implemented here. cxxforth
implements many of the words from the standards' core word sets, and a
smattering of words from other standard word sets.
In addition to words from the standards, cxxforth provides a few non-standard
words. Each of these is marked with "Not a standard word" in accompanying
comments.
While this Forth can be seen as a toy implementation, I do want it to be usable
for real-world applications. Forth was originally designed to be something
simple you could build yourself and extend and customize as needed to solve
your problem. I hope people can use cxxforth like that.
It is assumed that the reader has some familiarity with C++ and Forth. You may
want to first read the JONESFORTH source or the source of some other Forth
implementation to get the basic gist of how Forth is usually implemented.
[forth]: https://en.wikipedia.org/wiki/Forth_(programming_language) "Forth (programming language)"
[jonesforth]: http://git.annexia.org/?p=jonesforth.git;a=blob;f=jonesforth.S;h=45e6e854a5d2a4c3f26af264dfce56379d401425;hb=HEAD
[markdown]: https://daringfireball.net/projects/markdown/ "Markdown"
[dpans]: http://forth.sourceforge.net/std/dpans/dpansf.htm "Alphabetic list of words"
[forth2012]: http://forth-standard.org/standard/alpha "Forth 2012"
----
Building cxxforth
-----------------
Building the `cxxforth` executable and other targets is easiest if you are on a
UNIX-ish system that has `make`, `cmake`, and Clang or GCC. If you have those
components, you can probably build `cxxforth` by just entering these commands:
cd wherever_your_files_are/cxxforth
make
If successful, the `cxxforth` executable will be built in the
`wherever_your_files_are/cxxforth/build/` subdirectory.
If you don't have one of those components, or if 'make' doesn't work, then it's
not too hard to build it manually. You will need to create a file called
`cxxforthconfig.h`, which can be empty, then you need to invoke your C++
compiler on the `cxxforth.cpp` source file, enabling whatever options might be
needed for C++14 compatibility and to link with the necessary C++ and system
libraries. For example, on a Linux system with gcc, you should be able to
build it by entering these commands:
cd wherever_your_files_are/cxxforth
touch cxxforthconfig.h
g++ -std=c++14 -o cxxforth cxxforth.cpp
----
Running cxxforth
----------------
Once the `cxxforth` executable is built, you can run it like any other command-line utility.
If you run it without any additional arguments, it will display a welcome
message and then allow you to enter Forth commands. Enter "bye" to exit.
If there are any additional arguments, cxxforth will load and interpret those
files. For example, the `cxxforth/tests` directory contains a file `hello.fs`
that defines a word `hello`. So, if you are in the `cxxforth` directory and
you enter this:
build/cxxforth tests/hello.fs
Then cxxforth will load that file, and you can enter `hello` to execute the
word that was loaded from `hello.fs`.
----
The Code
--------
I start by including headers from the C++ Standard Library. I also include
`cxxforth.h`, which declares exported functions and includes the
`cxxforthconfig.h` file produced by the CMake build.
A macro `CXXFORTH_DISABLE_FILE_ACCESS` can be defined to prevent cxxforth from
defining words for opening, reading, and writing files. You may want to do
this on a platform that does not support file access, or if you don't need
those words and want a smaller executable.
****/
#include "cxxforth.h"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <list>
#include <stdexcept>
#include <string>
#include <thread>
#ifndef CXXFORTH_DISABLE_FILE_ACCESS
#include <cstdio>
#include <fstream>
#endif
using std::cerr;
using std::cout;
using std::endl;
using std::exception;
using std::isspace;
using std::ptrdiff_t;
using std::runtime_error;
using std::size_t;
using std::string;
/****
GNU Readline Support
--------------------
cxxforth can use the [GNU Readline][readline] library for user input if it is
available.
The CMake build will automatically detect whether the library is available, and
if so define `CXXFORTH_USE_READLINE`.
However, even if the GNU Readline library is available, you may not want to
link your executable with it due to its GPL licensing terms. You can pass
`-DCXXFORTH_DISABLE_READLINE=ON` to `cmake` to prevent it from searching for
the library.
[readline]: https://cnswww.cns.cwru.edu/php/chet/readline/rltop.html
****/
#ifdef CXXFORTH_USE_READLINE
#include "readline/readline.h"
#include "readline/history.h"
#endif
/****
Configuration Constants
-----------------------
I have a few macros to define the size of the Forth data space, the maximum
numbers of cells on the data and return stacks, and the maximum number of word
definitions in the dictionary.
These macros are usually defined in the `cxxforthconfig.h` header that is
generated by CMake and included by `cxxforth.h`, but I provide default values
in case they have not been defined.
****/
#ifndef CXXFORTH_VERSION
#define CXXFORTH_VERSION "1.4.1"
#endif
#ifndef CXXFORTH_DATASPACE_SIZE
#define CXXFORTH_DATASPACE_SIZE (16 * 1024 * sizeof(Cell))
#endif
#ifndef CXXFORTH_DSTACK_COUNT
#define CXXFORTH_DSTACK_COUNT (256)
#endif
#ifndef CXXFORTH_RSTACK_COUNT
#define CXXFORTH_RSTACK_COUNT (256)
#endif
/****
----
Data Types
----------
Next I define some types.
A `Cell` is the basic Forth type. I define the `Cell` type using the C++
`uintptr_t` type to ensure it is large enough to hold an address. This
generally means that it will be a 32-bit value on 32-bit platforms and a 64-bit
value on 64-bit platforms. (If you want to build a 32-bit Forth on a 64-bit
platform with clang or gcc, you can pass the `-m32` flag to the compiler and
linker.)
I won't be providing any of the double-cell operations that traditional Forths
provide. Double-cell operations were important in the days of 8-bit and 16-bit
Forths, but with cells of 32 bits or more, many applications have no need for
them.
I'm also not dealing with floating-point values. Floating-point support would
be useful, but I'm trying to keep this simple.
Forth doesn't require type declarations; a cell can be used as an address, an
unsigned integer, a signed integer, or a variety of other uses. However, in
C++ we will have to be explicit about types to perform the operations we want
to perform. So I define a few additional types to represent the ways that a
`Cell` can be used, and a few macros to cast between types without littering
the code with a lot of `reinterpret_cast<...>(...)` expressions.
****/
namespace {
using Cell = uintptr_t; // unsigned value
using SCell = intptr_t; // signed value
using Char = unsigned char;
using SChar = signed char;
using CAddr = Char*; // Any address
using AAddr = Cell*; // Cell-aligned address
#define CELL(x) reinterpret_cast<Cell>(x)
#define CADDR(x) reinterpret_cast<Char*>(x)
#define AADDR(x) reinterpret_cast<AAddr>(x)
#define CHARPTR(x) reinterpret_cast<char*>(x)
#define SIZE_T(x) static_cast<size_t>(x)
constexpr auto CellSize = sizeof(Cell);
/****
Boolean Constants
-----------------
Here I define constants for Forth _true_ and _false_ Boolean flag values.
Note that the Forth convention is that a true flag is a cell with all bits set,
unlike the C++ convention of using 1 or any other non-zero value to mean true,
so we need to be sure to use these constants for all Forth words that return a
Boolean flag.
****/
constexpr Cell False = 0;
constexpr Cell True = ~False;
/****
----
The Definition Struct
---------------------
My first big departure from traditional Forth implementations is how I will
store the word definitions for the Forth dictionary. Traditional Forths
intersperse the word names in the shared data space along with code and data,
using a linked list to navigate through them. I am going to use a `std::list`
of `Definition` structs, outside of the data space.
Use of `std::list` has these benefits:
- The `Definition` structures won't use data space. The C++ library will take care of allocating heap space as needed.
- The `Definition` structures won't move around in memory after being added to the list. (In contrast, use of `std::vector` or other C++ collections might move elements as they are modified.)
One of the members of `Definition` is a C++ `std::string` to hold the name. I
won't need to worry about managing the memory for that variable-length field.
The `name` field will be empty for a `:NONAME` definition.
A `Definition` also has a `code` field that points to the native code
associated with the word, a `does` field pointing to associated Forth
instructions, a `parameter` field that points to associated data-space
elements, and some bit flags to keep track of whether the word is `IMMEDIATE`
and/or `HIDDEN`. We will explore the use of these fields later when I talk
about the inner and outer interpreters.
`Definition` has a static field `executingWord` that contains the address
of the `Definition` that was most recently executed. This can be used by
`Code` functions to refer to their definitions.
Finally, `Definition` has a few member functions for executing the code and for
accessing the _hidden_ and _immediate_ flags.
****/
using Code = void(*)();
struct Definition {
Code code = nullptr;
AAddr does = nullptr;
AAddr parameter = nullptr;
Cell flags = 0;
string name;
static constexpr Cell FlagHidden = (1 << 1);
static constexpr Cell FlagImmediate = (1 << 2);
static const Definition* executingWord;
void execute() const {
auto saved = executingWord;
executingWord = this;
code();
executingWord = saved;
}
bool isHidden() const { return (flags & FlagHidden) != 0; }
void toggleHidden() { flags ^= FlagHidden; }
bool isImmediate() const { return (flags & FlagImmediate) != 0; }
void toggleImmediate() { flags ^= FlagImmediate; }
bool isFindable() const { return !name.empty() && !isHidden(); }
};
/****
I will use a pointer to a `Definition` as the Forth _execution token_ (XT).
****/
using Xt = Definition*;
#define XT(x) reinterpret_cast<Xt>(x)
/****
----
Global Variables
----------------
With the types defined, next I define global variables, starting with the Forth
data space and the data and return stacks.
For each of these arrays, there are constants that point to the end of the
array, so I can easily test whether I need to report an overflow.
****/
Char dataSpace[CXXFORTH_DATASPACE_SIZE];
Cell dStack[CXXFORTH_DSTACK_COUNT];
Cell rStack[CXXFORTH_RSTACK_COUNT];
constexpr CAddr dataSpaceLimit = &dataSpace[CXXFORTH_DATASPACE_SIZE];
constexpr AAddr dStackLimit = &dStack[CXXFORTH_DSTACK_COUNT];
constexpr AAddr rStackLimit = &rStack[CXXFORTH_RSTACK_COUNT];
/****
The Forth dictionary is a list of `Definition`s. The most recent definition is
at the back of the list.
****/
std::list<Definition> definitions;
/****
For each of the global arrays, I need a pointer to the current location.
For the data space, I have the `dataPointer`, which corresponds to Forth's
`HERE`.
For each of the stacks, I need a pointer to the element at the top of the
stack. The stacks grow upward. When a stack is empty, the associated pointer
points to an address below the actual bottom of the array, so I will need to
avoid dereferencing these pointers under those circumstances.
****/
CAddr dataPointer = nullptr;
AAddr dTop = nullptr;
AAddr rTop = nullptr;
/****
The inner-definition interpreter needs a pointer to the next instruction to be
executed. This will be explained below in the **Inner Interpreter** section.
****/
Xt* nextInstruction = nullptr;
/****
I have to define the static `executingWord` member declared in `Definition`.
****/
const Definition* Definition::executingWord = nullptr;
/****
There are a few special words whose XTs I will use frequently when compiling
or executing. Rather than looking them up in the dictionary as needed, I'll
cache their values during initialization.
****/
Xt doLiteralXt = nullptr;
Xt setDoesXt = nullptr;
Xt exitXt = nullptr;
Xt endOfDefinitionXt = nullptr;
/****
I need a flag to track whether we are in interpreting or compiling state.
This corresponds to Forth's `STATE` variable.
****/
Cell isCompiling = False;
/****
I provide a variable that controls the numeric base used for conversion
between numbers and text. This corresponds to the Forth `BASE` variable.
Whenever using C++ stream output operators, I will need to ensure the stream's
numeric output base matches `numericBase`. To make this easy, I'll define a
macro `SETBASE()` that calls the `std::setbase` I/O manipulator and use it
whenever writing numeric data using the stream operators.
****/
Cell numericBase = 10;
#define SETBASE() std::setbase(static_cast<int>(numericBase))
/****
The input buffer is a `std::string`. This makes it easy to use the C++ I/O
facilities, and frees me from the need to allocate a statically sized buffer
that could overflow. I also have a current offset into this buffer,
corresponding to the Forth `>IN` variable.
****/
string sourceBuffer;
Cell sourceOffset = 0;
/****
I need a buffer to store the result of the Forth `WORD` word. As with the
input buffer, I use a `string` so I don't need to worry about memory
management.
Note that while this is a `std:string`, its format is not that of a typical C++
string. The buffer returned by `WORD` has the word length as its first
character. That is, it is a Forth _counted string_.
****/
string wordBuffer;
/****
I need a buffer to store the result of the Forth `PARSE` word. Unlike `WORD`,
this is a "normal" string and I won't need to store the count at the beginning
of this buffer.
****/
string parseBuffer;
/****
I store the `argc` and `argv` values passed to `main()` so I can make them
available for use by the Forth program by our non-standard `#ARGS` and `ARG`
Forth words, defined later.
****/
size_t commandLineArgCount = 0;
const char** commandLineArgVector = nullptr;
/****
I need a variable to store the result of the last call to `SYSTEM`, which
the user can retrieve by using `$?`.
****/
int systemResult = 0;
/****
----
Stack Primitives
----------------
I will be doing a lot of pushing and popping values to and from our data and
return stacks, so in lieu of sprinkling pointer arithmetic throughout our code,
I'll define a few simple functions to handle those operations. I expect the
compiler to expand calls to these functions inline, so this isn't inefficient.
Above I defined the global variables `dTop` and `rTop` to point to the top of
the data stack and return stack. I will use the expressions `*dTop` and
`*rTop` when accessing the top-of-stack values. I will also use expressions
like `*(dTop - 1)` and `*(dTop - 2)` to reference the items beneath the top of
stack.
When I need to both read and remove a top-of-stack value, my convention will
be to put both operations on the same line, like this:
Cell x = *dTop; pop();
A more idiomatic C++ way to write this might be `Cell x = *(dTop--);`, but I
think that's less clear.
****/
// Make the data stack empty.
void resetDStack() {
dTop = dStack - 1;
}
// Make the return stack empty.
void resetRStack() {
rTop = rStack - 1;
}
// Return the depth of the data stack.
ptrdiff_t dStackDepth() {
return dTop - dStack + 1;
}
// Return the depth of the return stack.
ptrdiff_t rStackDepth() {
return rTop - rStack + 1;
}
// Push cell onto data stack.
void push(Cell x) {
*(++dTop) = x;
}
// Pop cell from data stack.
void pop() {
--dTop;
}
// Push cell onto return stack.
void rpush(Cell x) {
*(++rTop) = x;
}
// Pop cell from return stack.
void rpop() {
--rTop;
}
/****
----
Exceptions
----------
Forth provides the `ABORT` and `ABORT"` words, which interrupt execution and
return control to the main `QUIT` loop. I will implement this functionality
using a C++ exception to return control to the top-level interpreter.
The C++ functions `abort()` and `abortMessage()` defined here are the first
primitive functions that will be exposed as Forth words. For each such word, I
will spell out the Forth name of the primitive in all-caps, and provide a Forth
comment showing the stack effects. For words described in the standards, I
will generally not provide any more information, but for words that are not
standard words, I'll provide a brief description.
****/
class AbortException: public runtime_error {
public:
explicit AbortException(const string& msg): runtime_error(msg) {}
explicit AbortException(const char* msg): runtime_error(msg) {}
explicit AbortException(const char* caddr, size_t count)
: runtime_error(string(caddr, count)) {}
};
// ABORT ( i*x -- ) ( R: j*x -- )
void abort() {
throw AbortException("");
}
// ABORT-MESSAGE ( i*x c-addr u -- ) ( R: j*x -- )
//
// Not a standard word.
//
// Same semantics as the standard ABORT", but takes a string address and length
// instead of parsing the message string.
void abortMessage() {
auto count = SIZE_T(*dTop); pop();
auto caddr = CHARPTR(*dTop); pop();
throw AbortException(caddr, count);
}
/****
----
Runtime Safety Checks
---------------------
Old-school Forths are implemented by super-programmers who never make coding
mistakes and so don't want the overhead of bounds-checking or other nanny
hand-holding. However, I'm just a dumb C++ programmer, and I'd like some help
to catch mistakes.
To that end, I have a set of macros and functions that verify that I have the
expected number of arguments available on the stacks, that I'm not going to run
off the end of an array, that I'm not going to try to divide by zero, and so
on.
You can define the macro `CXXFORTH_SKIP_RUNTIME_CHECKS` to generate an
executable that doesn't include these checks, so when you have a fully debugged
Forth application you can run it on that optimized executable for improved
performance.
When the `CXXFORTH_SKIP_RUNTIME_CHECKS` macro is not defined, these macros will
check conditions and throw an `AbortException` if the assertions fail. I won't
go into the details of these macros here. Later we will see them used in the
definitions of our primitive Forth words.
****/
#ifdef CXXFORTH_SKIP_RUNTIME_CHECKS
#define RUNTIME_NO_OP() do { } while (0)
#define RUNTIME_ERROR(msg) RUNTIME_NO_OP()
#define RUNTIME_ERROR_IF(cond, msg) RUNTIME_NO_OP()
#define REQUIRE_DSTACK_DEPTH(n, name) RUNTIME_NO_OP()
#define REQUIRE_DSTACK_AVAILABLE(n, name) RUNTIME_NO_OP()
#define REQUIRE_RSTACK_DEPTH(n, name) RUNTIME_NO_OP()
#define REQUIRE_RSTACK_AVAILABLE(n, name) RUNTIME_NO_OP()
#define REQUIRE_ALIGNED(addr, name) RUNTIME_NO_OP()
#define REQUIRE_VALID_HERE(name) RUNTIME_NO_OP()
#define REQUIRE_DATASPACE_AVAILABLE(n, name) RUNTIME_NO_OP()
#else
#define RUNTIME_ERROR(msg) do { throw AbortException(msg); } while (0)
#define RUNTIME_ERROR_IF(cond, msg) do { if (cond) RUNTIME_ERROR(msg); } while (0)
#define REQUIRE_DSTACK_DEPTH(n, name) requireDStackDepth(n, name)
#define REQUIRE_DSTACK_AVAILABLE(n, name) requireDStackAvailable(n, name)
#define REQUIRE_RSTACK_DEPTH(n, name) requireRStackDepth(n, name)
#define REQUIRE_RSTACK_AVAILABLE(n, name) requireRStackAvailable(n, name)
#define REQUIRE_ALIGNED(addr, name) checkAligned(addr, name)
#define REQUIRE_VALID_HERE(name) checkValidHere(name)
#define REQUIRE_DATASPACE_AVAILABLE(n, name) requireDataSpaceAvailable(n, name)
template<typename T>
void checkAligned(T addr, const char* name) {
RUNTIME_ERROR_IF((CELL(addr) % CellSize) != 0,
string(name) + ": unaligned address");
}
void requireDStackDepth(size_t n, const char* name) {
RUNTIME_ERROR_IF(dStackDepth() < static_cast<ptrdiff_t>(n),
string(name) + ": stack underflow");
}
void requireDStackAvailable(size_t n, const char* name) {
RUNTIME_ERROR_IF((dTop + n) >= dStackLimit,
string(name) + ": stack overflow");
}
void requireRStackDepth(size_t n, const char* name) {
RUNTIME_ERROR_IF(rStackDepth() < ptrdiff_t(n),
string(name) + ": return stack underflow");
}
void requireRStackAvailable(size_t n, const char* name) {
RUNTIME_ERROR_IF((rTop + n) >= rStackLimit,
string(name) + ": return stack overflow");
}
void checkValidHere(const char* name) {
RUNTIME_ERROR_IF(dataPointer < dataSpace || dataSpaceLimit <= dataPointer,
string(name) + ": HERE outside data space");
}
void requireDataSpaceAvailable(size_t n, const char* name) {
RUNTIME_ERROR_IF((dataPointer + n) >= dataSpaceLimit,
string(name) + ": data space overflow");
}
#endif // CXXFORTH_SKIP_RUNTIME_CHECKS
/****
----
Forth Primitives
----------------
Now I will start defining the primitive operations that are exposed as Forth
words. You can think of these as the opcodes of a virtual Forth processor.
Once I have the primitive operations defined, I can then write definitions in
Forth that use these primitives to build more-complex words.
Each of these primitives is a function that takes no arguments and returns no
result, other than its effects on the Forth data stack, return stack, and data
space. Such a function can be assigned to the `code` field of a `Definition`.
When changing the stack, the primitives don't change the stack depth any more
than necessary. For example, `PICK` just replaces the top-of-stack value with
a different value, and `ROLL` uses `std::memmove()` to rearrange elements
rather than individually popping and pushng them.
You can peek ahead to the `definePrimitives()` function to see how these
primitives are added to the Forth dictionary.
Forth Stack Operations
----------------------
Let's start with some basic Forth stack manipulation words. These differ from
the push/pop/rpush/rpop/etc. primitives above in that they are intended to be
called from Forth code rather than from the C++ kernel code. So I include
runtime checks and use the stacks rather than passing arguments or returning
values via C++ call/return mechanisms.
Note that for C++ functions that implement primitive Forth words, I will
include the Forth names and stack effects in comments. You can look up the
Forth names in the standards to learn what these words are supposed to do.
****/
// DEPTH ( -- +n )
void depth() {
REQUIRE_DSTACK_AVAILABLE(1, "DEPTH");
push(static_cast<Cell>(dStackDepth()));
}
// DROP ( x -- )
void drop() {
REQUIRE_DSTACK_DEPTH(1, "DROP");
pop();
}
// DUP ( x -- x x )
void dup() {
REQUIRE_DSTACK_DEPTH(1, "DUP");
REQUIRE_DSTACK_AVAILABLE(1, "DUP");
push(*dTop);
}
// SWAP ( x0 x1 -- x1 x0 )
void swap() {
REQUIRE_DSTACK_DEPTH(2, "SWAP");
std::swap(*dTop, *(dTop - 1));
}
// PICK ( xu ... x1 x0 u -- xu ... x1 x0 xu )
void pick() {
REQUIRE_DSTACK_DEPTH(1, "PICK");
auto index = *dTop;
REQUIRE_DSTACK_DEPTH(index + 2, "PICK");
*dTop = *(dTop - index - 1);
}
// ROLL ( xu xu-1 ... x0 u -- xu-1 ... x0 xu )
void roll() {
REQUIRE_DSTACK_DEPTH(1, "ROLL");
auto n = *dTop; pop();
if (n > 0) {
REQUIRE_DSTACK_DEPTH(n + 1, "ROLL");
auto x = *(dTop - n);
std::memmove(dTop - n, dTop - n + 1, n * sizeof(Cell));
*dTop = x;
}
}
// >R ( x -- ) ( R: -- x )
void toR() {
REQUIRE_DSTACK_DEPTH(1, ">R");
REQUIRE_RSTACK_AVAILABLE(1, ">R");
rpush(*dTop); pop();
}
// R> ( -- x ) ( R: x -- )
void rFrom() {
REQUIRE_RSTACK_DEPTH(1, "R>");
REQUIRE_DSTACK_AVAILABLE(1, "R>");
push(*rTop); rpop();
}
// R@ ( -- x ) ( R: x -- x )
void rFetch() {
REQUIRE_RSTACK_DEPTH(1, "R@");
REQUIRE_DSTACK_AVAILABLE(1, "R@");
push(*rTop);
}
// EXIT ( -- ) ( R: nest-sys -- )
void exit() {
REQUIRE_RSTACK_DEPTH(1, "EXIT");
nextInstruction = reinterpret_cast<Xt*>(*rTop); rpop();
}
/****
Another important set of Forth primitives are those for reading and writing
values in data space.
****/
// ! ( x a-addr -- )
void store() {
REQUIRE_DSTACK_DEPTH(2, "!");
auto aaddr = AADDR(*dTop); pop();
REQUIRE_ALIGNED(aaddr, "!");
auto x = *dTop; pop();
*aaddr = x;
}
// @ ( a-addr -- x )
void fetch() {
REQUIRE_DSTACK_DEPTH(1, "@");
auto aaddr = AADDR(*dTop);
REQUIRE_ALIGNED(aaddr, "@");
*dTop = *aaddr;
}
// c! ( char c-addr -- )
void cstore() {
REQUIRE_DSTACK_DEPTH(2, "C!");
auto caddr = CADDR(*dTop); pop();
auto x = static_cast<Char>(*dTop); pop();
*caddr = x;
}
// c@ ( c-addr -- char )
void cfetch() {
REQUIRE_DSTACK_DEPTH(1, "C@");
auto caddr = CADDR(*dTop);
*dTop = static_cast<Cell>(*caddr);
}
// COUNT ( c-addr1 -- c-addr2 u )
void count() {
REQUIRE_DSTACK_DEPTH(1, "COUNT");
REQUIRE_DSTACK_AVAILABLE(1, "COUNT");
auto caddr = CADDR(*dTop);
auto count = static_cast<Cell>(*caddr);
*dTop = CELL(caddr + 1);
push(count);
}
/****
Next, I'll define some primitives for accessing and manipulating the data-space
pointer, `HERE`.
****/
template<typename T>
AAddr alignAddress(T addr) {
auto offset = CELL(addr) % CellSize;
return (offset == 0) ? AADDR(addr) : AADDR(CADDR(addr) + (CellSize - offset));
}
void alignDataPointer() {
dataPointer = CADDR(alignAddress(dataPointer));
}
// ALIGN ( -- )
void align() {
alignDataPointer();
REQUIRE_VALID_HERE("ALIGN");
}
// ALIGNED ( addr -- a-addr )
void aligned() {
REQUIRE_DSTACK_DEPTH(1, "ALIGNED");
*dTop = CELL(alignAddress(*dTop));
}
// HERE ( -- addr )
void here() {
REQUIRE_DSTACK_AVAILABLE(1, "HERE");
push(CELL(dataPointer));
}
// ALLOT ( n -- )
void allot() {
REQUIRE_DSTACK_DEPTH(1, "ALLOT");
REQUIRE_VALID_HERE("ALLOT");
REQUIRE_DATASPACE_AVAILABLE(CellSize, "ALLOT");
dataPointer += *dTop; pop();
}
// CELLS ( n1 -- n2 )
void cells() {
REQUIRE_DSTACK_DEPTH(1, "CELLS");
*dTop *= CellSize;
}
// Store a cell to data space.
void data(Cell x) {
REQUIRE_VALID_HERE(",");
REQUIRE_DATASPACE_AVAILABLE(CellSize, ",");
REQUIRE_ALIGNED(dataPointer, ",");
*(AADDR(dataPointer)) = x;
dataPointer += CellSize;
}
// UNUSED ( -- u )
void unused() {
REQUIRE_DSTACK_AVAILABLE(1, "UNUSED");
push(static_cast<Cell>(dataSpaceLimit - dataPointer));
}
/****
I could implement memory-block words like `CMOVE`, `CMOVE>`, `FILL`, and
`COMPARE` in Forth, but speed is often important for these, so I will make them
native primitives.
****/
// CMOVE ( c-addr1 c-addr2 u -- )
void cMove() {
REQUIRE_DSTACK_DEPTH(3, "CMOVE");
auto length = SIZE_T(*dTop); pop();
auto dest = CHARPTR(*dTop); pop();
auto src = CHARPTR(*dTop); pop();
std::memcpy(dest, src, length);
}