-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWI.PAS
2444 lines (2201 loc) · 64.6 KB
/
WI.PAS
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
program WI;
{
WHILE Interpreter (C) Copyright 1998, by Mike Wiering
Programmed in Borland/Turbo Pascal 7.0
Syntax:
wi filename[.whl] [datafile[.dat]] [Options]
Options:
-b Boolean values in output
-c Convert program to WHILE-data
-f Formal notation of lists
-h Highlight variable names in the variable list
-l Long string output (to stdout)
-o Overwrite existing files without asking
-q Quiet mode, only display output values or errors messages
-t Start in trace mode
-v List all variables after the WHILE program has ended
}
{
History:
Version 0.10:
9 Feb 1998 - started project, implemented data structures, parser,
expressions, assignment, read, write, hd, tl and cons
10 Feb 1998 - added while
12 Feb 1998 - added case, =?, atom=?
13 Feb 1998 - added error messages etc, mem checking
14 Feb 1998 - changed parser (indent/()), nested while bug fixed,
added tracing option (-t)
Version 0.20:
15 Feb 1998 - added multiple files, fixed error position
16 Feb 1998 - implemented easy notation read/write, added -f option
(write lists in formal notation)
Version 0.30:
24 Apr 1998 - added data input from file (2nd parameter)
12 May 1998 - added quote
13 May 1998 - added parameter -v: show all variables at end
14 May 1998 - memory of Source[] is disposed
Version 0.40:
15 May 1998 - added ^C checking, -h option: highlight variable
names
17 May 1998 - added numbers: (3) -> (nil nil nil)
24 May 1998 - added -c (Convert WHILE to DATA) and -o (Overwrite)
25 May 1998 - added break
26 May 1998 - added -q (quiet mode), watch vars (tab)
Version 0.50:
3 Jun 1998 - added more comments
4 Jun 1998 - fixed LStr Protected Mode memory bug
5 Jun 1998 - added more comments
6 Jun 1998 - added long string output (-l), added more comments
7 Jun 1998 - convert if/then/else, added standard comments etc
8 Jun 1998 - added -b (Boolean output) flag
}
{$DEFINE GARBAGE} { show garbage memory }
{ $DEFINE DEBUG}
{$M 65000,0,655360} { large stack }
{$I-} { no I/O checking, return errors in IOResult }
{$X+} { extended syntax }
{$IFDEF DEBUG}
{$R+} { range checking }
{$ELSE}
{$R-}
{$ENDIF}
uses
Dos,
Crt;
{ global constants and types }
const
{ total of all source lines (input file + files loaded at runtime) }
MAX_LINES = $1000;
MAX_LINE_LENGTH = 128;
const
{ tab size is important for compound statements (in while/case) }
DEFAULT_TAB_SIZE = 8;
const
{ program name, version }
PROGRAM_NAME = 'wi';
PROGRAM_VERSION = '0.50';
const
{ default extensions }
DEFAULT_EXTENSION = '.whl';
DEFAULT_DATA_EXTENSION = '.dat';
const
{ used to allocate memory for variables }
MAX_VARIABLES = 256;
MAX_IDENTIFIER_SIZE = 64;
const
{ external functions run at a higher level, input file is level 0 }
MAX_LEVELS = 16;
type
{ record to save cursor position in the source code }
PosRec =
record
Line: LongInt;
Pos: Integer;
end;
type
{ record for a source file at a certain level }
FileRec =
record
Filename: PathStr;
SourceBase, { position in Source[] where file starts }
TotalLines: LongInt; { number of lines in Source[] }
VarBase: Integer; { variables at this level }
Cursor, { current position }
LastPos: PosRec; { position of last-parsed keyword or char }
end;
type
{ pointers to source lines in array Source^[] }
SourceLinePtr = ^SourceLine;
SourceLine = string[MAX_LINE_LENGTH];
SourceLinePtrArrayPtr = ^SourceLinePtrArray;
SourceLinePtrArray = array[0..MAX_LINES - 1] of SourceLinePtr;
type
{ used to store values of atoms, max length is 255 }
StrPtr = ^string;
type
{ basic structure of WHILE data }
TreePtr = ^Tree;
Tree =
record
case Atom: Boolean of
TRUE: (Value: StrPtr);
FALSE: (Head, Tail: TreePtr);
end;
{ LongStr type implementation for long strings }
const
{ maximum line length of LongStr }
LS_LINE_SIZE = $FF00;
type
{ the LongStr type }
LongStrPtr = ^LongStr;
LongStr = array[0..LS_LINE_SIZE - 1] of Byte;
{ global variables }
var
{ lspStart contains read statement, lspEnd the write (-c option only) }
lspStart,
lspEnd: LongStrPtr;
var
{ the current level: 0 = input file, 1 is function called, etc. }
CurLevel: Integer;
var
{ source lines of WHILE-program (runtime function source is appended) }
Source: SourceLinePtrArrayPtr;
{ file information for each level }
Files: array[0..MAX_LEVELS - 1] of FileRec;
{ variable names and values }
VarNames: array[0..MAX_VARIABLES - 1] of string[MAX_IDENTIFIER_SIZE];
Values: array[0..MAX_VARIABLES - 1] of TreePtr;
var
{ command line option flags }
Tracing,
Formal,
FinalShow,
BoldVars,
LStrOut,
Overwrite,
Convert,
Quiet,
Bools: Boolean;
var
{ watch variables change at run-time when Monitor = TRUE }
Monitor: Boolean;
var
{ when tracing, show each line only once }
LastTraced: LongInt;
var
{ the current tab-size, always set to DEFAULT_TAB_SIZE }
TabSize: Integer;
var
{ name of (input or output) data file }
WhileData: string;
{$IFDEF GARBAGE}
var
{ calculate memory usage }
LeastMem: LongInt;
{$ENDIF}
{ general functions }
function UpCaseStr (s: string): string;
{ returns s in upper-case }
var
i: Integer;
begin { UpCaseStr }
for i := 1 to Length (s) do
s[i] := UpCase (s[i]);
UpCaseStr := s;
end; { UpCaseStr }
function Exist (f: string): Boolean;
{ returns TRUE if file f exists, else FALSE }
var
SR: SearchRec;
begin { Exist }
FindFirst (f, ANYFILE, SR);
Exist := DOSError = 0;
end; { Exist }
procedure AddExt (var s: string; Ext: string);
{ add an extension to a filename (only if the name has no extension) }
begin { AddExt }
if Pos ('.', s) = 0 then
if s = UpCaseStr (s) then
s := s + UpCaseStr (Ext)
else
s := s + Ext;
end; { AddExt }
procedure DelSpaces (var s: string);
{ remove leading spaces, tabs and CR/LF from s }
var
i, j: Integer;
begin { DelSpaces }
j := SizeOf (s) - 1;
while (s[1] in [' ', #9, #13, #10]) and (s <> '') do
begin
Delete (s, 1, 1); { delete first character }
for i := Length (s) + 1 to j do { clear remainder of string }
s[i] := #0;
j := Length (s); { save last end position }
end;
end; { DelSpaces }
function GetKey: string;
{ wait for keystroke }
var
c: Char;
begin { GetKey: }
c := ReadKey;
if c = #0 then { extended character }
GetKey := c + ReadKey
else
GetKey := c;
end; { GetKey: }
procedure ShowInfo;
{ show copyright message }
begin { ShowInfo }
WriteLn ('WHILE Interpreter, version ' + PROGRAM_VERSION +
', (C) copyright 1998, by Mike Wiering, Nijmegen.');
end; { ShowInfo }
procedure Abort (Msg: string);
{ show error message and quit }
begin { Abort }
WriteLn (Msg);
Halt;
end; { Abort }
procedure ShowSyntax;
{ show usage information }
begin { ShowSyntax }
ShowInfo;
WriteLn;
WriteLn ('Syntax: ', PROGRAM_NAME, ' filename[' +
DEFAULT_EXTENSION + '] [datafile[' +
DEFAULT_DATA_EXTENSION + ']] [Options]');
WriteLn;
WriteLn ('Options:');
WriteLn (' -b Boolean values in output.');
WriteLn (' -c Convert program to WHILE-data.');
WriteLn (' -f Use formal list-notation.');
WriteLn (' -h Highlight names when listing variables.');
WriteLn (' -l Long string output to stdout.');
WriteLn (' -o Overwrite existing files without asking.');
WriteLn (' -t Trace source code (press key to continue).');
WriteLn (' -v Show all variables after final output.');
WriteLn (' -q Quiet mode (only display output).');
Halt;
end; { ShowSyntax }
procedure CheckMem (Size: LongInt);
{ check available memory, abort program if not enough }
var
M: LongInt;
begin { CheckMem }
Size := (Size or $000F) + 1; { memory is used per 16 bytes }
M := MaxAvail - Size;
{$IFDEF GARBAGE}
if M < LeastMem then
LeastMem := M;
{$ENDIF}
if M < $10 then
Abort ('Out of memory.');
end; { CheckMem }
{
Long string (LongStr) functions
A long string is an array of bytes (up to LS_LINE_SIZE bytes), the
first two bytes contain the length of the string. Every time the string
is modified, memory is reallocated.
}
procedure LStrSetLen (var lsp: LongStrPtr; Length: LongInt);
{ set length, length is stored at the beginning of the string (2 bytes) }
begin { LStrSetLen }
lsp^[0] := Length mod $100;
lsp^[1] := Length div $100;
end; { LStrSetLen }
function LStrGetLen (var lsp: LongStrPtr): LongInt;
{ get current string length }
begin { LStrGetLen }
LStrGetLen := LongInt (LongInt (lsp^[1] * 256) + lsp^[0]);
end; { LStrGetLen }
procedure LStrInit (var lsp: LongStrPtr);
{ initialize new string }
begin { LStrInit }
CheckMem (2);
GetMem (lsp, 2);
LStrSetLen (lsp, 0);
end; { LStrInit }
procedure WriteLongStr (lsp: LongStrPtr);
{ write the contense of LongStr lsp^ to stdout }
var
i: Integer;
T: Text;
begin { WriteLongStr }
Assign (T, '');
ReWrite (T);
for i := 0 to LStrGetLen (lsp) - 1 do
Write (T, Chr (lsp^[i + 2]));
Close (T);
end; { WriteLongStr }
procedure LStrChangeMem (var lsp: LongStrPtr; NewSize: LongInt);
{ change the size of a string, allocate more memory }
var
Len, i: LongInt;
lsp2: LongStrPtr;
begin { LStrChangeMem }
if NewSize >= LS_LINE_SIZE then
Abort ('String size exceeds LS_LINE_SIZE');
Len := LStrGetLen (lsp) + 2;
{ allocate a new string }
CheckMem (NewSize);
GetMem (lsp2, NewSize);
if NewSize < Len then
Len := NewSize;
{ copy lsp to the new string }
for i := 0 to Len - 1 do
lsp2^[i] := lsp^[i];
{ FreeMem (lsp, Len); } { dangerous! }
lsp := lsp2;
end; { LStrChangeMem }
procedure LStrAddStr (var lsp: LongStrPtr; s: string);
{ append string s to LongStr lsp^ }
var
Len, i: LongInt;
begin { LStrAddStr }
if s = '' then
Exit;
Len := LStrGetLen (lsp) + 2;
LStrChangeMem (lsp, Len + Length (s));
for i := 0 to Length (s) - 1 do
lsp^[i + Len] := Ord (s[i + 1]);
LStrSetLen (lsp, Len - 2 + Length (s));
end; { LStrAddStr }
procedure LStrAddLStr (var lsp: LongStrPtr; lsp2: LongStrPtr);
{ append LongStr lsp2^ to LongStr lsp^ }
var
Len, Len2, i: LongInt;
begin { LStrAddLStr }
if lsp2 = nil then
Exit;
Len := LStrGetLen (lsp) + 2;
Len2 := LStrGetLen (lsp2);
if Len2 = 0 then
Exit;
LStrChangeMem (lsp, Len + Len2);
for i := 0 to Len2 - 1 do
lsp^[i + Len] := lsp2^[i + 2];
LStrSetLen (lsp, Len - 2 + Len2);
end; { LStrAddLStr }
procedure LStrInsertStr (var lsp: LongStrPtr; s: string; Pos: LongInt);
{ insert string s into LongStr lsp^ at position Pos }
var
Len, i: LongInt;
begin { LStrInsertStr }
if s = '' then
Exit;
Len := LStrGetLen (lsp) + 2;
LStrChangeMem (lsp, Len + Length (s));
for i := Len - 1 downto Pos do
lsp^[i + Length (s)] := lsp^[i];
for i := Length (s) - 1 downto 0 do
lsp^[2 + Pos - 1 + i] := Ord (s[i + 1]);
LStrSetLen (lsp, Len - 2 + Length (s));
end; { LStrInsertStr }
procedure LStrInsertLStr (var lsp: LongStrPtr; lsp2: LongStrPtr;
Pos: LongInt);
{ insert LongStr lsp2^ into LongStr lsp^ at position Pos }
var
Len, Len2, i: LongInt;
begin { LStrInsertLStr }
if lsp2 = nil then
Exit;
Len := LStrGetLen (lsp) + 2;
Len2 := LStrGetLen (lsp2);
if Len2 = 0 then
Exit;
LStrChangeMem (lsp, Len + Len2);
for i := Len - 1 downto Pos do
lsp^[i + Len2] := lsp^[i];
for i := Len2 - 1 downto 0 do
lsp^[2 + Pos - 1 + i] := lsp2^[i + 2];
LStrSetLen (lsp, Len - 2 + Len2);
end; { LStrInsertLStr }
procedure ReadOption (Option: string);
{ read one command line option and set flags }
var
s: string;
begin { ReadOption }
s := UpCaseStr (Option);
Delete (s, 1, 1); { delete the '-' or '/' }
if s = 'T' then
Tracing := TRUE
else
if s = 'F' then
Formal := TRUE
else
if s = 'V' then
FinalShow := TRUE
else
if s = 'H' then
BoldVars := TRUE
else
if s = 'L' then
LStrOut := TRUE
else
if s = 'O' then
Overwrite := TRUE
else
if s = 'C' then
Convert := TRUE
else
if s = 'Q' then
Quiet := TRUE
else
if s = 'B' then
Bools := TRUE
else
WriteLn ('Invalid option: ', Option);
end; { ReadOption }
function ReadCmdLine (var Filename: string; var WhileData: string):
Boolean;
{ read input, data file and flags from the command line }
var
i: Integer;
s: string;
Error: Boolean;
begin { ReadCmdLine }
Filename := '';
WhileData := '';
{ initialize flags }
Tracing := FALSE;
Formal := FALSE;
FinalShow := FALSE;
BoldVars := FALSE;
LStrOut := FALSE;
Overwrite := FALSE;
Convert := FALSE;
Quiet := FALSE;
Bools := FALSE;
Monitor := FALSE;
Error := FALSE;
for i := 1 to ParamCount do
begin
s := ParamStr (i);
if s[1] in ['-', '/'] then
ReadOption (s)
else
if Filename = '' then
Filename := s
else
if WhileData = '' then
WhileData := s
else
Error := TRUE; { too many parameters }
end; { for }
ReadCmdLine := (Filename <> '') and (not Error);
end; { ReadCmdLine }
function ReadFile (Filename: string; Level: Integer): Boolean;
{ read WHILE-source file into Source[], returns TRUE if all ok }
var
F: Text;
Line: SourceLine;
i, j,
Len: Integer;
s: string;
VBase: Integer;
Base: LongInt;
p: pointer;
begin { ReadFile }
{ initialize parameters in Files[] for new level Level }
Files[Level].Filename := Filename;
if Level = 0 then { main input file }
begin
Base := 0; { source line base }
VBase := 0; { variable base }
end
else
begin { function loaded from disk at run-time }
with Files[Level - 1] do
Base := SourceBase + TotalLines;
{ set a new base for variables so parent's vars are not harmed }
i := MAX_VARIABLES;
while (i > 0) and (VarNames[i - 1] = '') do
Dec (i);
VBase := i;
end; { else }
{ open the input file }
ReadFile := FALSE;
Assign (F, Filename);
Reset (F);
if IOResult <> 0 then
Exit;
with Files[Level] do
begin
Cursor.Line := 0;
Cursor.Pos := 1;
LastPos := Cursor;
SourceBase := Base;
VarBase := VBase;
TotalLines := 0;
repeat
ReadLn (F, Line);
{ detab string, convert tabs to spaces }
s := '';
for i := 1 to Length (Line) do
if Line[i] = #9 then { tab character }
begin
j := Length (s);
repeat
s := s + ' ';
Inc (j);
until j mod TabSize = 0;
end
else
s := s + Line[i];
Line := s; { ** no line length checking ** }
if Line = '' then { lines must have at least one character }
Line := ' ';
Len := Length (Line);
CheckMem (Len + 1);
GetMem (Source^[SourceBase + TotalLines], Len + 1);
{ store new line in Source[] }
Source^[SourceBase + TotalLines]^ := Line;
Inc (TotalLines);
until Eof (F) or (IOResult <> 0) or
(SourceBase + TotalLines > MAX_LINES - 1);
end; { with }
Close (F);
ReadFile := TRUE;
end; { ReadFile }
function GetSourceLine (Line: LongInt): string;
{ returns a source line from the WHILE program stored in Source[] }
begin { GetSourceLine }
with Files[CurLevel] do
if Line >= TotalLines then
GetSourceLine := ''
else
GetSourceLine := Source^[SourceBase + Line]^;
end; { GetSourceLine }
procedure Error (Msg: string; Position: PosRec);
{ show exact error position in source }
begin { Error }
with Position do
begin
WriteLn ('Error in line ', Line + 1, ': ', Msg);
WriteLn (GetSourceLine (Line));
WriteLn ('^': Pos);
end;
Halt;
end; { Error }
procedure SavePos (var Buf: PosRec; var Last: PosRec);
{ save the current Cursor/LastPos position in Buf and Last }
begin { SavePos }
with Files[CurLevel] do
begin
Buf := Cursor;
Last := LastPos;
end;
end; { SavePos }
procedure RestorePos (Buf, Last: PosRec);
{ restore a saved position }
begin { RestorePos }
with Files[CurLevel] do
begin
LastPos := Last;
Cursor := Buf;
end;
end; { RestorePos }
{ parse functions }
function GetC: Char;
{ get next char from file and move Cursor }
var
C: Char;
begin { GetC: }
with Files[CurLevel] do
with Cursor do
begin
if (Line >= TotalLines) then
C := #0 { indicate end of file }
else
if Pos > Length (Source^[SourceBase + Line]^) then
begin
C := #13; { new line }
Inc (Line);
Pos := 1;
end
else
begin
{ return next character }
C := Source^[SourceBase + Line]^[Pos];
if C in [#0] then
C := ' '; { in case the file contains a #0 char }
Inc (Pos);
end; { else }
end; { with }
GetC := C;
end; { GetC: }
function LookAheadChar: Char;
{ get next char without moving cursor }
var
Buf, Last: PosRec;
begin { LookAheadChar: }
SavePos (Buf, Last);
LookAheadChar := GetC;
RestorePos (Buf, Last);
end; { LookAheadChar: }
procedure CheckEnd (c: Char);
{ halt program if end-of-file found }
begin { CheckEnd }
if c = #0 then
Error ('Unexpected end of file.', Files[CurLevel].Cursor);
end; { CheckEnd }
function GetToken (MoveCursor: Boolean): string;
{ get next symbol or word, skip comments }
var
s: string;
c: Char;
Buf, Last: PosRec;
Comment: Boolean;
begin { GetToken }
if not MoveCursor then
SavePos (Buf, Last);
s := '';
repeat
Comment := FALSE;
c := GetC;
if (c = '(') and (LookAheadChar = '*') then { comment start }
begin
Comment := TRUE;
c := GetC; { skip '*' }
repeat
c := GetC;
CheckEnd (c); { halts if end of file }
until (c = '*') and (LookAheadChar = ')'); { comment end }
c := GetC; { skip ')' }
end;
until (not (c in [#13, #10, ' '])) and (not Comment);
with Files[CurLevel] do { save start position of token in LastPos }
begin
LastPos := Cursor;
Dec (LastPos.Pos);
end;
if c in ['0'..'9'] then { number }
begin
while LookAheadChar in ['0'..'9'] do
begin
s := s + c;
c := GetC;
end;
s := s + c;
end
else
if UpCase (c) in ['A'..'Z', '_'] then { (key)word/identifier }
begin
while (UpCase (LookAheadChar) in ['A'..'Z', '_', '0'..'9']) do
begin
s := s + c;
c := GetC;
end;
s := s + c;
end
else
s := c; { symbol }
if not MoveCursor then
RestorePos (Buf, Last);
GetToken := s;
end; { GetToken }
function CheckToken (Token: string): Boolean;
{ checks for Token and returns TRUE if found (and moves cursor) }
var
Buf, Last: PosRec;
s: string;
begin { CheckToken }
SavePos (Buf, Last);
s := '';
{ Token may be a combination of characters }
repeat
s := s + GetToken (TRUE);
until Length (s) >= Length (Token);
if s = Token then
CheckToken := TRUE
else
begin
RestorePos (Buf, Last); { resture old position }
CheckToken := FALSE;
end; { else }
end; { CheckToken }
procedure Expect (Token: string);
{ halts if Token is not found at the current position }
var
s: string;
begin { Expect }
with Files[CurLevel] do
if not CheckToken (Token) then
begin
s := GetToken (TRUE);
Error (#39 + Token + #39' expected.', LastPos);
end;
end; { Expect }
{ tree functions }
procedure ClearNode (Tree: TreePtr);
{ clear a node, Tree must be initialized }
begin { ClearNode }
with Tree^ do
begin
Atom := FALSE;
Value := nil;
Head := nil;
Tail := nil;
end;
end; { ClearNode }
function Cons (Hd, Tl: TreePtr): TreePtr;
{ returns cons Hd Tl }
var
Root: TreePtr;
begin { Cons }
{ only one new node is created with pointers to Hd and Tl }
CheckMem (SizeOf (Tree));
GetMem (Root, SizeOf (Tree));
ClearNode (Root);
Root^.Head := Hd;
Root^.Tail := Tl;
Cons := Root;
end; { Cons }
function ReadFileData (var s: string; var F: Text): TreePtr;
{ recursive function to read WHILE data from text file F }
var
Root, Cur: TreePtr;
Atom: string;
L: Integer;
c: Char;
procedure RunNumbers (var s: string);
{ convert numbers to sequences of NILs (used for variable numbers),
3 => NIL NIL NIL }
var
t: string;
i: Integer;
L: LongInt;
begin { RunNumbers }
{ because large numbers are allowed, only add one NIL at a time }
t := '';
while (s <> '') and (s[1] in ['0'..'9']) do { get number in t }
begin
t := t + s[1];
Delete (s, 1, 1);
end;
if t <> '' then { number found }
begin
Val (t, L, i);
if i <> 0 then { not a valid number, don't convert }
s := t + s
else
begin
{ valid number, string s becomes NIL+(L-1)+... }
Dec (L);
if L > 0 then { not the last NIL? }
begin
Str (L, t);
s := t + s;
end;
s := 'nil ' + s;
end; { else }
end; { if }
end; { RunNumbers }
begin { ReadFileData }
{ string s is used as FIFO buffer between file F and tree }
if not Eof (F) then
{ append more data from file F to s }
while (Length (s) < SizeOf (s) div 2) and (not Eof (F)) do
begin
Read (F, c);
if not (c in [#10, #13]) then { remove CR/LF }
s := s + c;
end;
{ check for numbers, replace with NILs }
RunNumbers (s);
{ s starts with 'nil', return NIL }
if (Copy (s, 1, 3) = 'nil') and
((Length (s) = 3) or (not (UpCase (s[4]) in ['A'..'Z']))) then
begin
ReadFileData := nil;
Delete (s, 1, 3);
Exit;
end;
{ initialize new tree in Root }
CheckMem (SizeOf (Tree));
GetMem (Root, SizeOf (Tree));
ClearNode (Root);
if s[1] = '(' then
begin
Root^.Atom := FALSE;
Delete (s, 1, 1); { '(' }
DelSpaces (s);
{ '()' is the same as NIL, can be used for numbers ()()() = 3 }
if s[1] = ')' then
begin
FreeMem (Root, SizeOf (Tree));
Root := nil;
Delete (s, 1, 1);
end
else
begin
Root^.Head := ReadFileData (s, F); { read Head }
DelSpaces (s);
if s[1] = '.' then { expression (X.Y) }
begin
Delete (s, 1, 1); { '.' }
DelSpaces (s);
Root^.Tail := ReadFileData (s, F); { read Tail }
DelSpaces (s);
if s[1] <> ')' then
Abort ('Syntax error, '')'' expected.');
Delete (s, 1, 1); { ')' }
end
else { expression (X Y Z ...) }
begin
DelSpaces (s);
Cur := Root;
while (s <> '') and (s[1] <> ')') do { read a list }
begin
Cur^.Tail := Cons (ReadFileData (s, F), nil);
Cur := Cur^.Tail;
DelSpaces (s);
end;
if (s = '') or (s[1] <> ')') then
Abort ('Syntax error, '')'' expected.');
Delete (s, 1, 1); { ')' }
end; { else }
end; { else }
end { if }
else { expression is an atom }
begin
DelSpaces (s);
{ read the atom }
Atom := '';
while (s <> '') and (not (s[1] in [' ', '.', ')'])) do
begin
Atom := Atom + s[1];
Delete (s, 1, 1);
end;
{ store the atom in Root }
L := Length (Atom) + 1;
CheckMem (L);
GetMem (Root^.Value, L);
Root^.Value^ := Atom;
Root^.Atom := TRUE;
end; { else }
ReadFileData := Root;
end; { ReadFileData }
function ReadTree (var s: string): TreePtr;
{ read a tree from string s, used for input from keyboard }
var
Root, Cur: TreePtr;
Atom: string;
L: Integer;
begin { ReadTree }
{ s starts with 'nil', return NIL }
if (Copy (s, 1, 3) = 'nil') and
((Length (s) = 3) or (not (UpCase (s[4]) in ['A'..'Z']))) then
begin
ReadTree := nil;
Delete (s, 1, 3);
Exit;
end;
{ initialize new tree in Root }
CheckMem (SizeOf (Tree));
GetMem (Root, SizeOf (Tree));
ClearNode (Root);
if s[1] = '(' then
begin
Root^.Atom := FALSE;