README.md 83.4 KB
Newer Older
Peter Fidelman's avatar
Peter Fidelman committed
1
2
Project URL: https://gitlab.cs.washington.edu/fidelp/frustration

psf's avatar
psf committed
3
4
Frustration - Escaping a Turing Tar Pit with Forth

Peter Fidelman's avatar
Peter Fidelman committed
5
6
# What is this file?

psf's avatar
psf committed
7
This is a tutorial that will show you how to bootstrap an interactive
Peter Fidelman's avatar
Peter Fidelman committed
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
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".

```rust
const ADDRESS_SPACE: usize = 65536;
```

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.

```rust
#[derive(Debug)]
struct Stack<const N: usize> {
    mem: [u16; N],
    tos: usize  /* top-of-stack */
}
```

First we'll need a function to add a number to the stack.
Peter Fidelman's avatar
Peter Fidelman committed
168

Peter Fidelman's avatar
Peter Fidelman committed
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
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.

```rust
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;
    }
```

We'll also need a function to remove & return the most recently pushed
number.

```rust
    fn pop(&mut self) -> u16 {
        let val = self.mem[self.tos];
        self.mem[self.tos] = 0;
```

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!().

```rust
        self.tos = (self.tos.wrapping_sub(1)) & (N - 1);
        return val;
    }
202
203
204
205
206
207
208
209
210
211
212
213
```

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.

```rust
    fn new() -> Stack<N> {
        return Stack {tos: N-1, mem: [0; N]};
    }
Peter Fidelman's avatar
Peter Fidelman committed
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
}
```
### 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.

```rust
struct Core {
    ram: [u8; ADDRESS_SPACE],
    ip: u16,  /* instruction pointer */
    dstack: Stack<16>, /* data stack */
    rstack: Stack<32>  /* return stack */
}
```

258
Finally, let's write a function that creates and returns a CPU for us to use.
Peter Fidelman's avatar
Peter Fidelman committed
259
260

```rust
261
use std::convert::TryInto;
Peter Fidelman's avatar
Peter Fidelman committed
262

263
264
265
266
267
268
269
270
impl Core {
    fn new() -> Core {
        return Core {
            ram: [0; ADDRESS_SPACE],
            ip: 0,
            dstack: Stack::new(),
            rstack: Stack::new()}
    }
Peter Fidelman's avatar
Peter Fidelman committed
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
```

## 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

303
Now let's write a function to read a number from the specified memory address.
Peter Fidelman's avatar
Peter Fidelman committed
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

```rust
    fn load(&self, addr: u16) -> u16 {
```

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.

```rust
        let a = addr as usize;
        return u16::from_le_bytes(self.ram[a..=a+1].try_into().unwrap());
    }
```

Writing to memory is very similar, it just works in the opposite direction.

```rust
    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());
    }
```

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]        []
Peter Fidelman's avatar
Peter Fidelman committed
444
104       [7]          []
Peter Fidelman's avatar
Peter Fidelman committed
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
```

 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.

```rust
    fn step(&mut self) {

        /* 1. Fetch the instruction.
         * Also advance ip to point at the next instruction for next time. */

        let opcode = self.load(self.ip);
        self.ip = self.ip.wrapping_add(2);

        /* 2. Decode and execute the instruction */

        if (opcode >= 0xffe0) && (opcode & 1 == 0) {

            /* Data processing instruction */

            PRIMITIVES[((opcode - 0xffe0) >> 1) as usize](self);

            /* 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.
             */

        }
        else if (opcode & 1) == 1 {
            /* Literal */
            self.dstack.push(opcode >> 1);
        }
        else {
            /* Call */
            self.rstack.push(self.ip);
            self.ip = opcode;
        }
    }
}
```

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...

```rust
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,
}
```

...which is then looked up in the table below.  This table gives each
instruction its unique behavior.

```rust
type Primitive = fn(&mut Core);

const PRIMITIVES: [Primitive; 16] = [
```

#### Return-stack instructions

```rust
    | x | {
        /* RET - Return from subroutine */
        x.ip = x.rstack.pop()
    },
```

```rust
    | x | {
        /* TOR - Transfer number from data stack to return stack */
        x.rstack.push(x.dstack.pop())
    },
```

```rust
    | x | {
        /* RTO - Transfer number from return stack to data stack */
        x.dstack.push(x.rstack.pop())
    },
```

#### Memory instructions

```rust
    | x | {
        /* LD - Load number from memory address specified on the data stack */
        let a = x.dstack.pop();
        x.dstack.push(x.load(a));
    },
```

```rust
    | x | {
        /* ST - Store number to memory address specified on the data stack */
        let a = x.dstack.pop();
        let v = x.dstack.pop();
        x.store(a, v);
    },
```

#### 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.

```rust
    | x | {
        /* DUP - Duplicate the top number on the data stack */
        let v = x.dstack.pop();
        x.dstack.push(v);
        x.dstack.push(v);
    },
```

```rust
    | x | {
        /* SWP - Exchange the top two numbers on the data stack */
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1);
        x.dstack.push(v2);
    },
