frustration.rs 88.6 KB
Newer Older
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
//@ Project URL: https://gitlab.cs.washington.edu/fidelp/frustration
//@
//@ Frustration - Escaping a Turing Tar Pit with Forth
//@
//@ # What is this file?
//@
//@ This is a tutorial that will show you how to bootstrap an interactive
//@ programming environment from a small amount of code.
//@
//@ First we will design a virtual computer.
//@
//@ Then we will design software to run on that computer, to enable REPL-style
//@ interactive programming.
//@
//@ A REPL is a
//@ "[Read, Evaluate, Print loop](https://en.wikipedia.org/wiki/Repl)".
//@ A REPL lets you type code at
//@ the keyboard and immediately get a result back.  You can also define
//@ functions, including functions that change how the environment works in
//@ fundamental ways.
//@
//@ # What is Forth?
//@
//@ Forth is the programming language we will use with our computer.
//@
//@ Forth was invented by Chuck Moore in the 1960s as a tool for quickly
//@ coming to grips with new computer systems.
//@
//@ > "Let us imagine a situation in which you have access to
//@ > your computer. I mean sole user sitting at the board with
//@ > all the lights, for some hours at a time. This is
//@ > admittedly an atypical situation, but one that can
//@ > always be arranged if you are competent, press hard, and
//@ > will work odd hours. Can you and the computer write a
//@ > program? Can you write a program that didn't descend from
//@ > a pre-existing program? You can learn a bit and have a
//@ > lot of fun trying."
//@ > 
//@ > -- Chuck Moore,
//@ > ["Programming a Problem-Oriented Language"](https://colorforth.github.io/POL.htm),
//@ > 1970
//@
//@ As you will see, it does not take much work to get Forth running on a
//@ new machine, including a machine with a completely unfamiliar instruction
//@ set.
//@
//@ But before we can do any of that we will need a machine.  Let's make one.
//@
//@ # Table of Contents
//@ - Part 1 - The Computer
//@   - 1.0 - Designing the CPU
//@     - Defining a stack
//@     - Designing a stack CPU
//@   - 1.1 - The instruction set
//@     - Memory access
//@     - Designing the instruction set
//@       - The CALL instruction
//@       - Data processing instructions
//@       - The LITERAL instruction
//@     - Making the CPU run
//@       - Return-stack instructions
//@       - Memory instructions
//@       - Stack shuffling instructions
//@       - Conditional skip instruction
//@       - Arithmetic and logic
//@       - Input/output
//@ - Part 2 - The Program
//@     - Designing the Forth dictionary
//@     - Tools for building the Forth dictionary
//@     - Building the Forth dictionary
//@       - Subroutine threading
//@       - key
//@       - emit
//@       - subtraction
//@       - 0= (compare-to-zero)
//@       - = (equals)
//@   - 2.1 - The lexer
//@     - Skipping whitespace
//@     - Reading characters into a buffer
//@       - over
//@       - 2dup
//@       - The input buffer
//@       - min
//@       - c@ and c! (byte-by-byte memory access)
//@       - Filling the input buffer
//@       - word
//@   - 2.2 - Dictionary lookup
//@       - latest
//@       - find
//@       - ' (quote)
//@   - 2.3 - The outer interpreter
//@       - here
//@       - Achieving interactivity
//@       - immediate
//@       - [ and ]
//@       - smudge and unsmudge
//@       - , (comma)
//@       - number
//@       - literal
//@   - 2.4 - Defining subroutines
//@     - create
//@     - : (define word)
//@     - ; (end of definition)
//@   - Miscellanea
//@ - Part 3 - Using the interactive programming environment
//@
//@ # Part 1 - The Computer
//@
//@ ## 1.0 - Designing the CPU
//@
//@ This computer will have a 16-bit CPU.  It will be able to access
//@ 2^16 (65536) memory locations, numbered 0 to 65535.
//@ Each of these locations, 0 to 65535, is called a "memory address".
psf's avatar
psf committed
114

psf's avatar
psf committed
115
116
const ADDRESS_SPACE: usize = 65536;

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
//@ The job of a CPU is to load numbers from memory, do math or logic on them,
//@ then write the resulting number back into memory.
//@
//@ The CPU needs a temporary place to hold numbers while it is working with
//@ them.
//@
//@ In most CPUs, this place is called a "register".  Registers work like
//@ variables in a programming language but there are only a few of them
//@ (most CPUs have between 1 and 32).
//@
//@ - On 64-bit ARM the registers are named  r0, r1, ..., r15.
//@ - On 64-bit Intel they are instead named rax, rbx, ....
//@
//@ Just in case those names ring any bells.
//@
//@ Having immediate access to dozens of registers is quite handy, but it means
//@ many choices are available to the programmer, or more likely, to the
//@ compiler.  And making good choices is Hard.  A lot of work goes into
//@ deciding what variable to store in what register
//@ ("[register allocation](https://en.wikipedia.org/wiki/Register_allocation)")
//@ and when to dump register contents back into memory ("spilling").
//@
//@ Our CPU avoids these problems by not having registers; instead we store
//@ numbers in a stack.
//@
//@ - Putting a number onto the top of the stack is called "push".
//@ - Taking the most recent number off the top of the stack is called "pop".
//@
//@ The CPU can only access the value that was most recently pushed onto the
//@ stack.  This may seem like a big limitation right now but you will see ways
//@ of dealing with it.
//@
//@ The choice to use a stack instead of registers makes our CPU a
//@ "[stack machine](https://en.wikipedia.org/wiki/Stack_machine)"
//@ as opposed to a "register machine".
//@
//@ ### Defining a stack
//@
//@ This stack is fixed-size and can hold N values.
psf's avatar
psf committed
156

