raz / commit 626e09b7

commit
626e09b72c72caebcfea0bacc302249c43ae2137
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
65f71297
Step 2: scanner and symbol table

scan.pas reads UTF-8 source, checks it, interns identifiers and hands
out symbols; errors give the line and the column in characters.
sym.pas holds types, objects and scopes, found through one hash table
keyed by scope and name, and the universe. test/scantest.pas prints
the symbols of a file.

patch · log

5 files changed, +1044 -0

.gitignore (history) added +2 -0

@@ -0,0 +1,2 @@
1+build/
2+/jed

Makefile (history) added +20 -0

@@ -0,0 +1,20 @@
1+# Builds the compiler, jed, from src/ into the repository's root; the
2+# library it needs is lib/, beside it.
3+
4+FPC = fpc
5+FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild
6+
7+jed: src/*.pas | build
8+ $(FPC) $(FPCFLAGS) -ojed src/jed.pas
9+
10+units: src/*.pas | build
11+ $(FPC) $(FPCFLAGS) src/scan.pas
12+ $(FPC) $(FPCFLAGS) src/sym.pas
13+
14+build:
15+ mkdir -p build
16+
17+clean:
18+ rm -rf build jed
19+
20+.PHONY: units clean

src/scan.pas added +548 -0

@@ -0,0 +1,548 @@
1+{ scan.pas: the scanner.
2+
3+ Reads a jed source file and hands the parser one symbol at a time:
4+ reserved words, identifiers, numbers, characters, strings and
5+ operators. Identifiers are interned, so that the rest of the compiler
6+ compares names as small integers. The scanner also reports errors,
7+ since it knows where in the file the compiler is.
8+
9+ Depends on: BaseUnix, to read files.
10+ Leaves out: recovery from errors. The first error stops the compiler. }
11+
12+unit scan;
13+
14+{$mode objfpc}{$H-}
15+
16+interface
17+
18+type
19+ TSym = (sNull, sIdent, sInt, sReal, sChar, sString,
20+ sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
21+ sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,
22+ sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sBar,
23+ { the reserved words, in the order of Words below }
24+ sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse,
25+ sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink,
26+ sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord,
27+ sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sType, sUntil, sVar,
28+ sVariant, sVolatile, sWhile, sXor,
29+ sEof);
30+
31+ PBytes = ^TBytes;
32+ TBytes = array[0..MaxInt - 1] of byte;
33+ PLongs = ^TLongs;
34+ TLongs = array[0..MaxInt div 4 - 1] of longint;
35+
36+ { Where the scanner is. Importing a module compiles it in the middle
37+ of another, so the parser saves this and restores it afterwards. }
38+ TScanState = record
39+ buf: PChar;
40+ len, pos, line, lineStart: longint;
41+ tokPos, tokLine, tokLineStart: longint;
42+ sym: TSym;
43+ ival: int64;
44+ rval: double;
45+ id: longint;
46+ path: shortstring;
47+ end;
48+
49+const
50+ MaxIdent = 63;
51+ MaxStr = 65536;
52+
53+var
54+ sym: TSym; { the current symbol }
55+ ival: int64; { sInt, sChar: its value }
56+ rval: double; { sReal: its value }
57+ id: longint; { sIdent: its name }
58+ sbuf: array[0..MaxStr] of byte; { sString: its bytes, then a zero }
59+ slen: longint; { sString: how many bytes }
60+
61+function Intern(p: PChar; n: longint): longint;
62+function NameOf(n: longint): shortstring;
63+function Open(const path: shortstring): boolean;
64+procedure Next;
65+procedure Mark(const msg: shortstring);
66+procedure Fatal(const msg: shortstring);
67+procedure Save(var st: TScanState);
68+procedure Restore(const st: TScanState);
69+function Where: shortstring;
70+function CurPath: shortstring;
71+function CurLine: longint;
72+
73+implementation
74+
75+uses BaseUnix;
76+
77+const
78+ NumWords = ord(sXor) - ord(sAnd) + 1;
79+ Words: array[0..NumWords - 1] of string[8] = (
80+ 'and', 'begin', 'break', 'by', 'code', 'const', 'defer', 'div', 'do',
81+ 'else', 'elsif', 'end', 'extern', 'for', 'forward', 'if', 'import',
82+ 'in', 'link', 'match', 'mod', 'module', 'not', 'of', 'or', 'packed',
83+ 'proc', 'record', 'repeat', 'return', 'set', 'shl', 'shr', 'then',
84+ 'to', 'type', 'until', 'var', 'variant', 'VOLATILE', 'while', 'xor');
85+
86+var
87+ cur: TScanState; { buf .. path; sym, ival, rval and id live above }
88+
89+ { The name table: every distinct identifier once, in a pool of
90+ characters, found through an open-addressed hash table. }
91+ pool: PChar;
92+ poolLen, poolCap: longint;
93+ nameOff, nameLen, nameHash: PLongs;
94+ numNames, nameCap: longint;
95+ table: PLongs; { name + 1, or 0 for an empty slot }
96+ tableMask: longint;
97+
98+{ Names }
99+
100+function Hash(p: PChar; n: longint): longint;
101+var h: longword; i: longint;
102+begin
103+ h := 2166136261;
104+ for i := 0 to n - 1 do h := (h xor byte(p[i])) * 16777619;
105+ Hash := longint(h and $7FFFFFFF);
106+end;
107+
108+procedure Grow;
109+var i, j, n: longint;
110+begin
111+ FreeMem(table);
112+ tableMask := tableMask * 2 + 1;
113+ table := GetMem((tableMask + 1) * 4);
114+ FillChar(table^, (tableMask + 1) * 4, 0);
115+ for n := 0 to numNames - 1 do begin
116+ i := nameHash^[n] and tableMask;
117+ while table^[i] <> 0 do i := (i + 1) and tableMask;
118+ table^[i] := n + 1;
119+ end;
120+ j := nameCap * 2;
121+ nameOff := ReAllocMem(nameOff, j * 4);
122+ nameLen := ReAllocMem(nameLen, j * 4);
123+ nameHash := ReAllocMem(nameHash, j * 4);
124+ nameCap := j;
125+end;
126+
127+function Intern(p: PChar; n: longint): longint;
128+var h, i, k: longint;
129+begin
130+ h := Hash(p, n);
131+ i := h and tableMask;
132+ while table^[i] <> 0 do begin
133+ k := table^[i] - 1;
134+ if (nameHash^[k] = h) and (nameLen^[k] = n)
135+ and (CompareByte(pool[nameOff^[k]], p^, n) = 0) then exit(k);
136+ i := (i + 1) and tableMask;
137+ end;
138+ if poolLen + n > poolCap then begin
139+ poolCap := poolCap * 2 + n;
140+ pool := ReAllocMem(pool, poolCap);
141+ end;
142+ Move(p^, pool[poolLen], n);
143+ k := numNames;
144+ nameOff^[k] := poolLen;
145+ nameLen^[k] := n;
146+ nameHash^[k] := h;
147+ inc(poolLen, n);
148+ inc(numNames);
149+ table^[i] := k + 1;
150+ if numNames * 2 > tableMask then Grow;
151+ Intern := k;
152+end;
153+
154+function NameOf(n: longint): shortstring;
155+var s: shortstring;
156+begin
157+ SetLength(s, nameLen^[n]);
158+ Move(pool[nameOff^[n]], s[1], nameLen^[n]);
159+ NameOf := s;
160+end;
161+
162+{ Errors }
163+
164+function Column(pos: longint): longint;
165+var i, col: longint;
166+begin
167+ { counted in characters: every byte but a UTF-8 continuation byte }
168+ col := 1;
169+ for i := cur.tokLineStart to pos - 1 do
170+ if (byte(cur.buf[i]) and $C0) <> $80 then inc(col);
171+ Column := col;
172+end;
173+
174+function Where: shortstring;
175+var l, c: shortstring;
176+begin
177+ Str(cur.tokLine, l);
178+ Str(Column(cur.tokPos), c);
179+ Where := cur.path + ':' + l + ':' + c;
180+end;
181+
182+function CurPath: shortstring;
183+begin
184+ CurPath := cur.path;
185+end;
186+
187+function CurLine: longint;
188+begin
189+ CurLine := cur.tokLine;
190+end;
191+
192+procedure Fatal(const msg: shortstring);
193+begin
194+ writeln(StdErr, 'jed: ', msg);
195+ Halt(1);
196+end;
197+
198+procedure Mark(const msg: shortstring);
199+begin
200+ writeln(StdErr, Where, ': ', msg);
201+ Halt(1);
202+end;
203+
204+{ Files }
205+
206+function Open(const path: shortstring): boolean;
207+var fd: cint; st: Stat; n, got, r: longint; p: shortstring;
208+begin
209+ p := path + #0;
210+ fd := FpOpen(@p[1], O_RDONLY);
211+ if fd < 0 then exit(false);
212+ if FpFStat(fd, st) <> 0 then begin FpClose(fd); exit(false) end;
213+ if (st.st_mode and S_IFMT) <> S_IFREG then begin FpClose(fd); exit(false) end;
214+ n := st.st_size;
215+ cur.buf := GetMem(n + 1);
216+ got := 0;
217+ while got < n do begin
218+ r := FpRead(fd, cur.buf[got], n - got);
219+ if r <= 0 then Fatal('can''t read ' + path);
220+ got := got + r;
221+ end;
222+ FpClose(fd);
223+ cur.buf[n] := #0; { the sentinel that ends every scan }
224+ cur.len := n;
225+ cur.pos := 0;
226+ cur.line := 1;
227+ cur.lineStart := 0;
228+ cur.tokPos := 0;
229+ cur.tokLine := 1;
230+ cur.tokLineStart := 0;
231+ cur.path := path;
232+ Open := true;
233+end;
234+
235+procedure Save(var st: TScanState);
236+begin
237+ st := cur;
238+ st.sym := sym; st.ival := ival; st.rval := rval; st.id := id;
239+end;
240+
241+procedure Restore(const st: TScanState);
242+begin
243+ cur := st;
244+ sym := st.sym; ival := st.ival; rval := st.rval; id := st.id;
245+end;
246+
247+{ UTF-8 }
248+
249+{ Decodes the character at buf[pos], which is not ASCII, checking that
250+ it is well formed; returns its code point and moves pos past it. }
251+function Utf8(var pos: longint): longint;
252+var b0, b1, n, i, cp: longint; lo, hi: byte;
253+begin
254+ b0 := byte(cur.buf[pos]);
255+ lo := $80; hi := $BF;
256+ case b0 of
257+ $C2..$DF: begin n := 1; cp := b0 and $1F end;
258+ $E0: begin n := 2; cp := 0; lo := $A0 end;
259+ $E1..$EC, $EE, $EF: begin n := 2; cp := b0 and $0F end;
260+ $ED: begin n := 2; cp := $0D; hi := $9F end; { no surrogates }
261+ $F0: begin n := 3; cp := 0; lo := $90 end;
262+ $F1..$F3: begin n := 3; cp := b0 and $07 end;
263+ $F4: begin n := 3; cp := 4; hi := $8F end; { up to 10FFFFH }
264+ else
265+ cur.tokPos := pos;
266+ Mark('bad UTF-8');
267+ end;
268+ for i := 1 to n do begin
269+ b1 := byte(cur.buf[pos + i]);
270+ if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then begin
271+ cur.tokPos := pos;
272+ Mark('bad UTF-8');
273+ end;
274+ cp := cp shl 6 or (b1 and $3F);
275+ lo := $80; hi := $BF;
276+ end;
277+ pos := pos + n + 1;
278+ Utf8 := cp;
279+end;
280+
281+procedure Put(b: longint);
282+begin
283+ if slen >= MaxStr then Mark('string too long');
284+ sbuf[slen] := b;
285+ inc(slen);
286+end;
287+
288+procedure PutUtf8(cp: longint);
289+begin
290+ if cp < $80 then Put(cp)
291+ else if cp < $800 then begin
292+ Put($C0 or cp shr 6); Put($80 or cp and $3F)
293+ end else if cp < $10000 then begin
294+ Put($E0 or cp shr 12); Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F)
295+ end else begin
296+ Put($F0 or cp shr 18); Put($80 or cp shr 12 and $3F);
297+ Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F)
298+ end;
299+end;
300+
301+function HexVal(c: char): longint;
302+begin
303+ case c of
304+ '0'..'9': HexVal := ord(c) - ord('0');
305+ 'A'..'F': HexVal := ord(c) - ord('A') + 10;
306+ 'a'..'f': HexVal := ord(c) - ord('a') + 10;
307+ else HexVal := -1;
308+ end;
309+end;
310+
311+{ One character of a character or string literal, at buf[pos]: its code
312+ point, or for \xHH, minus one minus the byte. }
313+function LitChar(inString: boolean): longint;
314+var c: char; v, d, n: longint;
315+begin
316+ c := cur.buf[cur.pos];
317+ if c = '\' then begin
318+ inc(cur.pos);
319+ c := cur.buf[cur.pos];
320+ inc(cur.pos);
321+ case c of
322+ 'n': v := 10;
323+ 't': v := 9;
324+ 'r': v := 13;
325+ '0': v := 0;
326+ '\', '''', '"': v := ord(c);
327+ 'x': begin
328+ if not inString then Mark('\x only in strings');
329+ d := HexVal(cur.buf[cur.pos]);
330+ n := HexVal(cur.buf[cur.pos + 1]);
331+ if (d < 0) or (n < 0) then Mark('\x needs two hex digits');
332+ inc(cur.pos, 2);
333+ v := -1 - (d * 16 + n);
334+ end;
335+ 'u': begin
336+ if cur.buf[cur.pos] <> '{' then Mark('\u needs {');
337+ inc(cur.pos);
338+ v := 0; n := 0;
339+ while HexVal(cur.buf[cur.pos]) >= 0 do begin
340+ v := v * 16 + HexVal(cur.buf[cur.pos]);
341+ inc(n); inc(cur.pos);
342+ if n > 6 then Mark('code point too big');
343+ end;
344+ if (n = 0) or (cur.buf[cur.pos] <> '}') then Mark('bad \u{...}');
345+ inc(cur.pos);
346+ if (v > $10FFFF) or ((v >= $D800) and (v <= $DFFF)) then
347+ Mark('not a code point');
348+ end;
349+ else Mark('unknown escape');
350+ end;
351+ end else if byte(c) >= $80 then
352+ v := Utf8(cur.pos)
353+ else if (c < ' ') or (c = #127) then
354+ Mark('unterminated literal')
355+ else begin
356+ v := ord(c);
357+ inc(cur.pos);
358+ end;
359+ LitChar := v;
360+end;
361+
362+{ Symbols }
363+
364+procedure Comment;
365+var depth: longint; c: char;
366+begin
367+ depth := 1;
368+ inc(cur.pos, 2);
369+ repeat
370+ c := cur.buf[cur.pos];
371+ if c = #0 then begin
372+ if cur.pos >= cur.len then Mark('comment not closed');
373+ inc(cur.pos);
374+ end else if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin
375+ inc(depth); inc(cur.pos, 2)
376+ end else if (c = '*') and (cur.buf[cur.pos + 1] = ')') then begin
377+ dec(depth); inc(cur.pos, 2)
378+ end else if c = #10 then begin
379+ inc(cur.pos); inc(cur.line); cur.lineStart := cur.pos
380+ end else if byte(c) >= $80 then
381+ Utf8(cur.pos)
382+ else
383+ inc(cur.pos);
384+ until depth = 0;
385+end;
386+
387+procedure Number;
388+var start, i, d: longint; allDec: boolean; v: qword; s: shortstring; code: word;
389+begin
390+ start := cur.pos;
391+ allDec := true;
392+ while cur.buf[cur.pos] in ['0'..'9', 'A'..'F'] do begin
393+ if cur.buf[cur.pos] > '9' then allDec := false;
394+ inc(cur.pos);
395+ end;
396+ if cur.buf[cur.pos] = 'H' then begin
397+ v := 0;
398+ for i := start to cur.pos - 1 do begin
399+ if v shr 60 <> 0 then Mark('number too big');
400+ v := v * 16 + qword(HexVal(cur.buf[i]));
401+ end;
402+ inc(cur.pos);
403+ sym := sInt;
404+ ival := int64(v); { 16 digits are the bits of a 64-bit word }
405+ end else if (cur.buf[cur.pos] = '.') and (cur.buf[cur.pos + 1] in ['0'..'9']) then begin
406+ if not allDec then Mark('bad number');
407+ inc(cur.pos);
408+ while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos);
409+ if cur.buf[cur.pos] = 'E' then begin
410+ inc(cur.pos);
411+ if cur.buf[cur.pos] in ['+', '-'] then inc(cur.pos);
412+ if not (cur.buf[cur.pos] in ['0'..'9']) then Mark('bad exponent');
413+ while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos);
414+ end;
415+ if cur.pos - start > 255 then Mark('number too long');
416+ SetLength(s, cur.pos - start);
417+ Move(cur.buf[start], s[1], cur.pos - start);
418+ Val(s, rval, code);
419+ if code <> 0 then Mark('bad real');
420+ sym := sReal;
421+ end else begin
422+ if not allDec then Mark('hex number needs H');
423+ v := 0;
424+ for i := start to cur.pos - 1 do begin
425+ d := ord(cur.buf[i]) - ord('0');
426+ if v > (qword(high(int64)) - qword(d)) div 10 then Mark('number too big');
427+ v := v * 10 + qword(d);
428+ end;
429+ sym := sInt;
430+ ival := int64(v);
431+ end;
432+ if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then Mark('bad number');
433+end;
434+
435+procedure Next;
436+var c: char; start, h, v: longint;
437+begin
438+ repeat
439+ c := cur.buf[cur.pos];
440+ while c in [' ', #9, #13, #10] do begin
441+ if c = #10 then begin
442+ inc(cur.line); cur.lineStart := cur.pos + 1
443+ end;
444+ inc(cur.pos);
445+ c := cur.buf[cur.pos];
446+ end;
447+ if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin
448+ Comment; c := ' '
449+ end;
450+ until c <> ' ';
451+ cur.tokPos := cur.pos;
452+ cur.tokLine := cur.line;
453+ cur.tokLineStart := cur.lineStart;
454+ case c of
455+ 'A'..'Z', 'a'..'z', '_': begin
456+ start := cur.pos;
457+ repeat inc(cur.pos)
458+ until not (cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '0'..'9', '_']);
459+ if cur.pos - start > MaxIdent then Mark('name too long');
460+ h := Intern(@cur.buf[start], cur.pos - start);
461+ if h < NumWords then sym := TSym(ord(sAnd) + h)
462+ else begin sym := sIdent; id := h end;
463+ end;
464+ '0'..'9': Number;
465+ '''': begin
466+ inc(cur.pos);
467+ if cur.buf[cur.pos] = '''' then Mark('empty character');
468+ v := LitChar(false);
469+ if cur.buf[cur.pos] <> '''' then Mark('character not closed');
470+ inc(cur.pos);
471+ sym := sChar;
472+ ival := v;
473+ end;
474+ '"': begin
475+ inc(cur.pos);
476+ slen := 0;
477+ while cur.buf[cur.pos] <> '"' do begin
478+ v := LitChar(true);
479+ if v < 0 then Put(-1 - v) else PutUtf8(v);
480+ end;
481+ inc(cur.pos);
482+ sbuf[slen] := 0;
483+ sym := sString;
484+ end;
485+ '+': begin inc(cur.pos); sym := sPlus end;
486+ '-': begin inc(cur.pos); sym := sMinus end;
487+ '*': begin inc(cur.pos); sym := sTimes end;
488+ '/': begin inc(cur.pos); sym := sSlash end;
489+ '=': begin inc(cur.pos); sym := sEql end;
490+ '#': begin inc(cur.pos); sym := sNeq end;
491+ '<': begin
492+ inc(cur.pos);
493+ if cur.buf[cur.pos] = '=' then begin inc(cur.pos); sym := sLeq end
494+ else sym := sLss;
495+ end;
496+ '>': begin
497+ inc(cur.pos);
498+ if cur.buf[cur.pos] = '=' then begin inc(cur.pos); sym := sGeq end
499+ else sym := sGtr;
500+ end;
501+ ':': begin
502+ inc(cur.pos);
503+ if cur.buf[cur.pos] = '=' then begin inc(cur.pos); sym := sBecomes end
504+ else sym := sColon;
505+ end;
506+ ';': begin inc(cur.pos); sym := sSemicolon end;
507+ ',': begin inc(cur.pos); sym := sComma end;
508+ '.': begin
509+ inc(cur.pos);
510+ if cur.buf[cur.pos] = '.' then begin
511+ inc(cur.pos);
512+ if cur.buf[cur.pos] = '.' then begin inc(cur.pos); sym := sEllipsis end
513+ else sym := sUpto;
514+ end else sym := sPeriod;
515+ end;
516+ '(': begin inc(cur.pos); sym := sLparen end;
517+ ')': begin inc(cur.pos); sym := sRparen end;
518+ '[': begin inc(cur.pos); sym := sLbrak end;
519+ ']': begin inc(cur.pos); sym := sRbrak end;
520+ '{': begin inc(cur.pos); sym := sLbrace end;
521+ '}': begin inc(cur.pos); sym := sRbrace end;
522+ '^': begin inc(cur.pos); sym := sArrow end;
523+ '|': begin inc(cur.pos); sym := sBar end;
524+ #0: begin
525+ if cur.pos < cur.len then Mark('NUL character');
526+ sym := sEof;
527+ end;
528+ else
529+ if byte(c) >= $80 then
530+ Mark('text outside strings, characters and comments must be ASCII');
531+ Mark('unexpected character');
532+ end;
533+end;
534+
535+var i: longint;
536+
537+initialization
538+ poolCap := 1 shl 16;
539+ pool := GetMem(poolCap);
540+ nameCap := 1 shl 12;
541+ nameOff := GetMem(nameCap * 4);
542+ nameLen := GetMem(nameCap * 4);
543+ nameHash := GetMem(nameCap * 4);
544+ tableMask := 2 * nameCap - 1;
545+ table := GetMem((tableMask + 1) * 4);
546+ FillChar(table^, (tableMask + 1) * 4, 0);
547+ for i := 0 to NumWords - 1 do Intern(@Words[i][1], length(Words[i]));
548+end.

src/sym.pas added +455 -0

@@ -0,0 +1,455 @@
1+{ sym.pas: types, objects and scopes.
2+
3+ Every name the program declares becomes an object (TObj): a constant,
4+ type, variable, procedure, module, record field, variant case or
5+ built-in. Every type is a TType. Objects are found through one hash
6+ table keyed by scope and name, so a lookup costs the same however
7+ big a module grows. A scope is just a number: the universe is 0,
8+ and each module, procedure, record and match arm gets a fresh one.
9+
10+ Depends on: scan, for names and errors.
11+ Leaves out: code. Where a variable lives is decided here (frame
12+ offsets, chunk numbers), but nothing is emitted. }
13+
14+unit sym;
15+
16+{$mode objfpc}{$H-}
17+
18+interface
19+
20+uses scan;
21+
22+type
23+ TForm = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray,
24+ fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError);
25+ { fConst is the type of an untyped integer constant; fStr of a string
26+ literal, whose length the literal carries }
27+
28+ TClass = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin);
29+
30+ PType = ^TType;
31+ PObj = ^TObj;
32+ PModule = ^TModule;
33+ PImport = ^TImport;
34+
35+ TType = record
36+ form: TForm;
37+ size, align: int64;
38+ signed: boolean; { fInt }
39+ vol: boolean; { fPtr: ^VOLATILE }
40+ packd: boolean; { fRecord }
41+ variadic: boolean; { fProc: ends in ... }
42+ base: PType; { fPtr, fArray, fSlice: what it holds; fProc: result }
43+ len: int64; { fArray: elements; fProc: parameters; fVariant: cases }
44+ fields: PObj; { fRecord: fields; fVariant: cases; fProc: parameters }
45+ scope: longint; { fRecord: the scope of its fields }
46+ fwd: longint; { fPtr whose base isn't declared yet: its name, else -1 }
47+ obj: PObj; { the declaration that names it, or nil }
48+ module: PModule; { the module that built it }
49+ end;
50+
51+ TObj = record
52+ cls: TClass;
53+ name: longint;
54+ exported: boolean;
55+ typ: PType;
56+ next: PObj; { the next in its list: scope, fields, parameters }
57+ scope: longint; { where it is declared }
58+ val: int64; { oConst: value; oBuiltin: which; oCase: tag;
59+ oField: offset; oVar: frame offset }
60+ chunk: longint; { global oVar, oProc, string oConst: its chunk }
61+ lev: integer; { oVar: 0 for a module variable, 1 for a local }
62+ ind: boolean; { oVar: the frame slot holds the variable's address }
63+ off: int64; { oVar with ind: added to that address }
64+ isVar: boolean; { a var parameter }
65+ fwd: boolean; { oProc: declared forward, no body yet }
66+ isCode: boolean; { oProc: a code procedure }
67+ fields: PObj; { oCase: its fields }
68+ module: PModule; { oModule: the module; others: where declared }
69+ end;
70+
71+ TImport = record
72+ module: PModule;
73+ next: PImport;
74+ end;
75+
76+ TModule = record
77+ name: longint;
78+ scope: longint;
79+ path: shortstring;
80+ first, last: PObj; { its top-level declarations, in order }
81+ imports: PImport;
82+ body: longint; { the chunk of its body, or -1 }
83+ done: boolean; { compiled to the end }
84+ checkOnly: boolean; { read only to check another file's interface }
85+ next: PModule; { modules in the order they were finished }
86+ end;
87+
88+const
89+ { built-in procedures }
90+ bSize = 0; bAdr = 1; bLen = 2; bNew = 3; bMsg = 4; bSyscall = 5;
91+ bFence = 6; bCas = 7; bXchg = 8; bXadd = 9; bArgc = 10; bArgv = 11;
92+
93+var
94+ tI8, tI16, tI32, tI64, tU8, tU16, tU32, tU64: PType;
95+ tBool, tReal, tConst, tNil, tStr, tNone, tPtrU8: PType;
96+ curModule: PModule;
97+
98+function NewType(form: TForm; size, align: int64): PType;
99+function NewObj(cls: TClass; name: longint; typ: PType): PObj;
100+function NewScope: longint;
101+procedure OpenScope(s: longint);
102+procedure CloseScope;
103+function TopScope: longint;
104+procedure Insert(obj: PObj; s: longint);
105+function Find(s, name: longint): PObj;
106+function Lookup(name: longint): PObj;
107+
108+function AlignUp(x, a: int64): int64;
109+function Same(a, b: PType): boolean;
110+function IsInt(t: PType): boolean;
111+function IsScalar(t: PType): boolean;
112+function IsAggregate(t: PType): boolean;
113+function Fits(v: int64; t: PType): boolean;
114+function TypeName(t: PType): shortstring;
115+function SameAcross(a, b: PType; ma, mb: PModule): boolean;
116+function SameSig(a, b: PType; ma, mb: PModule): boolean;
117+
118+implementation
119+
120+const
121+ MaxDepth = 64;
122+
123+type
124+ PObjTab = ^TObjTab;
125+ TObjTab = array[0..MaxInt div 16] of PObj;
126+
127+var
128+ scopes: array[0..MaxDepth - 1] of longint;
129+ depth: longint;
130+ nextScope: longint;
131+ hashTab: PObjTab;
132+ hashMask, hashCount: longint;
133+
134+function NewType(form: TForm; size, align: int64): PType;
135+var t: PType;
136+begin
137+ New(t);
138+ FillChar(t^, SizeOf(TType), 0);
139+ t^.form := form;
140+ t^.size := size;
141+ t^.align := align;
142+ t^.fwd := -1;
143+ t^.module := curModule;
144+ NewType := t;
145+end;
146+
147+function NewObj(cls: TClass; name: longint; typ: PType): PObj;
148+var o: PObj;
149+begin
150+ New(o);
151+ FillChar(o^, SizeOf(TObj), 0);
152+ o^.cls := cls;
153+ o^.name := name;
154+ o^.typ := typ;
155+ o^.chunk := -1;
156+ o^.module := curModule;
157+ NewObj := o;
158+end;
159+
160+{ Scopes }
161+
162+function NewScope: longint;
163+begin
164+ inc(nextScope);
165+ NewScope := nextScope;
166+end;
167+
168+procedure OpenScope(s: longint);
169+begin
170+ if depth = MaxDepth then Mark('nested too deeply');
171+ scopes[depth] := s;
172+ inc(depth);
173+end;
174+
175+procedure CloseScope;
176+begin
177+ dec(depth);
178+end;
179+
180+function TopScope: longint;
181+begin
182+ TopScope := scopes[depth - 1];
183+end;
184+
185+function Slot(s, name: longint): longint;
186+begin
187+ Slot := longint((longword(s) * 2654435761 xor longword(name) * 40503) and longword(hashMask));
188+end;
189+
190+procedure Rehash;
191+var old: PObjTab; n, i, j: longint;
192+begin
193+ old := hashTab;
194+ n := hashMask + 1;
195+ hashMask := n * 2 - 1;
196+ hashTab := GetMem(n * 2 * SizeOf(PObj));
197+ FillChar(hashTab^, n * 2 * SizeOf(PObj), 0);
198+ for i := 0 to n - 1 do
199+ if old^[i] <> nil then begin
200+ j := Slot(old^[i]^.scope, old^[i]^.name);
201+ while hashTab^[j] <> nil do j := (j + 1) and hashMask;
202+ hashTab^[j] := old^[i];
203+ end;
204+ FreeMem(old);
205+end;
206+
207+procedure Insert(obj: PObj; s: longint);
208+var i: longint; o: PObj;
209+begin
210+ i := Slot(s, obj^.name);
211+ o := hashTab^[i];
212+ while o <> nil do begin
213+ if (o^.scope = s) and (o^.name = obj^.name) then
214+ Mark(NameOf(obj^.name) + ' is declared twice');
215+ i := (i + 1) and hashMask;
216+ o := hashTab^[i];
217+ end;
218+ obj^.scope := s;
219+ hashTab^[i] := obj;
220+ inc(hashCount);
221+ if hashCount * 2 > hashMask then Rehash;
222+end;
223+
224+function Find(s, name: longint): PObj;
225+var i: longint; o: PObj;
226+begin
227+ i := Slot(s, name);
228+ o := hashTab^[i];
229+ while o <> nil do begin
230+ if (o^.scope = s) and (o^.name = name) then exit(o);
231+ i := (i + 1) and hashMask;
232+ o := hashTab^[i];
233+ end;
234+ Find := nil;
235+end;
236+
237+function Lookup(name: longint): PObj;
238+var i: longint; o: PObj;
239+begin
240+ for i := depth - 1 downto 0 do begin
241+ o := Find(scopes[i], name);
242+ if o <> nil then exit(o);
243+ end;
244+ Lookup := nil;
245+end;
246+
247+{ Types }
248+
249+function AlignUp(x, a: int64): int64;
250+begin
251+ AlignUp := (x + a - 1) div a * a;
252+end;
253+
254+function IsInt(t: PType): boolean;
255+begin
256+ IsInt := t^.form in [fInt, fConst];
257+end;
258+
259+function IsScalar(t: PType): boolean;
260+begin
261+ IsScalar := t^.form in [fBool, fInt, fReal, fConst, fNil, fPtr, fProc,
262+ fEnum, fSet, fError];
263+end;
264+
265+function IsAggregate(t: PType): boolean;
266+begin
267+ IsAggregate := t^.form in [fArray, fSlice, fRecord, fVariant];
268+end;
269+
270+function Fits(v: int64; t: PType): boolean;
271+begin
272+ if t^.form <> fInt then exit(t^.form = fConst);
273+ case t^.size of
274+ 1: if t^.signed then Fits := (v >= -128) and (v <= 127)
275+ else Fits := (v >= 0) and (v <= 255);
276+ 2: if t^.signed then Fits := (v >= -32768) and (v <= 32767)
277+ else Fits := (v >= 0) and (v <= 65535);
278+ 4: if t^.signed then Fits := (v >= -2147483648) and (v <= 2147483647)
279+ else Fits := (v >= 0) and (v <= 4294967295);
280+ else
281+ { an untyped constant is 64 bits; one with the top bit set came from
282+ a hex literal, and stands for a U64 above high(I64) }
283+ Fits := true;
284+ end;
285+end;
286+
287+{ Structural sameness of two types. Named types are the same only if
288+ they are one declaration; a type with no name is the same as another
289+ built alike. }
290+function Alike(a, b: PType): boolean;
291+var p, q: PObj;
292+begin
293+ if a = b then exit(true);
294+ if a^.form <> b^.form then exit(false);
295+ case a^.form of
296+ fPtr: Alike := (a^.vol = b^.vol) and Same(a^.base, b^.base);
297+ fArray: Alike := (a^.len = b^.len) and Same(a^.base, b^.base);
298+ fSlice: Alike := Same(a^.base, b^.base);
299+ fProc: begin
300+ if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false);
301+ if (a^.base = nil) <> (b^.base = nil) then exit(false);
302+ if (a^.base <> nil) and not Same(a^.base, b^.base) then exit(false);
303+ p := a^.fields; q := b^.fields;
304+ while p <> nil do begin
305+ if (p^.isVar <> q^.isVar) or not Same(p^.typ, q^.typ) then exit(false);
306+ p := p^.next; q := q^.next;
307+ end;
308+ Alike := true;
309+ end;
310+ else Alike := false;
311+ end;
312+end;
313+
314+function Same(a, b: PType): boolean;
315+begin
316+ if a = b then exit(true);
317+ if (a = nil) or (b = nil) then exit(false);
318+ if (a^.obj <> nil) and (b^.obj <> nil) then exit(false);
319+ Same := Alike(a, b);
320+end;
321+
322+function TypeName(t: PType): shortstring;
323+var s: shortstring;
324+begin
325+ if t = nil then exit('nothing');
326+ if t^.obj <> nil then begin
327+ if (t^.obj^.module <> nil) and (t^.obj^.module <> curModule) then
328+ exit(NameOf(t^.obj^.module^.name) + '.' + NameOf(t^.obj^.name));
329+ exit(NameOf(t^.obj^.name));
330+ end;
331+ case t^.form of
332+ fConst: TypeName := 'an integer constant';
333+ fNil: TypeName := 'nil';
334+ fStr: TypeName := 'a string';
335+ fPtr: if t^.vol then TypeName := '^VOLATILE ' + TypeName(t^.base)
336+ else TypeName := '^' + TypeName(t^.base);
337+ fArray: begin Str(t^.len, s); TypeName := '[' + s + ']' + TypeName(t^.base) end;
338+ fSlice: TypeName := '[]' + TypeName(t^.base);
339+ fRecord: TypeName := 'record';
340+ fVariant: TypeName := 'variant';
341+ fProc: TypeName := 'proc';
342+ else TypeName := '?';
343+ end;
344+end;
345+
346+{ The interface check: types of two files of one module, where a type
347+ declared in one file stands for the type of the same name in the
348+ other. }
349+function SameAcross(a, b: PType; ma, mb: PModule): boolean;
350+var p, q: PObj;
351+begin
352+ if a = b then exit(true);
353+ if (a = nil) or (b = nil) then exit(false);
354+ if (a^.obj <> nil) or (b^.obj <> nil) then begin
355+ if (a^.obj = nil) or (b^.obj = nil) then exit(false);
356+ exit((a^.obj^.module = ma) and (b^.obj^.module = mb)
357+ and (a^.obj^.name = b^.obj^.name));
358+ end;
359+ if a^.form <> b^.form then exit(false);
360+ case a^.form of
361+ fPtr: SameAcross := (a^.vol = b^.vol) and SameAcross(a^.base, b^.base, ma, mb);
362+ fArray: SameAcross := (a^.len = b^.len) and SameAcross(a^.base, b^.base, ma, mb);
363+ fSlice: SameAcross := SameAcross(a^.base, b^.base, ma, mb);
364+ fProc: SameAcross := SameSig(a, b, ma, mb);
365+ fRecord, fVariant: begin
366+ { anonymous: every field, exported or not, in order }
367+ p := a^.fields; q := b^.fields;
368+ while (p <> nil) and (q <> nil) do begin
369+ if (p^.name <> q^.name) or not SameAcross(p^.typ, q^.typ, ma, mb) then exit(false);
370+ p := p^.next; q := q^.next;
371+ end;
372+ SameAcross := (p = nil) and (q = nil);
373+ end;
374+ else SameAcross := false;
375+ end;
376+end;
377+
378+function SameSig(a, b: PType; ma, mb: PModule): boolean;
379+var p, q: PObj;
380+begin
381+ if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false);
382+ if (a^.base = nil) <> (b^.base = nil) then exit(false);
383+ if (a^.base <> nil) and not SameAcross(a^.base, b^.base, ma, mb) then exit(false);
384+ p := a^.fields; q := b^.fields;
385+ while p <> nil do begin
386+ if (p^.isVar <> q^.isVar) or not SameAcross(p^.typ, q^.typ, ma, mb) then exit(false);
387+ p := p^.next; q := q^.next;
388+ end;
389+ SameSig := true;
390+end;
391+
392+{ The universe }
393+
394+function Basic(const name: shortstring; form: TForm; size: int64; signed: boolean): PType;
395+var t: PType; o: PObj;
396+begin
397+ t := NewType(form, size, size);
398+ t^.signed := signed;
399+ o := NewObj(oType, Intern(@name[1], length(name)), t);
400+ o^.exported := true;
401+ t^.obj := o;
402+ Insert(o, 0);
403+ Basic := t;
404+end;
405+
406+procedure Enter(const name: shortstring; cls: TClass; t: PType; v: int64);
407+var o: PObj;
408+begin
409+ o := NewObj(cls, Intern(@name[1], length(name)), t);
410+ o^.val := v;
411+ o^.exported := true;
412+ Insert(o, 0);
413+end;
414+
415+initialization
416+ hashMask := (1 shl 14) - 1;
417+ hashTab := GetMem((hashMask + 1) * SizeOf(PObj));
418+ FillChar(hashTab^, (hashMask + 1) * SizeOf(PObj), 0);
419+ depth := 1;
420+ scopes[0] := 0;
421+ nextScope := 0;
422+ curModule := nil;
423+ tI8 := Basic('I8', fInt, 1, true);
424+ tI16 := Basic('I16', fInt, 2, true);
425+ tI32 := Basic('I32', fInt, 4, true);
426+ tI64 := Basic('I64', fInt, 8, true);
427+ tU8 := Basic('U8', fInt, 1, false);
428+ tU16 := Basic('U16', fInt, 2, false);
429+ tU32 := Basic('U32', fInt, 4, false);
430+ tU64 := Basic('U64', fInt, 8, false);
431+ tBool := Basic('BOOL', fBool, 1, false);
432+ tReal := Basic('F64', fReal, 8, false);
433+ tConst := NewType(fConst, 8, 8);
434+ tConst^.signed := true;
435+ tNil := NewType(fNil, 8, 8);
436+ tStr := NewType(fStr, 0, 1);
437+ tNone := NewType(fNone, 0, 1);
438+ tPtrU8 := NewType(fPtr, 8, 8);
439+ tPtrU8^.base := tU8;
440+ Enter('true', oConst, tBool, 1);
441+ Enter('false', oConst, tBool, 0);
442+ Enter('nil', oConst, tNil, 0);
443+ Enter('SIZE', oBuiltin, nil, bSize);
444+ Enter('ADR', oBuiltin, nil, bAdr);
445+ Enter('LEN', oBuiltin, nil, bLen);
446+ Enter('NEW', oBuiltin, nil, bNew);
447+ Enter('MSG', oBuiltin, nil, bMsg);
448+ Enter('SYSCALL', oBuiltin, nil, bSyscall);
449+ Enter('FENCE', oBuiltin, nil, bFence);
450+ Enter('CAS', oBuiltin, nil, bCas);
451+ Enter('XCHG', oBuiltin, nil, bXchg);
452+ Enter('XADD', oBuiltin, nil, bXadd);
453+ Enter('ARGC', oBuiltin, nil, bArgc);
454+ Enter('ARGV', oBuiltin, nil, bArgv);
455+end.

test/scantest.pas added +19 -0

@@ -0,0 +1,19 @@
1+{ Prints the symbols of a file, one per line: a test of scan.pas. }
2+program scantest;
3+{$mode objfpc}{$H-}
4+uses scan;
5+var i: longint;
6+begin
7+ if not Open(ParamStr(1)) then Fatal('no file');
8+ repeat
9+ Next;
10+ write(Where, ' ', ord(sym));
11+ case sym of
12+ sIdent: write(' ', NameOf(id));
13+ sInt, sChar: write(' ', ival);
14+ sReal: write(' ', rval:0:6);
15+ sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end;
16+ end;
17+ writeln;
18+ until sym = sEof;
19+end.