```

```rust
    | x | {
        /* DRP - Discard the top number on the data stack */
        let _ = x.dstack.pop();
    },
```

#### 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.

```rust
    | x | {
        /* Q - If the top number on the data stack is zero, skip the next
         * instruction. */

        let f = x.dstack.pop();
        if f == 0 {
            x.ip = x.ip.wrapping_add(2)
        }
    },
```

Because all of our instructions are two bytes, adding two to the
instruction pointer skips the next instruction.

#### Arithmetic and logic

```rust
    | x | {
        /* ADD - Sum the top two numbers on the data stack. */
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1.wrapping_add(v2));
    },
```

```rust
    | x | {
        /* SFT - Bit shift number left or right by the specified amount.
         * A positive shift amount will shift left, negative will shift right.
         */

        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
            }
        );
    },
```

```rust
    | x | { // OR - Bitwise-or the top two numbers on the data stack.
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1 | v2);
    },
```

```rust
    | x | { // AND - Bitwise-and the top two numbers on the data stack.
        let v1 = x.dstack.pop();
        let v2 = x.dstack.pop();
        x.dstack.push(v1 & v2);
    },
```

```rust
    | x | { // INV - Bitwise-invert the top number on the data stack.
        let v1 = x.dstack.pop();
        x.dstack.push(!v1);
    },
```

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.

```rust
    | x | { // GEQ - Unsigned-compare the top two items on the data stack.
        let v2 = x.dstack.pop();
        let v1 = x.dstack.pop();
        x.dstack.push(if v1 >= v2 { 0xffff } else { 0 });
    },
```

#### 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)".

```rust
    | x | { // IO - Write/read a number from/to input/output port.
        let port = x.dstack.pop();
```

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
Peter Fidelman's avatar
Peter Fidelman committed
794
[stdin and stdout](https://en.wikipedia.org/wiki/Standard_streams).
Peter Fidelman's avatar
Peter Fidelman committed
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

```rust
        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.

```rust
        match port {
            0 => {
                /* Push a character from stdin onto the data stack */
                let mut buf: [u8; 1] = [0];
                let _ = io::stdin().read(&mut buf);
                x.dstack.push(buf[0] as u16);
                /* You are welcome to make your own computer that supports
                 * utf-8, but this one does not. */
            }
            1 => {
                /* Pop a character from the data stack to stdout */
                let val  = x.dstack.pop();
                print!("{}", ((val & 0xff) as u8) as char);
                let _ = io::stdout().flush();
            }
            2 => {
                /* Dump CPU status.
                 * Like the front panel with the blinking lights that Chuck
                 * talked about. */
                println!("{:?} {:?}", x.ip, x.dstack);
                let _ = io::stdout().flush();
            }
            _ => {}
        }
    }
```

Peter Fidelman's avatar
Peter Fidelman committed
835
836
That's all the CPU instructions we'll need.

Peter Fidelman's avatar
Peter Fidelman committed
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
```rust
];
```

# 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
Peter Fidelman's avatar
Peter Fidelman committed
868
"[Moving Forth](http://www.bradrodriguez.com/papers/index.html)".
Peter Fidelman's avatar
Peter Fidelman committed
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
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:

```rust
struct Dict<'a> {
    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.
}
```

Now we can write functions in Rust to help us build the dictionary.

```rust
enum Item {
    Literal(u16),
    Call(u16),
    Opcode(Op)
}
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) } }

impl Dict<'_> {

    /* Helper to reserve space in the dictionary by advancing the "here"
     * pointer */

    fn allot(&mut self, n: u16) {
        self.here = self.here.wrapping_add(n);
    }

    /* Helper to append a 16 bit integer to the dictionary */

    fn comma(&mut self, val: u16) {
        self.c.store(self.here, val);
        self.allot(2);
    }

    /* Helper to append a CPU instruction to the dictionary */

    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) }
        }
    }

For faster browsing, not all history is shown. View entire blame