psf's avatar
psf committed
157
#[derive(Debug)]
psf's avatar
psf committed
158
159
struct Stack<const N: usize> {
    mem: [u16; N],
psf's avatar
psf committed
160
    tos: usize  /* top-of-stack */
psf's avatar
psf committed
161
162
}

163
164
165
166
167
168
169
170
171
172
//@ First we'll need a function to add a number to the stack.
//@
//@ When a fixed-size stack fills up, there is a failure case
//@ (stack overflow) that must be handled somehow.
//@
//@ This particular stack is a circular stack, meaning that if
//@ it ever fills up, it will discard the oldest entry instead of
//@ signaling an error.  The lack of error handling makes the CPU
//@ simpler.

psf's avatar
psf committed
173
174
175
176
177
impl<const N: usize> Stack<N> {
    fn push(&mut self, val: u16) {
        self.tos = (self.tos.wrapping_add(1)) & (N - 1);
        self.mem[self.tos] = val;
    }
psf's avatar
psf committed
178

179
180
181
//@ We'll also need a function to remove & return the most recently pushed
//@ number.

psf's avatar
psf committed
182
183
184
    fn pop(&mut self) -> u16 {
        let val = self.mem[self.tos];
        self.mem[self.tos] = 0;
185

186
187
188
//@ You don't have to set the value back to zero.  I am only doing
//@ this because it makes makes the stack look nicer when dumped
//@ out with print!().
189

psf's avatar
psf committed
190
191
192
        self.tos = (self.tos.wrapping_sub(1)) & (N - 1);
        return val;
    }
psf's avatar
psf committed
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
//@ Finally, here is a function that creates a new stack.
//@ Because these are circular stacks it doesn't matter where top-of-stack
//@ (tos) starts off pointing.  I arbitrarily set it to the highest index so
//@ the first value pushed will wind up at index 0, again because this
//@ makes the stack look nicer when printed out.

    fn new() -> Stack<N> {
        return Stack {tos: N-1, mem: [0; N]};
    }
}
//@ ### Designing a stack CPU
//@
//@ Now that we have a stack let's use one in our CPU!  Or two?
//@
//@ Why two stacks?
//@
//@ The first stack is called the "data stack" and is used instead of
//@ registers, as already described.
//@
//@ The second stack will be called the "return stack".  This one holds
//@ subroutine return addresses.  Don't worry if you don't know what that
//@ means; we'll get to it later when we talk about the instruction set.
//@
//@ In addition to stacks we are going to give the CPU a couple more things:
//@
//@ 1. An "instruction pointer", which holds the memory address of the next
//@    instruction that the CPU will execute.
//@
//@ 2. To make life simpler we put main memory straight on "the CPU" even
//@    though in a real computer, RAM would be off-chip and accessed through a
//@    data bus.
//@
//@ In our memory, each of the 65536 possible memory addresses will store one
//@ 8-bit byte (u8 data type in Rust).  This makes it a 65536 byte (64 KB)
//@ memory.  We could have chosen to make each memory address store 16-bits
//@ instead.  That would make this a "word-addressed memory".  Instead we are
//@ going with the
//@ "[byte-addressed memory](https://en.wikipedia.org/wiki/Byte_addressing)"
//@ that is more conventional in today's
//@ computers.  This choice is arbitrary.
//@
//@ Let's add those things to the CPU.
psf's avatar
psf committed
236

psf's avatar
psf committed
237
238
struct Core {
    ram: [u8; ADDRESS_SPACE],
psf's avatar
psf committed
239
240
241
    ip: u16,  /* instruction pointer */
    dstack: Stack<16>, /* data stack */
    rstack: Stack<32>  /* return stack */
psf's avatar
psf committed
242
243
}

244
//@ Finally, let's write a function that creates and returns a CPU for us to use.
245

246
use std::convert::TryInto;
psf's avatar
psf committed
247

