-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathchapter7.tex
More file actions
1584 lines (1313 loc) · 58.3 KB
/
chapter7.tex
File metadata and controls
1584 lines (1313 loc) · 58.3 KB
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
%% Thinking Forth
%% Copyright (C) 2004 Leo Brodie
%% Initial transcription by Nils M Holm
%% Based on OCR scans by Steve Fisher
%% -*-coding: iso-8859-1;-*-
\chapter{Handling~Data: Stacks~and~States}\Chapmark{7}
\expandafter\initial\Forth{} handles data in one of two ways: either
on the stack or in data structures. When to use which approach and how
to manage both the stack and data structures are the topics of this
chapter.
\section{The Stylish Stack}%
\index{D!Data stacks!concept of|(}
The simplest way for \Forth{} words to pass arguments to each other is
via the stack. The process is ``simple'' because all the work of pushing
and popping values to and from the stack is implicit.
\begin{interview}
\person{Moore}:\index{M!Moore, Charles|(}
\begin{tfquot}
The data stack uses this idea of ``hidden information.'' The arguments
being passed between subroutines are not explicit in the calling sequence.
The same argument might ripple through a whole lot of words quite invisibly,
even below the level of awareness of the programmer, simply because it
doesn't have to be referred to explicitly.
\end{tfquot}\index{M!Moore, Charles|)}
\end{interview}
One important result of this approach: Arguments are unnamed. They
reside on the stack, not in named variables. This effect is one of the
reasons for \Forth{}'s elegance. At the same time it's one of the reasons
badly written \Forth{} code can be unreadable. Let's explore this
paradox.
The invention of the stack is analogous to that of pronouns in
English. Consider the passage:
%!! indent paragraph
\begin{tfquot}
Take this gift, wrap it in tissue paper and put it in a box.
\end{tfquot}
Notice the word ``gift'' is mentioned only once. The gift is referred to
henceforth as ``it.''
The informality of the ``it'' construct makes English more readable
(provided the reference is unambiguous). So with the stack, the implicit
passing of arguments makes code more readable. We emphasize the
\emph{processes}, not the \emph{passing of arguments} to the processes.
Our analogy to pronouns suggests why bad \Forth{} can be so unreadable.
The spoken language gets confusing when too many things are
referred to with pronouns.
\begin{tfquot}
Take off the wrapping and open the box. Remove the gift and throw it
away.
\end{tfquot}
The problem with this passage is that we're using ``it'' to refer to too
many things at once. There are two solutions to this error. The easiest
solution is to supply a real name instead of ``it'':
\begin{tfquot}
Remove the wrapping and open the box. Take out the gift and throw
\emph{the box} away.
\end{tfquot}
Or we can introduce the words ``former'' and ``latter.'' But the best
solution is to redesign the passage:
\begin{tfquot}
Remove the wrapping and open the present. Throw away the box.
\end{tfquot}
So in \Forth{} we have analogous observations:
\begin{tip}
Simplify code by using the stack. But don't stack too deeply within any
single definition. Redesign, or, as a last resort, use a named variable.
\end{tip}
Some newcomers to \Forth{} view the stack the way a gymnast views a
trampoline: as a fun place to bounce around on. But the stack is meant for
data-passing, not acrobatics.
\index{D!Data stacks!depth of|(}%
So how deep is ``too deep?'' Generally, three elements on the stack is
the most you can manage within a single definition. (In double-length
arithmetic, each ``element'' occupies two stack positions but is logically
treated as a single element by operators such as \forthb{2DUP}, \forthb{2OVER},
etc.)
In your ordinary lexicon of stack operators, \forthb{ROT} is the only one
that gives you access to the third stack item. Aside from \forthb{PICK} and
\forthb{ROLL} (which we'll comment on soon), there's no easy way to get at
anything below that.
To stretch our analogy to the limit, perhaps three elements on the
stack corresponds to the three English pronouns ``this,'' ``that,'' and
``t'other.''%
\index{D!Data stacks!concept of|)}
\subsection{Redesign}
Let's witness a case where a wrong-headed approach leads to a messy
stack problem. Suppose we're trying to write the definition of \forth{+THRU}
(see \Chap{5}, ``Listing Organization'' section, ``Relative Loading''
subsection). We've decided that our loop body will be
\begin{Code}
... DO i load LOOP ;
\end{Code}
that is, we'll put \forthb{LOAD} in a loop, then arrange for the index and
limit to correspond to the absolute screens being loaded.
On the stack initially we have:
\begin{Code}
lo hi
\end{Code}
where ``lo'' and ``hi'' are the \emph{offsets} from \forthb{BLK}.
We need to permute them for \forthb{DO}, like this:
\begin{Code}
hi+1+blk lo+blk
\end{Code}
Our biggest problem is adding the value of \forth{BLK} to both offsets.
We've already taken a wrong turn but we don't know it yet. So let's
proceed. We try:
\begin{Code}
lo hi
blk @
lo hi blk
swap
lo blk hi
over
lo blk hi blk
+
lo blk hi+blk
1+
lo blk hi+blk+1
rot rot
hi+blk+1 lo blk
+
hi+blk+1 lo+blk
\end{Code}
We made it, but what a mess!
If we're gluttons for punishment, we might make two more stabs at
it arriving at:
\begin{Code}
blk @ dup rot + 1+ rot rot +
\end{Code}
and
\begin{Code}
blk @ rot over + rot rot + 1+ swap
\end{Code}
All three sequences do the same thing, but the code seems to be getting
blurrier, not better.
With experience we learn to recognize the combination \forth{ROT ROT} as
a danger sign: the stack is too crowded. Without having to work out the
alternates, we recognize the problem: once we make two copies of ``blk,''
we have four elements on the stack.
\medbreak
At this point, the first resort is usually the return stack:
\begin{Code}
blk @ dup >r + 1+ swap r> +
\end{Code}
(See ``The Stylish Return Stack,'' coming up next.) Here we've \forthb{DUP}ed
``blk,'' saving one copy on the return stack and adding the other copy to
``hi.''
Admittedly an improvement. But readable?
Next we think, ``Maybe we need a named variable.'' Of course, we
have one already: \forthb{BLK}. So we try:
\begin{Code}
blk @ + 1+ swap blk @ +
\end{Code}
Now it's more readable, but it's still rather long, and redundant too.
\forthb{BLK @ +} appears twice.
``\forthb{BLK @ +}''? That sounds familiar. Finally our neurons connect.
We look back at the source for \forth{+LOAD} just defined:
\begin{Code}
: +load ( offset -- ) blk @ + load ;
\end{Code}
This word, \forth{+LOAD}, should be doing the work. All we have to write is:
\begin{Code}
: +thru ( lo hi ) 1+ swap DO i +load LOOP ;
\end{Code}
We haven't created a more efficient version here, because the work of
\forthb{BLK @ +} will be done on every pass of the loop. But we have
created a cleaner, conceptually simpler, and more readable piece of code.
In this case, the inefficiency is unnoticeable because it only occurs as
each block is loaded.
Redesigning, or rethinking the problem, was the path we should
have taken as soon as things got ugly.%
\index{D!Data stacks!depth of|)}
\subsection{Local Variables}%
\index{L!Local variables|(}%
\index{D!Data stacks!local variables and,|(}%
\index{D!Data stacks!data@vs. data structures|(}%
\index{D!Data structures:!data@vs. data stacks|(}
\index{V!Variables:!local|(}%
Most of the time problems can be arranged so that only a few arguments
are needed on the stack at any one time. Occasionally, however, there's
nothing you can do.
Here's an example of a worst case. Assume you have a word called
\forth{LINE} which draws a line between any two points, specified as
coordinates in this order:
\begin{Code}
( x1 y1 x2 y2 -- )
\end{Code}
where $x_1,y_1$ represent the $x,y$ coordinates for the one end-point, and
$x_2,y_2$ represent the opposite end-point.
Now you have to write a box-drawing word called \forth{[BOX]} which
takes four arguments in this order:
\begin{Code}
( x1 y1 x2 y2 -- )
\end{Code}
where x1 y1 represent the $x,y$ coordinates for the upper left-hand corner
of the box, and x2 y2 represent the lower right-hand corner coordinates.
Not only do you have four elements on the stack, they each have to
be referred to more than once as you draw lines from point to point.
Although we're using the stack to get the four arguments, the algorithm
for drawing a box doesn't lend itself to the nature of the stack. If you're
in a hurry, it would probably be best to take the easy way out:
\begin{Code}
: [box] { x1 y1 x2 y2 -- }
x1 y1 x2 y1 line
x2 y1 x2 y2 line
x2 y2 x1 y2 line
x1 y2 x1 y1 line ;
\end{Code}
What we've done is create four named variables, one for each coordinate.
The first thing \forth{[BOX]} does is fill these variables with the
arguments from the stack. Then the four lines are drawn, referencing the
variables. Variables such as these that are used only within a definition
(or in some cases, within a lexicon) are called ``local variables.''
I've been guilty many times of playing hotshot, trying to do as
much as possible on the stack rather than define a local variable. There
are three reasons to avoid this cockiness.
First, it's a pain to code that way. Second, the result is unreadable.
Third, all your work becomes useless when a design change becomes
necessary, and the order of two arguments changes on the stack. The
\forthb{DUP}s, \forthb{OVER}s and \forthb{ROT}s weren't really solving the
problem, just jockeying things into position.
With this third reason in mind, I recommend the following:
\begin{tip}
Especially in the design phase, keep on the stack only the arguments you're
using immediately. Create local variables for any others. (If necessary,
eliminate the variables during the optimization phase.)
\end{tip}
Fourth, if the definition is extremely time-critical, those tricky stack
manipulators, (e.g., \forthb{ROT ROT}) can really eat up clock cycles.
Direct access to variables is faster.
If it's \emph{really} time-critical, you may need to convert to assembler
anyway. In this case, all your stack problems fly out the door, because
all your data will be referenced either in registers or indirectly through
registers. Luckily, the definitions with the messiest stack arguments are
often the ones written in code. Our \forth{[BOX]} primitive is a case in
point. \forthb{CMOVE>} is another.
The approach we took with \forth{[BOX]} certainly beats spending half an
hour juggling items on the stack, but it is by no means the best solution.
What's nasty about it is the expense of creating four named variables,
headers and all, solely for use within this one routine.
(If you're target compiling an application that will not require headers
in the dictionary, the only loss will be the 8 bytes in RAM for the
variables. In \Forth{} systems of the future, headers may be separated
into other pages of memory anyway; again the loss will be only 8 bytes.)
Let me repeat: This example represents a worst-case situation, and occurs
rarely in most \Forth{} applications. If words are well-factored, then
each word is designed to do very little. Words that do little generally
require few arguments.
In this case, though, we are dealing with two points each represented
by two coordinates.
Can we change the design? First, \forth{LINE} may be \emph{too} primitive a
primitive. It requires four arguments because it can draw lines between
any two points, diagonally, if necessary.
In drawing our box, we may only need perfectly vertical and horizontal
lines. In this case we can write the more powerful, but less specific,
words \forth{VERTICAL} and \forth{HORIZONTAL} to draw these lines. Each
requires only \emph{three} arguments: the starting position's x and y, and
the length. This factoring of function simplifies the definition of
\forth{[BOX].}
Or we might discover that this syntax feels more natural to the
user:
\begin{Code}
10 10 origin! 30 30 box
\end{Code}
where \forth{ORIGIN!} sets a two-element pointer to the ``origin,'' the
place where the box will start (the upper left-hand corner). Then
``\forth{30 30 BOX}'' draws a box 30 units high and 30 units wide,
relative to the origin.
This approach reduces the number of stack arguments to \forth{BOX} as
part of the design.
\begin{interview}
\person{Paysan}:
\begin{tfquot}
I prefer turtle graphics. This is a turtle graphics without cursor
direction, so the direction is explicit (using the same \forth{LINE}
primitive):
\begin{Code}
2variable pos
: setpos ( x y -- ) pos 2! ;
: p+ ( x y w h -- x' y' ) rot + >r + r> ;
: moveto ( dx dy -- ) pos 2@ p+ pos 2! ;
: drawto ( dx dy -- ) pos 2@ 2swap moveto pos 2@ line ;
: right ( dx -- ) 0 drawto ;
: down ( dy -- ) 0 swap drawto ;
: left ( dx -- ) negate right ;
: up ( dy -- ) negate down ;
: box ( w h -- ) 2dup down right up left ;
: [box] ( x y w h -- ) 2swap setpos box ;
\end{Code}
Now this seems to be a lot of work for a single box, to get rid of the
long definition and the stack juggling. But usually, it doesn't end
with a single box. And then the small initial work pays off big.
I think this is a good illustration how \Forth{} code should look
like. None of the definitions has more than 7 words. Only one has more
than one stack juggling word. The global variable now is no disguised
``local,'' but the state (position) of the turtle.
\end{tfquot}
\end{interview}
\begin{tip}
When determining which arguments to handle via data structures rather
than via the stack, choose the arguments that are the more permanent or
that represent a current state.
\end{tip}%
\index{L!Local variables|)}%
\index{V!Variables:!local|)}%
\index{D!Data stacks!local variables and,|)}%
\index{D!Data stacks!data@vs. data structures|)}%
\index{D!Data structures:!data@vs. data stacks|)}
\subsection{On PICK and ROLL}%
\index{D!Data stacks!PICK and ROLL|(}%
\index{P!PICK|(}%
\index{R!ROLL|(}%
Some folks like the words \forthb{PICK} and \forthb{ROLL}. They use these
words to access elements from any level on the stack. We don't recommend
them. For one thing, \forthb{PICK} and \forthb{ROLL} encourage the
programmer to think of the stack as an array, which it is not. If you have
so many elements on the stack that you need \forthb{PICK} and
\forthb{ROLL}, those elements should be in an array instead.
Second, they encourage the programmer to refer to arguments that
have been left on the stack by higher-level, calling definitions without
being explicitly \emph{passed} as arguments. This makes the definition
dependent on other definitions. That's unstructured---and dangerous.
Finally, the position of an element on the stack depends on what's
above it, and the number of things above it can change constantly. For
instance, if you have an address at the fourth stack position down, you can
write
\begin{Code}
4 pick @
\end{Code}
to fetch its contents. But you must write
\begin{Code}
( n) 5 pick !
\end{Code}
because with ``$n$'' on the stack, the address is now in the fifth position.
Code like this is hard to read and harder to modify.%
\index{D!Data stacks!PICK and ROLL|)}%
\index{P!PICK|)}%
\index{R!ROLL|)}%
\subsection{Make Stack Drawings}%
\index{D!Data stacks!drawings|(}
When you do have a cumbersome stack situation to solve, it's best to work
it out with paper and pencil. Some people even make up forms, such as the
one in \Fig{fig7-1}. Done formally like this (instead of on the back of your
phone bill), stack commentaries serve as nice auxiliary documentation.
\subsection{Stack Tips}
\begin{tip}
Make sure that stack effects balance out under all possible control flows.
\end{tip}
In the stack commentary for \forthb{CMOVE>} in \Fig{fig7-1}, the inner
brace represents the contents of the \forthb{DO }\forthb{LOOP}. The stack
depth upon exiting the loop is the same as upon entering it: one element.
Within the outer braces, the stack result of the \forthb{IF} clause is the
same as that of the \forthb{ELSE} clause: one element left over. (What
that leftover element represents doesn't matter, as symbolized by the
``x'' next to \forthb{THEN}.)
\wepsfiga{fig7-1}{Example of a stack commentary.}
%!! include \Fig{fig7-1} here
\begin{tip}
When doing two things with the same number, perform the function that
will go underneath first.
\end{tip}
For example:
\begin{Code}
: count ( a -- a+1 # ) dup c@ swap 1+ swap ;
\end{Code}
(where you first get the count) is more efficiently written:
\begin{Code}
: count ( a -- a+1 # ) dup 1+ swap c@ ;
\end{Code}
(where you first compute the address).
\goodbreak
\begin{tip}
Where possible, keep the number of return arguments the same in all
possible cases.
\end{tip}%
\index{E!Error-code|(}
You'll often find a definition which does some job and, if something goes
wrong, returns an error-code identifying the problem. Here's one way
the stack interface might be designed:
\begin{Code}
( -- error-code f | -- t )
\end{Code}
If the flag is true, the operation was successful. If the flag is false,
it was unsuccessful and there's another value on the stack to indicate the
nature of the error.
You'll find stack manipulation easier, though, if you redesign the interface
to look like this:
\begin{Code}
( -- error-code | 0=no-error )
\end{Code}
One value serves both as a flag and (in case of an error) the error code.
Note that reverse-logic is used; non-zero indicates an error. You can use
any values for the error codes except zero.%
\index{E!Error-code|)}%
\index{D!Data stacks!drawings|)}
\section{The Stylish Return Stack}%
\index{D!Data stacks!return|(}
\index{R!Return stack|(}
What about this use of the return stack to hold temporary arguments? Is
it good style or what?
Some people take great offense to its use. But the return stack
offers the simplest solution to certain gnarly stack jams. Witness the
definition of \forthb{CMOVE>} in the previous section.
If you decide to use the return stack for this purpose, remember
that you are using a component of \Forth{} for a purpose other than that
intended. (See the section called ``Sharing Components,'' later in this
chapter.)
Here's some suggestions to keep you from shooting yourself in the
foot:
\begin{tip}
%!! there's certainly some better way to do ordered lists in TeX
\begin{enumerate}
\item Keep return stack operators symmetrical.
\item Keep return stack operators symmetrical under all control flow
conditions.
\item In factoring definitions, watch out that one part doesn't contain
one return stack operator, and the other its counterpart.
\item If used inside a \forthb{DO }\forthb{LOOP}, return stack operators
must be symmetrical within the loop, and \forthb{I} is no longer valid in
code bounded by \forthb{>R} and \forthb{R>}.
\end{enumerate}
\end{tip}
For every \forthb{>R} there must be a \forthb{R>} in the same definition.
Sometimes the operators will appear to be symmetrical, but due to the
control structure they aren't. For instance:
\begin{Code}
... BEGIN ... >r ... WHILE ... r> ... REPEAT
\end{Code}
If this construction is used in the outer loop of your application,
everything will run fine until you exit (perhaps hours later) when you'll
suddenly blow up. The problem? The last time through the loop, the
resolving \forthb{R>} has been skipped.%
\index{D!Data stacks!return|)}
\index{R!Return stack|)}
\section{The Problem With Variables}%
\index{V!Variables:!problem with|(}
Although we handle data of immediate interest on the stack, we depend
on much information tucked away in variables, ready for recurring access.
A piece of code can change the contents of a variable without
necessarily having to know anything about how that data will be used,
who will use it, or when and if it will be used. Another piece of code can
fetch the contents of a variable and use it without knowing where that
value came from.
For every word that pushes a value onto the stack, another word
must consume that value. The stack gives us point-to-point communication,
like the post office.
Variables, on the other hand, can be set by any command and accessed
any number of times---or not at all---by any command. Variables
are available for anyone who cares to look---like graffiti.
Thus variables can be used to reflect the current state of affairs.
Using currentness can simplify problems. In the Roman numeral example
of \Chap{4}, we used the variable \forth{COLUMN\#} to represent the
current decimal-place; the words \forth{ONER}, \forth{FIVER}, and
\forth{TENER} depended on this information to determine which type of
symbol to display. We didn't have to specify both descriptions every
time, as in \forth{TENS ONER}, \forth{TENS FIVER}, etc.
On the other hand, currentness adds a new level of complexity. To make
something current we must first define a variable or some type of data
structure. We also must remember to initialize it, if there's any chance
that part of our code will refer to it before another part has had a
chance to set it.
A more serious problem with variables is that they are not ``reentrant.''
On a multi-tasked \Forth{} system, each task which requires local
variables must have its own copies. \Forth{}'s \forthb{USER} variables
serve this purpose. (See \emph{Starting \Forth{}}, Chapter Nine,
``\Forth{} Geography.'')
Even within a single task, a definition that refers to a variable is
harder to test, verify, and reuse in a different situation than one in
which arguments are passed via the stack.
Suppose we are implementing a word-processor editor. We need a routine
that calculates the number of characters between the current cursor
position and the previous carriage-return/line-feed sequence. So we write
a word that employs a \forthb{DO }\forthb{LOOP} starting at the current
position (\forth{CURSOR @}) and ending at the zeroth position, searching
for the line feed character.
Once the loop has found the character sequence, we subtract its
relative address from our current cursor position
\begin{Code}
its-position cursor @ swap -
\end{Code}
to determine the distance between them.
Our word's stack effect is:
\begin{Code}
( -- distance-to-previous-cr/lf)
\end{Code}
But in later coding we find we need a similar word to compute the distance
from an arbitrary character---\emph{not} the current cursor position---to
the first previous line-feed character. We end up factoring out the
``\forth{CURSOR @}'' and allowing the starting address to be passed as an
argument on the stack, resulting in:
\begin{Code}
( starting-position -- distance-to-previous-cr/lf)
\end{Code}
By factoring-out the reference to the variable, we made the definition
more useful.
\begin{tip}
Unless it involves cluttering up the stack to the point of unreadability,
try to pass arguments via the stack rather than pulling them out of
variables.
\end{tip}
\begin{interview}
\index{K!Kogge, Peter|(}
\person{Kogge}:
\begin{tfquot}
Most of the modularity of \Forth{} comes from designing and treating
\Forth{} words as ``functions'' in the mathematical sense. In my
experience a \Forth{} programmer usually tries quite hard to avoid
defining any but the most essential global variables (I have a friend who
has the sign ``Help stamp out variables'' above his desk), and tries to
write words with what is called ``referential transparency,'' i.e., given
the same stack inputs a word will always give the same stack outputs
regardless of the more global context in which it is executed.
In fact this property is exactly what we use when we test words in
isolation. Words that do not have this property are significantly harder
to test. In a sense a ``named variable'' whose value changes frequently is
the next worst thing to the now ``forbidden'' GOTO.
\end{tfquot}
\index{K!Kogge, Peter|)}
\end{interview}
\wepsfigp{img7-211}{``Shot from a cannon on a fast-moving train,
hurtling between the blades of a windmill, and expecting to grab a
trapeze dangling from a hot-air balloon\dots{} I~told you Ace, there were
too many variables!''}
\noindent Earlier we suggested the use of local variables especially
during the design phase, to eliminate stack traffic. It's important to
note that in doing so, the variables were referred to only within the one
definition. In our example, \forth{[BOX]} receives four arguments from
the stack and immediately loads them into local variables for its own use.
The four variables are not referred to outside of this definition, and the
word behaves safely as a function.
Programmers unaccustomed to a language in which data can be passed
implicitly don't always utilize the stack as fully as they should.
\person{Michael Ham}\index{H!Ham, Michael}
suggests the reason may be that beginning \Forth{} users
don't trust the stack \cite{ham83}. He admits to initially feeling
safer about storing values into variables than leaving them on the
stack. ``No telling \emph{what} might happen with all that thrashing
about on the stack,'' he felt.
It took some time for him to appreciate that ``if words keep properly
to themselves, using the stack only for their expected input and output
and cleaning up after themselves, they can be looked upon as sealed
systems \dots{} I could put the count on the stack at the beginning of the
loop, go through the complete routine for each group, and at the end the
count would emerge, back on top of the stack, not a hair out of place.''%
\index{V!Variables:!problem with|)}
\section{Local and Global Variables/Initialization}%
\index{V!Variables:!local|(}%
\index{V!Variables:!global|(}%
\index{G!Global variables|(}%
\index{L!Local variables|(}%
As we saw earlier, a variable that is used exclusively within a single
definition (or single lexicon), hidden from other code, is called a local
variable. A variable used by more than one lexicon is called a global
variable. As we've seen in an earlier chapter, a set of global variables that
collectively describe a common interface between several lexicons is
called an ``interface lexicon.''
\index{I!Interface lexicon}
\Forth{} makes no distinction between local and global variables.
But \Forth{} programmers do.
\begin{interview}%
\index{M!Moore, Charles|(}
\person{Moore}:
\begin{tfquot}
We should be writing for the reader. If something is referred to only
locally, a temporary variable just for accumulating a sum in, we should
define it locally. It's handier to define it in the block where it's used,
where you can see its comment.
If it's used globally, we should collect things according to their logical
function, and define them together on a separate screen. One per line with
a comment.
The question is, where do you initialize them? Some say on the same line,
immediately following its definition. But that messes up the comments, and
there isn't room for any decent comment. And it scatters the
initialization all over the application.
I tend to do all my initialization in the load screen. After I've loaded
all my blocks, I initialize the things that have to be initialized. It
might also set up color lookup tables or execute some initialization code.
If your program is destined to be target compiled, then it's easy to write
a word at the point that encompasses all the initialization.
It can get much more elaborate. I've defined variables in ROM where the
variables were all off in an array in high memory, and the initial values are
in ROM, and I copy up the initial values at initialization time. But usually
you're only initializing a few variables to anything other than zero.
\end{tfquot}%
\index{M!Moore, Charles|)}
\end{interview}%
\index{V!Variables:!local|)}%
\index{V!Variables:!global|)}%
\index{G!Global variables|)}%
\index{L!Local variables|)}%
\section{Saving and Restoring a State}%
\index{V!Variables:!saving and restoring states|(}%
\index{D!Data stacks!saving and restoring states|(}
Variables have the characteristic that when you change their contents,
you clobber the value that was there before. Let's look at some of the
problems this can create, and some of the things we can do about them.
\index{B!BASE|(}%
\forthb{BASE} is a variable that indicates the current
number radix for all numeric input and output. The following words are
commonly found in \Forth{} systems:
\begin{Code}
: decimal ( -- ) 10 base ! ;
: hex ( -- ) 16 base ! ;
\end{Code}
Suppose we've written a word that displays a ``dump'' of memory.
Ordinarily, we work in decimal mode, but we want the dump in hexadecimal.
So we write:
\begin{Code}
: dump ( a # -- )
hex ... ( code for the dump) ... decimal ;
\end{Code}
This works---most of the time. But there's a presumption that we want to
come back to decimal mode. What if it had been working in hexadecimal, and
wants to come back to hexadecimal? Before we change the base to
\forthb{HEX}, we have to save its current value. When we're done dumping,
we restore it.
\index{R!Return stack|(}
This means we have to tuck away the saved value temporarily,
while we format the dump. The return stack is one place to do this:
\begin{Code}
: dump ( a # -- )
base @ >r hex ( code for dump) r> base ! ;
\end{Code}
If things get too messy, we may have to define a temporary variable:
\index{R!Return stack|)}
\begin{Code}
Variable old-base
: dump ( a # -- )
base @ old-base ! hex ( code for dump )
old-base @ base ! ;
\end{Code}
How quickly things get complicated.%
\index{B!BASE|)}
In this situation, if both the current and the old version of a variable
belong only to your application (and not part of your system), and if this
same situation comes up more than once, apply a technique of factoring:
\begin{Code}
: bury ( a -- ) dup cell+ 1 cells move ;
: exhume ( a -- ) dup cell+ swap 1 cells move ;
\end{Code}
Then instead of defining two variables, such as \forth{CONDITION} and
\forth{OLD-CONDITION}, define one double-length variable:
\begin{Code}
2Variable condition
\end{Code}
Use \forth{BURY} and \forth{EXHUME} to save and restore the original value:
\begin{Code}
: diddle condition bury 17 condition ! ( diddle )
condition exhume ;
\end{Code}
\forth{BURY} saves the ``old'' version of condition at \forth{CONDITION CELL+}.
You still have to be careful. Going back to our \forthb{DUMP} example,
suppose you decided to add the friendly feature of letting the user exit
the dump at any time by pressing the ``escape'' key. So inside the loop
you build the test for a key being pressed, and if so execute
\forthb{QUIT}. But what happens?
The user starts in decimal, then types \forthb{DUMP}. He exits
\forthb{DUMP} midway through and finds himself, strangely, in hexadecimal.
In the simple case at hand, the best solution is to not use
\forthb{QUIT}, but rather a controlled exit from the loop (via
\forthb{LEAVE}, etc.) to the end of the definition where
\forthb{BASE} is reset.
In very complex applications a controlled exit is often impractical,
yet many variables must somehow be restored to a natural condition.
\begin{interview}%
\index{M!Moore, Charles|(}
\person{Moore} responds to this example:
\begin{tfquot}
You really get tied up in a knot. You're creating problems for
yourself. If I want a hex dump I say \forthb{HEX }\forthb{DUMP}. If I
want a decimal dump I say \forthb{DECIMAL }\forthb{DUMP}. I don't give
\forthb{DUMP} the privilege of messing around with my environment.
There's a philosophical choice between restoring a situation when you
finish and establishing the situation when you start. For a long time I felt
you should restore the situation when you're finished. And I would try to
do that consistently everywhere. But it's hard to define ``everywhere.'' So
now I tend to establish the state before I start.
If I have a word which cares where things are, it had better set them. If
somebody else changes them, they don't have to worry about resetting
them.
There are more exits than there are entrances.
\end{tfquot}\index{M!Moore, Charles|)}
\end{interview}
In cases in which I need to do the resetting before I'm done, I've found it
useful to have a single word (which I call \forth{PRISTINE}) to perform this
resetting. I invoke \forth{PRISTINE}:
%!! '*'s should be bullets
\begin{itemize}
\item at the normal exit point of the application
\item at the point where the user may deliberately exit (just before
\forthb{QUIT})
\item at any point where a fatal error may occur, causing an abort.
\end{itemize}
Finally, when you encounter this situation of having to save/restore a
value, make sure it's not just a case of bad factoring. For example,
suppose we have written:
\begin{Code}
: long ( -- ) 18 #holes ! ;
: short ( -- ) 9 #holes ! ;
: game ( -- ) #holes @ 0 DO i hole play LOOP ;
\end{Code}
The current \forth{GAME} is either \forth{LONG} or \forth{SHORT}.
Later we decide we need a word to play \emph{any} number of holes. So
we invoke \forth{GAME} making sure not to clobber the current value of
\forth{\#HOLES}:
\begin{Code}
: holes ( n -- ) #holes @ swap #holes ! game #holes ! ;
\end{Code}
Because we needed \forth{HOLES} after we'd defined \forth{GAME}, it
seemed to be of greater complexity; we built \forth{HOLES} around
\forth{GAME}. But in fact---perhaps you see it already---rethinking is
in order:
\begin{Code}
: holes ( n -- ) 0 DO i hole play LOOP ;
: game ( -- ) #holes @ holes ;
\end{Code}
We can build \forth{GAME} around \forth{HOLES} and avoid all this
saving/restoring nonsense.%
\index{V!Variables:!saving and restoring states|)}%
\index{D!Data stacks!saving and restoring states|)}
\section{Application Stacks}
In the last section we examined some ways to save and restore a single
previous value. Some applications require \emph{several} values to be
saved and restored. You may often find the best solution to this problem
in defining your own stack.
Here is the code for a user stack including very simple error checking
(an error clears the stack):
\begin{Code}
Create stack 6 cells allot
\ { tos-pointer | stack [5 cells] }
here Constant stack>
: init-stack ( -- ) stack stack ! ; init-stack
: ?bad ( ? -- )
IF ." stack error " init-stack abort THEN ;
: push ( n -- )
cell stack +! stack @ dup stack> = ?bad ! ;
: pop ( -- n )
stack @ @ cell negate stack +! stack @ stack < ?bad ;
\end{Code}
The word \forth{PUSH} takes a value from off of your data stack and
``pushes'' it onto this new stack. \forth{POP} is the opposite,
``popping'' a value from off the new stack, and onto \Forth{}'s data
stack.
In a real application you might want to change the names \forth{PUSH}
and \forth{POP} to better match their conceptual purposes.
\section{Sharing Components}%
\index{C!Components:!sharing|(}%
\index{S!Sharing components|(}
\begin{tip}
It's legal to use a component for an additional purpose besides its
intended one, provided:
\medskip
\begin{enumerate}
\item All uses of the component are mutually exclusive
\item Each interrupting use of the component restores the component to
its previous state when finished.
\end{enumerate}
\medskip\noindent
Otherwise you need an additional component or level of complexity.
\end{tip}%
\index{D!Data stacks!return|(}
We've seen a simple example of this principle with the return stack. The
return stack is a component of the \Forth{} system designed to hold return
addresses, and thereby serve as an indication of where you've been and
where you're going. To use the return stack as a holder for temporary
values is possible, and in many cases desirable. Problems occur when one
of the above restrictions is ignored.%
\index{D!Data stacks!return|)}
In my text formatter the output can go invisible. This feature has
two purposes:
\begin{enumerate}
\item for looking ahead to see whether something will fit, and
\item for formatting the table of contents (the entire document is
formatted and page numbers are calculated without anything actually being
displayed).
\end{enumerate}
It was tempting to think that once having added the ability to make
the output invisible, I could use this feature to serve both purposes.
Unfortunately, the two purposes are not mutually exclusive.
Let's see what would happen if I tried to violate this rule. Imagine
that the word \forth{DISPLAY} does the output, and it's smart enough
to know whether to be visible or invisible. The words \forth{VISIBLE}
and \forth{INVISIBLE} set the state respectively.
My code for looking ahead will first execute \forth{INVISIBLE,} then
test-format the upcoming text to determine its length, and finally
execute \forth{VISIBLE} to restore things to the normal state.
This works fine.
Later I add the table-of-contents feature. First the code executes
\forth{IN\-VI\-SI\-BLE}, then runs through the document determining page
numbers etc.; then finally executes \forth{VISIBLE} to restore things
to normal.
The catch? Suppose I'm running a table of contents and I hit one of
those places where I look ahead. When I finish looking ahead, I
execute \forth{VISIBLE}. Suddenly I start printing the document when I
was supposed to be running the table of contents.
The solution? There are several.
One solution views the problem as being that the lookahead code is
clobbering the visible/invisible flag, which may have been preset by
table-of-contents. Therefore, the lookahead code should be responsible for
saving, and later restoring, the flag.
Another solution involves keeping two separate variables---one to
indicate we're looking ahead, the other to indicate we're printing the
table of contents. The word \forth{DISPLAY} requires that both flags
be false in order to actually display anything.
There are two ways to accomplish the latter approach, depending on
how you want to decompose the problem. First, we could nest one condition
within the other:
\begin{Code}
: [display] ...
( the original definition, always does the output) ... ;
Variable 'lookahead? ( t=looking-ahead)
: <display> ( -- ) 'lookahead? @ 0= IF [display] THEN ;
Variable 'toc? ( t=setting-table-of-contents)
: display ( -- ) 'toc? @ 0= IF <display> THEN ;
\end{Code}
{\sloppy
\forth{DISPLAY} checks that we're not setting the table of contents
and invokes \forth{<DISPLAY>}, which in turn checks that we're not
looking ahead and invokes \forth{[DISPLAY]}.
}
In the development cycle, the word \forth{[DISPLAY]} that always does
the output was originally called \forth{DISPLAY}. Then a new
\forth{DISPLAY} was defined to include the lookahead check, and the
original definition was renamed \forth{[DISPLAY]}, thus adding a level
of complexity backward without changing any of the code that used
\forth{DISPLAY}.