psf's avatar
psf committed
248
impl Core {
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
    fn new() -> Core {
        return Core {
            ram: [0; ADDRESS_SPACE],
            ip: 0,
            dstack: Stack::new(),
            rstack: Stack::new()}
    }

//@ ## 1.1 - The instruction set
//@
//@ Now we have a CPU sitting there but it does nothing.
//@
//@ A working CPU would execute a list of instructions.  An instruction is
//@ a number that is a command for the CPU.  For example:
//@
//@ - 65522 might mean "add the top two values on the data stack".
//@ - 65524 might mean "invert the bits of the top value on the data stack".
//@
//@ The map of instruction-to-behavior comes from the CPU's
//@ "instruction set" i.e. the set of all possible instructions and their
//@ behaviors.
//@
//@ Normally you program a CPU by putting instructions into memory and then
//@ telling the CPU the memory address where it can find the first instruction.
//@
//@ The CPU will:
//@
//@ 1. Fetch the instruction (load it from memory)
//@ 2. Decode the instruction (look it up in the instruction set)
//@ 3. Execute that instruction (do the thing the instruction set said to do)
//@ 4. Move on to the next instruction and repeat.
//@
//@ So now we will make the CPU do those things.
//@ We'll start off by teaching it how to access memory, and then we will
//@ define the instruction set.
//@
//@ ### Memory access
//@
//@ Now let's write a function to read a number from the specified memory address.

psf's avatar
psf committed
289
    fn load(&self, addr: u16) -> u16 {
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
//@ We immediately run into trouble because we are using byte-addressed
//@ memory as mentioned earlier.
//@
//@ Each memory location stores 8 bits (a byte)
//@
//@ Our CPU operates on 16 bit values and we want each memory operation
//@ to read/write 16 bits at a time for efficiency reasons.
//@
//@ What do we do?
//@
//@ This CPU chooses to do the following:
//@
//@ - Read the low byte of the 16-bit number from address a
//@ - Read the high byte of the 16-bit number from address a+1
//@
//@ ```
//@ 16 bit number in CPU: [00000000 00000001]        = 1
//@                        |        |
//@                        |        memory address a = 1
//@                        |
//@                        memory address a+1        = 0
//@ ```
//@
//@ This is called
//@ "[little endian](https://en.wikipedia.org/wiki/Endianness)"
//@ because the low byte comes first.
//@
//@ We could have just as easily done the opposite:
//@
//@ - Read the high byte of the 16-bit number from address a
//@ - Read the low  byte of the 16-bit number from address a+1
//@
//@ ```
//@ 16 bit number in CPU: [00000000 00000001]          = 1
//@                        |        |
//@                        |        memory address a+1 = 1
//@                        |
//@                        memory address a            = 0
//@ ```
//@
//@ This is called "big endian" because the high byte comes first.
//@
//@ The "le" in the function call below stands for little-endian.
334

335
        let a = addr as usize;
psf's avatar
psf committed
336
337
        return u16::from_le_bytes(self.ram[a..=a+1].try_into().unwrap());
    }
psf's avatar
psf committed
338

339
340
//@ Writing to memory is very similar, it just works in the opposite direction.

psf's avatar
psf committed
341
342
343
344
    fn store(&mut self, addr: u16, val: u16) {
        let a = addr as usize;
        self.ram[a..=a+1].copy_from_slice(&val.to_le_bytes());
    }
psf's avatar
psf committed
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
//@ With that taken care of, we can get around to defining the CPU's
//@ instruction set.
//@
//@ ### Designing the instruction set
//@
//@ Each instruction on this CPU will be the same size, 16 bits, for
//@ the following reasons:
//@
//@ 1. Instruction fetch always completes in 1 read.  You never have to
//@    go back and fetch more bytes.
//@
//@ 2. If you put the first instruction at an even numbered address then
//@    you know all the rest of the instructions will also be at even
//@    numbered addresses.  I will take advantage of this later.
//@
//@ 3. A variable length encoding would save space but 2 bytes per
//@    instruction is already pretty small so it doesn't matter very much.
//@
//@ Here are the instructions I picked.
//@
//@ #### The CALL instruction
//@
//@ ```
//@ CALL
//@ ------------------------------------------------------------+----
//@ | n   n   n   n   n   n   n   n   n   n   n   n   n   n   n | 0 |
//@ ------------------------------------------------------------+----
//@ ```
//@
//@ ##### What CALL does
//@
//@ - Push instruction pointer onto the return stack.
//@ - Set instruction pointer to address nnnnnnnnnnnnnnn0.
//@
//@ This lets you call a subroutine at any even numbered address
//@ from 0 to 65534.
//@
//@ ##### Why this is useful
//@
//@ Together with the return stack, CALL lets you call subroutines.
//@
//@ A subroutine is a list of instructions that does something
//@ useful and then returns control to the caller.
//@
//@ For example:
//@
//@ ```
//@ Address   Instruction   Meaning
//@ 100 ->           200    Call 200
//@ 102 ->           ???    Add the top two values on the data stack.
//@ ...
//@ 200 ->           ???    Push the value 3 onto the data stack
//@ 202 ->           ???    Push the value 4 onto the data stack
//@ 204 ->           ???    Return to caller
//@ ```
//@
//@ Don't worry about the other instructions I am using here.  I will
//@ define them later.
//@
//@ I mostly want to point out the three instructions that I put
//@ at address 200 because they are a subroutine,
//@ a small self contained piece of code (6 bytes) that
//@ performs a specific task.
//@
//@ Do you think it's cool that you can count exactly how many bytes it
//@ took?  I think it's cool.
//@
//@ Here is what happens when the CPU begins execution at address 100.
//@
//@ ```
//@ Address   Data stack   Return stack
//@ 100       []           []    <--- About to call subroutine...
//@ 200       []           [102]
//@ 202       [3]          [102]
//@ 204       [3 4]        [102] <--- About to return from subroutine...
//@ 102       [3 4]        []
//@ 104       [7]          []
//@ ```
//@
//@  The return stack is there to make sure that returning from a subroutine
//@  goes back to where it came from.  We will talk more about the return
//@  stack later when we talk about the RET instruction.
//@
//@ ##### Limitations of CALL:
//@
//@ This CPU cannot call an instruction that starts at an odd address.
//@
//@ At first this seems like a limitation, but it really isn't.
//@ If you put the first instruction at an even numbered address then
//@ all the rest of the instructions will also be at even numbered
//@ addresses.  So this works fine.
//@
//@ Of course if you intersperse instructions and data in memory...
//@
//@ ```
//@            _________
//@  ________ |_________| _____________
//@ |________|    Data   |_____________|
//@ Instructions         More instructions
//@ ```
//@
//@ ...then you will have to be careful to make sure the second block
//@ of instructions also starts at an even numbered address.
//@ You might need to include an extra byte of data as
//@ "[padding](https://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding)".
//@
//@ #### Data processing instructions
//@ ```
//@ Data processing instructions
//@ --------------------------------------------+---------------+----
//@ | 1   1   1   1   1   1   1   1   1   1   1 | x   x   x   x | 0 |
//@ --------------------------------------------+---------------+----
//@ ```
//@
//@ Sixteen of the even numbers are reserved for additional instructions
//@ that will be be described later.
//@
//@ The even numbers 1111111111100000 to 1111111111111110 (65504 to 65534)
//@ are reserved for these instructions.  This means that CALL 65504 through
//@ CALL 65534 are not possible.  Put another way, it is not possible to
//@ call a subroutine living in the top 32 bytes of memory.  This is not a
//@ very severe limitation.
//@
//@ #### The LITERAL instruction
//@ ```
//@ LITERAL
//@ ------------------------------------------------------------+----
//@ | n   n   n   n   n   n   n   n   n   n   n   n   n   n   n | 1 |
//@ ------------------------------------------------------------+----
//@ ```
//@
//@ ##### What LITERAL does
//@
//@ - Place the value 0nnnnnnnnnnnnnnn on the data stack.
//@
//@ ##### Why this is useful:
//@
//@ Programs will often need to deal with constant numbers.
//@ For example, you might want to add 2 to a memory address (to move
//@ on to the next even-numbered address) or add 32 to a character code
//@ (to convert an uppercase letter to lowercase).  These constants have
//@ to come from somewhere.
//@
//@ ##### Limitations of LITERAL:
//@
//@ To differentiate it from a call, this instruction is always an
//@ odd number.  The trailing 1 is discarded before placing the number on
//@ the data stack.  This missing bit means that only 2^15 values can be
//@ represented (0 to 32767).  32768 on up cannot be stored directly.
//@ You would need to do some follow-up math to get these numbers.
//@ The most direct way is to use the INV instruction, described later.
//@
//@ ### Making the CPU run
//@
//@ Now that the instruction set is generally described let's look at
//@ the code that implements it.
502

psf's avatar
psf committed
503
    fn step(&mut self) {
504

psf's avatar
psf committed
505
506
        /* 1. Fetch the instruction.
         * Also advance ip to point at the next instruction for next time. */
507

psf's avatar
psf committed
508
509
        let opcode = self.load(self.ip);
        self.ip = self.ip.wrapping_add(2);
psf's avatar
psf committed
510

psf's avatar
psf committed
511
        /* 2. Decode and execute the instruction */
512

psf's avatar
psf committed
513
        if (opcode >= 0xffe0) && (opcode & 1 == 0) {
514

psf's avatar
psf committed
515
            /* Data processing instruction */
516

psf's avatar
psf committed
517
            PRIMITIVES[((opcode - 0xffe0) >> 1) as usize](self);
518

psf's avatar
psf committed
519
520
521
522
523
524
525
526
527
528
529
530
            /* These instructions get looked up in a table.  The bit
             * math converts the instruction code into an index in the
             * table as follows:
             *
             * 0xffe0 --> 0
             * 0xffe2 --> 1
             * ...
             * 0xfffe --> 15
             *
             * The table will be described below, and these instructions
             * explained.
             */
531

psf's avatar
psf committed
532
        }
psf's avatar
psf committed
533
        else if (opcode & 1) == 1 {
psf's avatar
psf committed
534
            /* Literal */
psf's avatar
psf committed
535
            self.dstack.push(opcode >> 1);
536
        }
psf's avatar
psf committed
537
        else {
psf's avatar
psf committed
538
            /* Call */
psf's avatar
psf committed
539
540
            self.rstack.push(self.ip);
            self.ip = opcode;
541
542
543
544
        }
    }
}

545
546
547
548
549
//@ The CALL and LITERAL instructions are directly handled above.
//@
//@ The 16 data processing instructions are each assigned a number in the
//@ appropriate range that we carved out for them...

psf's avatar
psf committed
550
551
552
553
554
555
556
enum Op {
    RET = 0xffe0, TOR = 0xffe2, RTO = 0xffe4, LD  = 0xffe6,
    ST  = 0xffe8, DUP = 0xffea, SWP = 0xffec, DRP = 0xffee,
    Q   = 0xfff0, ADD = 0xfff2, SFT = 0xfff4, OR  = 0xfff6,
    AND = 0xfff8, INV = 0xfffa, GEQ = 0xfffc, IO  = 0xfffe,
}

557
558
559
//@ ...which is then looked up in the table below.  This table gives each
//@ instruction its unique behavior.

psf's avatar
psf committed
560
561
type Primitive = fn(&mut Core);

psf's avatar
psf committed
562
const PRIMITIVES: [Primitive; 16] = [
563
564
565

//@ #### Return-stack instructions

psf's avatar
psf committed
566
    | x | {
psf's avatar
psf committed
567
        /* RET - Return from subroutine */
psf's avatar
psf committed
568
569
        x.ip = x.rstack.pop()
    },
570

psf's avatar
psf committed
571
    | x | {
psf's avatar
psf committed
572
        /* TOR - Transfer number from data stack to return stack */
psf's avatar
psf committed
573
574
        x.rstack.push(x.dstack.pop())
    },
575

psf's avatar
psf committed
576
    | x | {
psf's avatar
psf committed
577
        /* RTO - Transfer number from return stack to data stack */
psf's avatar
psf committed
578
579
        x.dstack.push(x.rstack.pop())
    },
580
581
582

//@ #### Memory instructions

psf's avatar
psf committed
583
    | x | {
psf's avatar
psf committed
584
        /* LD - Load number from memory address specified on the data stack */
psf's avatar
psf committed
585
586
587
        let a = x.dstack.pop();
        x.dstack.push(x.load(a));
    },
588

psf's avatar
psf committed
589
    | x | {
psf's avatar
psf committed
590
        /* ST - Store number to memory address specified on the data stack */
psf's avatar
psf committed
591
592
593
594
        let a = x.dstack.pop();
        let v = x.dstack.pop();
        x.store(a, v);
    },
595

596
597
598
599
600
601
602
603
604
605
606
//@ #### Stack shuffling instructions
//@
//@ Remember the problem of "register allocation" mentioned earlier,
//@ and how stack machines are supposed to avoid that problem?  Well,
//@ nothing comes for free.  Stack machines can only process the top
//@ value(s) on the stack.  So sometimes you will have to do some work
//@ to "unbury" a crucial value and move it to the top of the stack.
//@ That's what these instructions are for.
//@
//@ Their use will become more obvious when we start programming the
//@ machine, soon.
607

psf's avatar
psf committed
608
    | x | {
609
        /* DUP - Duplicate the top number on the data stack */
psf's avatar
psf committed
610
611
612
613
        let v = x.dstack.pop();
        x.dstack.push(v);
        x.dstack.push(v);
    },
614

psf's avatar
psf committed
615
    | x | {
616
        /* SWP - Exchange the top two numbers on the data stack */
psf's avatar
psf committed
617
618
619
620
621
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1);
        x.dstack.push(v2);
    },
622

psf's avatar
psf committed
623
    | x | {
624
        /* DRP - Discard the top number on the data stack */
psf's avatar
psf committed
625
626
        let _ = x.dstack.pop();
    },
627
628
629
630
631
632
633

//@ #### Conditional skip instruction
//@
//@ We only have one of these: "Q".  This is the only "decision-making"
//@ instruction that our CPU has.  This means that all "if-then" logic,
//@ counted loops, etc.  will be built using Q.

psf's avatar
psf committed
634
635
    | x | {
        /* Q - If the top number on the data stack is zero, skip the next
636
         * instruction. */
637

psf's avatar
psf committed
638
639
640
        let f = x.dstack.pop();
        if f == 0 {
            x.ip = x.ip.wrapping_add(2)
641
        }
psf's avatar
psf committed
642
    },
643
644
645
646
647
648

//@ Because all of our instructions are two bytes, adding two to the
//@ instruction pointer skips the next instruction.
//@
//@ #### Arithmetic and logic

psf's avatar
psf committed
649
    | x | {
650
        /* ADD - Sum the top two numbers on the data stack. */
psf's avatar
psf committed
651
652
653
654
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1.wrapping_add(v2));
    },
655

psf's avatar
psf committed
656
657
658
659
    | x | {
        /* SFT - Bit shift number left or right by the specified amount.
         * A positive shift amount will shift left, negative will shift right.
         */
660

psf's avatar
psf committed
661
662
663
664
665
666
667
668
669
        let amt = x.dstack.pop();
        let val = x.dstack.pop();
        x.dstack.push(
            if amt <= 0xf {
                val << amt
            } else if amt >= 0xfff0 {
                val >> (0xffff - amt + 1)
            } else {
                0
psf's avatar
psf committed
670
            }
psf's avatar
psf committed
671
672
        );
    },
673

psf's avatar
psf committed
674
    | x | { // OR - Bitwise-or the top two numbers on the data stack.
psf's avatar
psf committed
675
676
677
678
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1 | v2);
    },
679

psf's avatar
psf committed
680
    | x | { // AND - Bitwise-and the top two numbers on the data stack.
psf's avatar
psf committed
681
682
683
684
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1 & v2);
    },
685

psf's avatar
psf committed
686
    | x | { // INV - Bitwise-invert the top number on the data stack.
psf's avatar
psf committed
687
688
689
        let v1 = x.dstack.pop();
        x.dstack.push(!v1);
    },
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707

//@ You can use the INV instruction to compensate for the LITERAL
//@ instruction's inability to encode constants 32768 to 65535,
//@ a.k.a. the
//@ [signed](https://en.wikipedia.org/wiki/Two%27s_complement)
//@ negative numbers.
//@
//@ Use two instructions instead:
//@
//@ - LITERAL the complement of your desired constant
//@ - INV
//@
//@ For example,
//@
//@ - LITERAL(0) INV yields 65535 (signed -1)
//@ - LITERAL(1) INV yields 65534 (signed -2)
//@ - etc.

psf's avatar
psf committed
708
    | x | { // GEQ - Unsigned-compare the top two items on the data stack.
psf's avatar
psf committed
709
710
711
712
        let v2 = x.dstack.pop();
        let v1 = x.dstack.pop();
        x.dstack.push(if v1 >= v2 { 0xffff } else { 0 });
    },
713

714
715
716
717
718
719
720
721
722
723
724
//@ #### Input/output
//@
//@ The CPU needs some way to communicate with the outside world.
//@
//@ Some machines use memory mapped IO where certain memory addresses are
//@ routed to hardware devices instead of main memory.  This machine already
//@ has the full 64K of memory connected so no address space is readily
//@ available for hardware devices.
//@ Instead we define a separate input-output space of 65536 possible
//@ locations.  Each of these possible locations is called an IO
//@ "[port](https://en.wikipedia.org/wiki/IO_port)".
725

psf's avatar
psf committed
726
    | x | { // IO - Write/read a number from/to input/output port.
psf's avatar
psf committed
727
        let port = x.dstack.pop();
728

729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//@ For a real CPU you could hook up hardware such as a serial
//@ transmitter that sends data to a computer terminal, or just an
//@ output pin controller that is wired to a light bulb.
//@
//@ This is a fake software CPU so I am going to hook it up to
//@ [stdin and stdout](https://en.wikipedia.org/wiki/Standard_streams).

        use std::io;
        use std::io::Read;
        use std::io::Write;

//@ I'm loosely following a pattern in which even ports are inputs
//@ and odd ports are outputs.  But each port acts different.
//@ In a hardware CPU this would not be suitable but it is fine for
//@ a software emulation.
744

psf's avatar
psf committed
745
746
        match port {
            0 => {
psf's avatar
psf committed
747
                /* Push a character from stdin onto the data stack */
psf's avatar
psf committed
748
749
750
                let mut buf: [u8; 1] = [0];
                let _ = io::stdin().read(&mut buf);
                x.dstack.push(buf[0] as u16);
psf's avatar
psf committed
751
752
                /* You are welcome to make your own computer that supports
                 * utf-8, but this one does not. */
psf's avatar
psf committed
753
754
            }
            1 => {
psf's avatar
psf committed
755
                /* Pop a character from the data stack to stdout */
psf's avatar
psf committed
756
757
758
759
760
                let val  = x.dstack.pop();
                print!("{}", ((val & 0xff) as u8) as char);
                let _ = io::stdout().flush();
            }
            2 => {
psf's avatar
psf committed
761
                /* Dump CPU status.
762
763
                 * Like the front panel with the blinking lights that Chuck
                 * talked about. */
764
                println!("{:?} {:?}", x.ip, x.dstack);
psf's avatar
psf committed
765
766
767
                let _ = io::stdout().flush();
            }
            _ => {}
psf's avatar
psf committed
768
        }
psf's avatar
psf committed
769
    }
770
771
772

//@ That's all the CPU instructions we'll need.

psf's avatar
psf committed
773
];
psf's avatar
psf committed
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
//@ # Part 2 - The Program
//@
//@ You now have an unfamiliar computer with no software.  Can you and the
//@ computer write a program?
//@
//@ The first program is the hardest to write because you don't have any tools
//@ to help write it.  The computer itself is going to be no help.  Without any
//@ program it will sit there doing nothing.
//@
//@ What should the first program be?
//@ A natural choice would be a tool that helps you program more easily.
//@
//@ An interactive programming environment needs to let you do 2 things:
//@
//@ 1. Call subroutines by typing their name at the keyboard
//@ 2. Define new subroutines in terms of existing ones
//@
//@ Begin with step 1:
//@ Call subroutines by typing their name at the keyboard
//@
//@ This is where we will meet Forth.
//@
//@ Our interactive programming environment will be a small language in the
//@ Forth family.  If you want to learn how to implement a full featured Forth,
//@ please read
//@ [Jonesforth](http://git.annexia.org/?p=jonesforth.git;a=blob;f=jonesforth.S),
//@ and Brad Rodriguez' series of articles
//@ "[Moving Forth](http://www.bradrodriguez.com/papers/index.html)".
//@ The small Forth I write below will probably help you understand
//@ those Forths a little better.
//@
//@ Forth organizes all the computer's memory as a "dictionary" of subroutines.
//@ The point of the dictionary is to give each subroutine a name so you
//@ can run a subroutine by typing its name.  The computer will look up its
//@ address for you and call it.
//@
//@ ### Designing the Forth dictionary
//@
//@ The dictionary starts at a low address and grows towards high addresses.
//@ It is organized as a
//@ [linked list](https://en.wikipedia.org/wiki/Linked_list), like this:
//@
//@ ```
//@ [Link field][Name][Code .......... ]
//@  ^
//@  |
//@ [Link field][Name][Code ...... ]
//@  ^
//@  |
//@ [Link field][Name][Code ............... ]
//@ ```
//@
//@ The reason it is a linked list is to allow each list entry to be a
//@ different length.
//@
//@ Each dictionary entry contains three things:
//@
//@ - "Link field": The address of the previous dictionary entry.
//@                 For the first dictionary entry this field is 0.
//@
//@ - "Name": A few letters to name this dictionary entry.
//@           Later you will type this name at the keyboard to call up
//@           this dictionary entry.
//@
//@ - "Code": A subroutine to execute when you call up this dictionary
//@           entry.  This is a list of CPU instructions.  Note that one
//@           of the CPU instructions is "call".  So you can have a subroutine
//@           that call other subroutines, or calls itself.  This code should
//@           end with a return (RET) instruction.  Here is an example subroutine:
//@
//@ ```
//@ Number Instruction  Meaning
//@ ------ -----------  -------
//@ 7      Literal(3)   Push the value 3 onto the data stack
//@ 9      Literal(4)   Push the value 4 onto the data stack
//@ 65504  RET          Return to caller
//@ ```
//@
//@ A linked list is not a very fast data structure but this doesn't really
//@ matter because dictionary lookup doesn't need to be fast.  Lookups are
//@ for converting text you typed at the keyboard to subroutine addresses.
//@ You can't type very fast compared to a computer so this lookup doesn't
//@ need to be fast.
//@
//@ In addition to the linked list itself, you will need a couple of
//@ variables to keep track of where the dictionary is in memory:
//@
//@ - Dictionary pointer:  The address of the newest dictionary entry.
//@ - Here:                The address of the first unused memory location,
//@                        which comes just after the newest dictionary entry.
//@
//@ ```
//@ [Link field][Name][Code .......... ]
//@  ^
//@  |
//@ [Link field][Name][Code ...... ]
//@  ^
//@  |
//@ [Link field][Name][Code ............... ]
//@  ^                                       ^
//@  |                                       |
//@ [Dictionary pointer]                    [Here]
//@ ```
//@
//@ ### Tools for building the Forth dictionary
//@
//@ If you were sitting in front of a minicomputer in 196x you would need
//@ to create the dictionary with pencil and paper, but in 20xx we will
//@ write a Rust program to help create the dictionary.
//@
//@ First we need to keep track of where the dictionary is:
psf's avatar
psf committed
886

psf's avatar
psf committed
887
struct Dict<'a> {
psf's avatar
psf committed
888
889
890
891
892
    dp: u16,   // The dictionary pointer
    here: u16, // The "here" variable
    c: &'a mut Core  // The dictionary lives in memory.  We are going to
                     // hang on to a mutable reference to the core to give
                     // us easy access to the memory.
893
894
}

895
//@ Now we can write functions in Rust to help us build the dictionary.
psf's avatar
psf committed
896

psf's avatar
psf committed
897
898
899
900
enum Item {
    Literal(u16),
    Call(u16),
    Opcode(Op)
Peter Fidelman's avatar
call    
Peter Fidelman committed
901
}
psf's avatar
psf committed
902
903
impl From<u16> for Item { fn from(a: u16) -> Self { Item::Call(a) } }
impl From<Op>  for Item { fn from(o: Op)  -> Self { Item::Opcode(o) } }
Peter Fidelman's avatar
call    
Peter Fidelman committed
904

psf's avatar
psf committed
905
impl Dict<'_> {
906

psf's avatar
psf committed
907
908
    /* Helper to reserve space in the dictionary by advancing the "here"
     * pointer */
909

psf's avatar
psf committed
910
911
    fn allot(&mut self, n: u16) {
        self.here = self.here.wrapping_add(n);
912
    }
psf's avatar
psf committed
913

psf's avatar
psf committed
914
    /* Helper to append a 16 bit integer to the dictionary */
915

psf's avatar
psf committed
916
917
918
    fn comma(&mut self, val: u16) {
        self.c.store(self.here, val);
        self.allot(2);
psf's avatar
psf committed
919
    }
920

psf's avatar
psf committed
921
    /* Helper to append a CPU instruction to the dictionary */
922

psf's avatar
psf committed
923
924
925
926
927
928
    fn emit<T: Into<Item>>(&mut self, val: T) {
        match val.into() {
            Item::Call(val)    => { self.comma(val) }
            Item::Opcode(val)  => { self.comma(val as u16) }
            Item::Literal(val) => { assert!(val <= 0x7fff);
                                    self.comma((val << 1) | 1) }
psf's avatar
psf committed
929
930
        }
    }
psf's avatar
psf committed
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
    /* Helper to append a "name" field to the dictionary. */

//@ The "name" field bears a closer look.  To make each dictionary header a
//@ consistent size, I am choosing to not store every letter of the name.
//@ Instead I am storing only the length of the name and then the first
//@ three letters of the name.
//@
//@ That means these two names will compare equal:
//@
//@ - ALLOW (-> 5ALL)
//@ - ALLOT (-> 5ALL)
//@
//@ Even though their first three letters are the same, these two names
//@ will compare unequal because they are different lengths:
//@
//@ - FORTH (-> 5FOR)
//@ - FORGET (-> 6FOR)
//@
//@ If a name is shorter than 3 letters it is padded out with spaces.
//@
//@ - X (-> `1X  `)
//@
//@ You can see that the name field is always four bytes regardless
//@ of how many letters are in the name, and the link field is two bytes.
//@ This means a dictionary header in this Forth is always six bytes.
957

psf's avatar
psf committed
958
    fn name(&mut self, n: u8, val: [u8; 3]) {
psf's avatar
psf committed
959
        /* Store the length and the first character */
psf's avatar
psf committed
960
        self.comma(n as u16 | ((val[0] as u16) << 8));
961

psf's avatar
psf committed
962
        /* Store the next two characters */
psf's avatar
psf committed
963
        self.comma(val[1] as u16 | ((val[2] as u16) << 8));
psf's avatar
psf committed
964
965
    }

966
967
968
//@ Finally, a function that appends a new link field to the dictionary,
//@ pointing to the previous dictionary entry.

psf's avatar
psf committed
969
970
    /* Helper to append a new link field to the dictionary and update the
     * dictionary pointer appropriately. */
971

psf's avatar
psf committed
972
973
974
975
    fn entry(&mut self) {
        let here = self.here;
        self.comma(self.dp);
        self.dp = here;
psf's avatar
psf committed
976
977
978
    }
}

979
980
981
982
983
984
985
986
987
988
989
990
991
992

//@ Now we can start building the dictionary.
//@
//@ To create our Forth interactive programmming environment, we will start
//@ by defining subroutines that:
//@
//@ - read names from the keyboard
//@ - look up and execute dictionary entries by name
//@
//@ We will put these subroutines themselves in the dictionary so they are
//@ available for use once our interactive environment is up and running!
//@
//@ ### Building the Forth dictionary

psf's avatar
psf committed
993
994
995
fn build_dictionary(c: &mut Core) {
    use Op::*;
    use Item::*;
psf's avatar
psf committed
996

psf's avatar
psf committed
997
998
    let mut d = Dict {
        dp: 0,  /* Nothing in the dictionary yet */
999

1000
        here: 2,  /* Reserve address 0 as the "reset vector", i.e. where the
For faster browsing, not all history is shown. View entire blame