From 626e09b72c72caebcfea0bacc302249c43ae2137 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:07:25 +0000 Subject: [PATCH] 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. --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96b025b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build/ +/jed diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d4ca04c --- /dev/null +++ b/Makefile @@ -0,0 +1,20 @@ +# Builds the compiler, jed, from src/ into the repository's root; the +# library it needs is lib/, beside it. + +FPC = fpc +FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild + +jed: src/*.pas | build + $(FPC) $(FPCFLAGS) -ojed src/jed.pas + +units: src/*.pas | build + $(FPC) $(FPCFLAGS) src/scan.pas + $(FPC) $(FPCFLAGS) src/sym.pas + +build: + mkdir -p build + +clean: + rm -rf build jed + +.PHONY: units clean diff --git a/src/scan.pas b/src/scan.pas new file mode 100644 index 0000000..7501aba --- /dev/null +++ b/src/scan.pas @@ -0,0 +1,548 @@ +{ scan.pas: the scanner. + + Reads a jed source file and hands the parser one symbol at a time: + reserved words, identifiers, numbers, characters, strings and + operators. Identifiers are interned, so that the rest of the compiler + compares names as small integers. The scanner also reports errors, + since it knows where in the file the compiler is. + + Depends on: BaseUnix, to read files. + Leaves out: recovery from errors. The first error stops the compiler. } + +unit scan; + +{$mode objfpc}{$H-} + +interface + +type + TSym = (sNull, sIdent, sInt, sReal, sChar, sString, + sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq, + sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis, + sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sBar, + { the reserved words, in the order of Words below } + sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse, + sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink, + sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord, + sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sType, sUntil, sVar, + sVariant, sVolatile, sWhile, sXor, + sEof); + + PBytes = ^TBytes; + TBytes = array[0..MaxInt - 1] of byte; + PLongs = ^TLongs; + TLongs = array[0..MaxInt div 4 - 1] of longint; + + { Where the scanner is. Importing a module compiles it in the middle + of another, so the parser saves this and restores it afterwards. } + TScanState = record + buf: PChar; + len, pos, line, lineStart: longint; + tokPos, tokLine, tokLineStart: longint; + sym: TSym; + ival: int64; + rval: double; + id: longint; + path: shortstring; + end; + +const + MaxIdent = 63; + MaxStr = 65536; + +var + sym: TSym; { the current symbol } + ival: int64; { sInt, sChar: its value } + rval: double; { sReal: its value } + id: longint; { sIdent: its name } + sbuf: array[0..MaxStr] of byte; { sString: its bytes, then a zero } + slen: longint; { sString: how many bytes } + +function Intern(p: PChar; n: longint): longint; +function NameOf(n: longint): shortstring; +function Open(const path: shortstring): boolean; +procedure Next; +procedure Mark(const msg: shortstring); +procedure Fatal(const msg: shortstring); +procedure Save(var st: TScanState); +procedure Restore(const st: TScanState); +function Where: shortstring; +function CurPath: shortstring; +function CurLine: longint; + +implementation + +uses BaseUnix; + +const + NumWords = ord(sXor) - ord(sAnd) + 1; + Words: array[0..NumWords - 1] of string[8] = ( + 'and', 'begin', 'break', 'by', 'code', 'const', 'defer', 'div', 'do', + 'else', 'elsif', 'end', 'extern', 'for', 'forward', 'if', 'import', + 'in', 'link', 'match', 'mod', 'module', 'not', 'of', 'or', 'packed', + 'proc', 'record', 'repeat', 'return', 'set', 'shl', 'shr', 'then', + 'to', 'type', 'until', 'var', 'variant', 'VOLATILE', 'while', 'xor'); + +var + cur: TScanState; { buf .. path; sym, ival, rval and id live above } + + { The name table: every distinct identifier once, in a pool of + characters, found through an open-addressed hash table. } + pool: PChar; + poolLen, poolCap: longint; + nameOff, nameLen, nameHash: PLongs; + numNames, nameCap: longint; + table: PLongs; { name + 1, or 0 for an empty slot } + tableMask: longint; + +{ Names } + +function Hash(p: PChar; n: longint): longint; +var h: longword; i: longint; +begin + h := 2166136261; + for i := 0 to n - 1 do h := (h xor byte(p[i])) * 16777619; + Hash := longint(h and $7FFFFFFF); +end; + +procedure Grow; +var i, j, n: longint; +begin + FreeMem(table); + tableMask := tableMask * 2 + 1; + table := GetMem((tableMask + 1) * 4); + FillChar(table^, (tableMask + 1) * 4, 0); + for n := 0 to numNames - 1 do begin + i := nameHash^[n] and tableMask; + while table^[i] <> 0 do i := (i + 1) and tableMask; + table^[i] := n + 1; + end; + j := nameCap * 2; + nameOff := ReAllocMem(nameOff, j * 4); + nameLen := ReAllocMem(nameLen, j * 4); + nameHash := ReAllocMem(nameHash, j * 4); + nameCap := j; +end; + +function Intern(p: PChar; n: longint): longint; +var h, i, k: longint; +begin + h := Hash(p, n); + i := h and tableMask; + while table^[i] <> 0 do begin + k := table^[i] - 1; + if (nameHash^[k] = h) and (nameLen^[k] = n) + and (CompareByte(pool[nameOff^[k]], p^, n) = 0) then exit(k); + i := (i + 1) and tableMask; + end; + if poolLen + n > poolCap then begin + poolCap := poolCap * 2 + n; + pool := ReAllocMem(pool, poolCap); + end; + Move(p^, pool[poolLen], n); + k := numNames; + nameOff^[k] := poolLen; + nameLen^[k] := n; + nameHash^[k] := h; + inc(poolLen, n); + inc(numNames); + table^[i] := k + 1; + if numNames * 2 > tableMask then Grow; + Intern := k; +end; + +function NameOf(n: longint): shortstring; +var s: shortstring; +begin + SetLength(s, nameLen^[n]); + Move(pool[nameOff^[n]], s[1], nameLen^[n]); + NameOf := s; +end; + +{ Errors } + +function Column(pos: longint): longint; +var i, col: longint; +begin + { counted in characters: every byte but a UTF-8 continuation byte } + col := 1; + for i := cur.tokLineStart to pos - 1 do + if (byte(cur.buf[i]) and $C0) <> $80 then inc(col); + Column := col; +end; + +function Where: shortstring; +var l, c: shortstring; +begin + Str(cur.tokLine, l); + Str(Column(cur.tokPos), c); + Where := cur.path + ':' + l + ':' + c; +end; + +function CurPath: shortstring; +begin + CurPath := cur.path; +end; + +function CurLine: longint; +begin + CurLine := cur.tokLine; +end; + +procedure Fatal(const msg: shortstring); +begin + writeln(StdErr, 'jed: ', msg); + Halt(1); +end; + +procedure Mark(const msg: shortstring); +begin + writeln(StdErr, Where, ': ', msg); + Halt(1); +end; + +{ Files } + +function Open(const path: shortstring): boolean; +var fd: cint; st: Stat; n, got, r: longint; p: shortstring; +begin + p := path + #0; + fd := FpOpen(@p[1], O_RDONLY); + if fd < 0 then exit(false); + if FpFStat(fd, st) <> 0 then begin FpClose(fd); exit(false) end; + if (st.st_mode and S_IFMT) <> S_IFREG then begin FpClose(fd); exit(false) end; + n := st.st_size; + cur.buf := GetMem(n + 1); + got := 0; + while got < n do begin + r := FpRead(fd, cur.buf[got], n - got); + if r <= 0 then Fatal('can''t read ' + path); + got := got + r; + end; + FpClose(fd); + cur.buf[n] := #0; { the sentinel that ends every scan } + cur.len := n; + cur.pos := 0; + cur.line := 1; + cur.lineStart := 0; + cur.tokPos := 0; + cur.tokLine := 1; + cur.tokLineStart := 0; + cur.path := path; + Open := true; +end; + +procedure Save(var st: TScanState); +begin + st := cur; + st.sym := sym; st.ival := ival; st.rval := rval; st.id := id; +end; + +procedure Restore(const st: TScanState); +begin + cur := st; + sym := st.sym; ival := st.ival; rval := st.rval; id := st.id; +end; + +{ UTF-8 } + +{ Decodes the character at buf[pos], which is not ASCII, checking that + it is well formed; returns its code point and moves pos past it. } +function Utf8(var pos: longint): longint; +var b0, b1, n, i, cp: longint; lo, hi: byte; +begin + b0 := byte(cur.buf[pos]); + lo := $80; hi := $BF; + case b0 of + $C2..$DF: begin n := 1; cp := b0 and $1F end; + $E0: begin n := 2; cp := 0; lo := $A0 end; + $E1..$EC, $EE, $EF: begin n := 2; cp := b0 and $0F end; + $ED: begin n := 2; cp := $0D; hi := $9F end; { no surrogates } + $F0: begin n := 3; cp := 0; lo := $90 end; + $F1..$F3: begin n := 3; cp := b0 and $07 end; + $F4: begin n := 3; cp := 4; hi := $8F end; { up to 10FFFFH } + else + cur.tokPos := pos; + Mark('bad UTF-8'); + end; + for i := 1 to n do begin + b1 := byte(cur.buf[pos + i]); + if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then begin + cur.tokPos := pos; + Mark('bad UTF-8'); + end; + cp := cp shl 6 or (b1 and $3F); + lo := $80; hi := $BF; + end; + pos := pos + n + 1; + Utf8 := cp; +end; + +procedure Put(b: longint); +begin + if slen >= MaxStr then Mark('string too long'); + sbuf[slen] := b; + inc(slen); +end; + +procedure PutUtf8(cp: longint); +begin + if cp < $80 then Put(cp) + else if cp < $800 then begin + Put($C0 or cp shr 6); Put($80 or cp and $3F) + end else if cp < $10000 then begin + Put($E0 or cp shr 12); Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F) + end else begin + Put($F0 or cp shr 18); Put($80 or cp shr 12 and $3F); + Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F) + end; +end; + +function HexVal(c: char): longint; +begin + case c of + '0'..'9': HexVal := ord(c) - ord('0'); + 'A'..'F': HexVal := ord(c) - ord('A') + 10; + 'a'..'f': HexVal := ord(c) - ord('a') + 10; + else HexVal := -1; + end; +end; + +{ One character of a character or string literal, at buf[pos]: its code + point, or for \xHH, minus one minus the byte. } +function LitChar(inString: boolean): longint; +var c: char; v, d, n: longint; +begin + c := cur.buf[cur.pos]; + if c = '\' then begin + inc(cur.pos); + c := cur.buf[cur.pos]; + inc(cur.pos); + case c of + 'n': v := 10; + 't': v := 9; + 'r': v := 13; + '0': v := 0; + '\', '''', '"': v := ord(c); + 'x': begin + if not inString then Mark('\x only in strings'); + d := HexVal(cur.buf[cur.pos]); + n := HexVal(cur.buf[cur.pos + 1]); + if (d < 0) or (n < 0) then Mark('\x needs two hex digits'); + inc(cur.pos, 2); + v := -1 - (d * 16 + n); + end; + 'u': begin + if cur.buf[cur.pos] <> '{' then Mark('\u needs {'); + inc(cur.pos); + v := 0; n := 0; + while HexVal(cur.buf[cur.pos]) >= 0 do begin + v := v * 16 + HexVal(cur.buf[cur.pos]); + inc(n); inc(cur.pos); + if n > 6 then Mark('code point too big'); + end; + if (n = 0) or (cur.buf[cur.pos] <> '}') then Mark('bad \u{...}'); + inc(cur.pos); + if (v > $10FFFF) or ((v >= $D800) and (v <= $DFFF)) then + Mark('not a code point'); + end; + else Mark('unknown escape'); + end; + end else if byte(c) >= $80 then + v := Utf8(cur.pos) + else if (c < ' ') or (c = #127) then + Mark('unterminated literal') + else begin + v := ord(c); + inc(cur.pos); + end; + LitChar := v; +end; + +{ Symbols } + +procedure Comment; +var depth: longint; c: char; +begin + depth := 1; + inc(cur.pos, 2); + repeat + c := cur.buf[cur.pos]; + if c = #0 then begin + if cur.pos >= cur.len then Mark('comment not closed'); + inc(cur.pos); + end else if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin + inc(depth); inc(cur.pos, 2) + end else if (c = '*') and (cur.buf[cur.pos + 1] = ')') then begin + dec(depth); inc(cur.pos, 2) + end else if c = #10 then begin + inc(cur.pos); inc(cur.line); cur.lineStart := cur.pos + end else if byte(c) >= $80 then + Utf8(cur.pos) + else + inc(cur.pos); + until depth = 0; +end; + +procedure Number; +var start, i, d: longint; allDec: boolean; v: qword; s: shortstring; code: word; +begin + start := cur.pos; + allDec := true; + while cur.buf[cur.pos] in ['0'..'9', 'A'..'F'] do begin + if cur.buf[cur.pos] > '9' then allDec := false; + inc(cur.pos); + end; + if cur.buf[cur.pos] = 'H' then begin + v := 0; + for i := start to cur.pos - 1 do begin + if v shr 60 <> 0 then Mark('number too big'); + v := v * 16 + qword(HexVal(cur.buf[i])); + end; + inc(cur.pos); + sym := sInt; + ival := int64(v); { 16 digits are the bits of a 64-bit word } + end else if (cur.buf[cur.pos] = '.') and (cur.buf[cur.pos + 1] in ['0'..'9']) then begin + if not allDec then Mark('bad number'); + inc(cur.pos); + while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos); + if cur.buf[cur.pos] = 'E' then begin + inc(cur.pos); + if cur.buf[cur.pos] in ['+', '-'] then inc(cur.pos); + if not (cur.buf[cur.pos] in ['0'..'9']) then Mark('bad exponent'); + while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos); + end; + if cur.pos - start > 255 then Mark('number too long'); + SetLength(s, cur.pos - start); + Move(cur.buf[start], s[1], cur.pos - start); + Val(s, rval, code); + if code <> 0 then Mark('bad real'); + sym := sReal; + end else begin + if not allDec then Mark('hex number needs H'); + v := 0; + for i := start to cur.pos - 1 do begin + d := ord(cur.buf[i]) - ord('0'); + if v > (qword(high(int64)) - qword(d)) div 10 then Mark('number too big'); + v := v * 10 + qword(d); + end; + sym := sInt; + ival := int64(v); + end; + if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then Mark('bad number'); +end; + +procedure Next; +var c: char; start, h, v: longint; +begin + repeat + c := cur.buf[cur.pos]; + while c in [' ', #9, #13, #10] do begin + if c = #10 then begin + inc(cur.line); cur.lineStart := cur.pos + 1 + end; + inc(cur.pos); + c := cur.buf[cur.pos]; + end; + if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin + Comment; c := ' ' + end; + until c <> ' '; + cur.tokPos := cur.pos; + cur.tokLine := cur.line; + cur.tokLineStart := cur.lineStart; + case c of + 'A'..'Z', 'a'..'z', '_': begin + start := cur.pos; + repeat inc(cur.pos) + until not (cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '0'..'9', '_']); + if cur.pos - start > MaxIdent then Mark('name too long'); + h := Intern(@cur.buf[start], cur.pos - start); + if h < NumWords then sym := TSym(ord(sAnd) + h) + else begin sym := sIdent; id := h end; + end; + '0'..'9': Number; + '''': begin + inc(cur.pos); + if cur.buf[cur.pos] = '''' then Mark('empty character'); + v := LitChar(false); + if cur.buf[cur.pos] <> '''' then Mark('character not closed'); + inc(cur.pos); + sym := sChar; + ival := v; + end; + '"': begin + inc(cur.pos); + slen := 0; + while cur.buf[cur.pos] <> '"' do begin + v := LitChar(true); + if v < 0 then Put(-1 - v) else PutUtf8(v); + end; + inc(cur.pos); + sbuf[slen] := 0; + sym := sString; + end; + '+': begin inc(cur.pos); sym := sPlus end; + '-': begin inc(cur.pos); sym := sMinus end; + '*': begin inc(cur.pos); sym := sTimes end; + '/': begin inc(cur.pos); sym := sSlash end; + '=': begin inc(cur.pos); sym := sEql end; + '#': begin inc(cur.pos); sym := sNeq end; + '<': begin + inc(cur.pos); + if cur.buf[cur.pos] = '=' then begin inc(cur.pos); sym := sLeq end + else sym := sLss; + end; + '>': begin + inc(cur.pos); + if cur.buf[cur.pos] = '=' then begin inc(cur.pos); sym := sGeq end + else sym := sGtr; + end; + ':': begin + inc(cur.pos); + if cur.buf[cur.pos] = '=' then begin inc(cur.pos); sym := sBecomes end + else sym := sColon; + end; + ';': begin inc(cur.pos); sym := sSemicolon end; + ',': begin inc(cur.pos); sym := sComma end; + '.': begin + inc(cur.pos); + if cur.buf[cur.pos] = '.' then begin + inc(cur.pos); + if cur.buf[cur.pos] = '.' then begin inc(cur.pos); sym := sEllipsis end + else sym := sUpto; + end else sym := sPeriod; + end; + '(': begin inc(cur.pos); sym := sLparen end; + ')': begin inc(cur.pos); sym := sRparen end; + '[': begin inc(cur.pos); sym := sLbrak end; + ']': begin inc(cur.pos); sym := sRbrak end; + '{': begin inc(cur.pos); sym := sLbrace end; + '}': begin inc(cur.pos); sym := sRbrace end; + '^': begin inc(cur.pos); sym := sArrow end; + '|': begin inc(cur.pos); sym := sBar end; + #0: begin + if cur.pos < cur.len then Mark('NUL character'); + sym := sEof; + end; + else + if byte(c) >= $80 then + Mark('text outside strings, characters and comments must be ASCII'); + Mark('unexpected character'); + end; +end; + +var i: longint; + +initialization + poolCap := 1 shl 16; + pool := GetMem(poolCap); + nameCap := 1 shl 12; + nameOff := GetMem(nameCap * 4); + nameLen := GetMem(nameCap * 4); + nameHash := GetMem(nameCap * 4); + tableMask := 2 * nameCap - 1; + table := GetMem((tableMask + 1) * 4); + FillChar(table^, (tableMask + 1) * 4, 0); + for i := 0 to NumWords - 1 do Intern(@Words[i][1], length(Words[i])); +end. diff --git a/src/sym.pas b/src/sym.pas new file mode 100644 index 0000000..07b9899 --- /dev/null +++ b/src/sym.pas @@ -0,0 +1,455 @@ +{ sym.pas: types, objects and scopes. + + Every name the program declares becomes an object (TObj): a constant, + type, variable, procedure, module, record field, variant case or + built-in. Every type is a TType. Objects are found through one hash + table keyed by scope and name, so a lookup costs the same however + big a module grows. A scope is just a number: the universe is 0, + and each module, procedure, record and match arm gets a fresh one. + + Depends on: scan, for names and errors. + Leaves out: code. Where a variable lives is decided here (frame + offsets, chunk numbers), but nothing is emitted. } + +unit sym; + +{$mode objfpc}{$H-} + +interface + +uses scan; + +type + TForm = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray, + fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError); + { fConst is the type of an untyped integer constant; fStr of a string + literal, whose length the literal carries } + + TClass = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin); + + PType = ^TType; + PObj = ^TObj; + PModule = ^TModule; + PImport = ^TImport; + + TType = record + form: TForm; + size, align: int64; + signed: boolean; { fInt } + vol: boolean; { fPtr: ^VOLATILE } + packd: boolean; { fRecord } + variadic: boolean; { fProc: ends in ... } + base: PType; { fPtr, fArray, fSlice: what it holds; fProc: result } + len: int64; { fArray: elements; fProc: parameters; fVariant: cases } + fields: PObj; { fRecord: fields; fVariant: cases; fProc: parameters } + scope: longint; { fRecord: the scope of its fields } + fwd: longint; { fPtr whose base isn't declared yet: its name, else -1 } + obj: PObj; { the declaration that names it, or nil } + module: PModule; { the module that built it } + end; + + TObj = record + cls: TClass; + name: longint; + exported: boolean; + typ: PType; + next: PObj; { the next in its list: scope, fields, parameters } + scope: longint; { where it is declared } + val: int64; { oConst: value; oBuiltin: which; oCase: tag; + oField: offset; oVar: frame offset } + chunk: longint; { global oVar, oProc, string oConst: its chunk } + lev: integer; { oVar: 0 for a module variable, 1 for a local } + ind: boolean; { oVar: the frame slot holds the variable's address } + off: int64; { oVar with ind: added to that address } + isVar: boolean; { a var parameter } + fwd: boolean; { oProc: declared forward, no body yet } + isCode: boolean; { oProc: a code procedure } + fields: PObj; { oCase: its fields } + module: PModule; { oModule: the module; others: where declared } + end; + + TImport = record + module: PModule; + next: PImport; + end; + + TModule = record + name: longint; + scope: longint; + path: shortstring; + first, last: PObj; { its top-level declarations, in order } + imports: PImport; + body: longint; { the chunk of its body, or -1 } + done: boolean; { compiled to the end } + checkOnly: boolean; { read only to check another file's interface } + next: PModule; { modules in the order they were finished } + end; + +const + { built-in procedures } + bSize = 0; bAdr = 1; bLen = 2; bNew = 3; bMsg = 4; bSyscall = 5; + bFence = 6; bCas = 7; bXchg = 8; bXadd = 9; bArgc = 10; bArgv = 11; + +var + tI8, tI16, tI32, tI64, tU8, tU16, tU32, tU64: PType; + tBool, tReal, tConst, tNil, tStr, tNone, tPtrU8: PType; + curModule: PModule; + +function NewType(form: TForm; size, align: int64): PType; +function NewObj(cls: TClass; name: longint; typ: PType): PObj; +function NewScope: longint; +procedure OpenScope(s: longint); +procedure CloseScope; +function TopScope: longint; +procedure Insert(obj: PObj; s: longint); +function Find(s, name: longint): PObj; +function Lookup(name: longint): PObj; + +function AlignUp(x, a: int64): int64; +function Same(a, b: PType): boolean; +function IsInt(t: PType): boolean; +function IsScalar(t: PType): boolean; +function IsAggregate(t: PType): boolean; +function Fits(v: int64; t: PType): boolean; +function TypeName(t: PType): shortstring; +function SameAcross(a, b: PType; ma, mb: PModule): boolean; +function SameSig(a, b: PType; ma, mb: PModule): boolean; + +implementation + +const + MaxDepth = 64; + +type + PObjTab = ^TObjTab; + TObjTab = array[0..MaxInt div 16] of PObj; + +var + scopes: array[0..MaxDepth - 1] of longint; + depth: longint; + nextScope: longint; + hashTab: PObjTab; + hashMask, hashCount: longint; + +function NewType(form: TForm; size, align: int64): PType; +var t: PType; +begin + New(t); + FillChar(t^, SizeOf(TType), 0); + t^.form := form; + t^.size := size; + t^.align := align; + t^.fwd := -1; + t^.module := curModule; + NewType := t; +end; + +function NewObj(cls: TClass; name: longint; typ: PType): PObj; +var o: PObj; +begin + New(o); + FillChar(o^, SizeOf(TObj), 0); + o^.cls := cls; + o^.name := name; + o^.typ := typ; + o^.chunk := -1; + o^.module := curModule; + NewObj := o; +end; + +{ Scopes } + +function NewScope: longint; +begin + inc(nextScope); + NewScope := nextScope; +end; + +procedure OpenScope(s: longint); +begin + if depth = MaxDepth then Mark('nested too deeply'); + scopes[depth] := s; + inc(depth); +end; + +procedure CloseScope; +begin + dec(depth); +end; + +function TopScope: longint; +begin + TopScope := scopes[depth - 1]; +end; + +function Slot(s, name: longint): longint; +begin + Slot := longint((longword(s) * 2654435761 xor longword(name) * 40503) and longword(hashMask)); +end; + +procedure Rehash; +var old: PObjTab; n, i, j: longint; +begin + old := hashTab; + n := hashMask + 1; + hashMask := n * 2 - 1; + hashTab := GetMem(n * 2 * SizeOf(PObj)); + FillChar(hashTab^, n * 2 * SizeOf(PObj), 0); + for i := 0 to n - 1 do + if old^[i] <> nil then begin + j := Slot(old^[i]^.scope, old^[i]^.name); + while hashTab^[j] <> nil do j := (j + 1) and hashMask; + hashTab^[j] := old^[i]; + end; + FreeMem(old); +end; + +procedure Insert(obj: PObj; s: longint); +var i: longint; o: PObj; +begin + i := Slot(s, obj^.name); + o := hashTab^[i]; + while o <> nil do begin + if (o^.scope = s) and (o^.name = obj^.name) then + Mark(NameOf(obj^.name) + ' is declared twice'); + i := (i + 1) and hashMask; + o := hashTab^[i]; + end; + obj^.scope := s; + hashTab^[i] := obj; + inc(hashCount); + if hashCount * 2 > hashMask then Rehash; +end; + +function Find(s, name: longint): PObj; +var i: longint; o: PObj; +begin + i := Slot(s, name); + o := hashTab^[i]; + while o <> nil do begin + if (o^.scope = s) and (o^.name = name) then exit(o); + i := (i + 1) and hashMask; + o := hashTab^[i]; + end; + Find := nil; +end; + +function Lookup(name: longint): PObj; +var i: longint; o: PObj; +begin + for i := depth - 1 downto 0 do begin + o := Find(scopes[i], name); + if o <> nil then exit(o); + end; + Lookup := nil; +end; + +{ Types } + +function AlignUp(x, a: int64): int64; +begin + AlignUp := (x + a - 1) div a * a; +end; + +function IsInt(t: PType): boolean; +begin + IsInt := t^.form in [fInt, fConst]; +end; + +function IsScalar(t: PType): boolean; +begin + IsScalar := t^.form in [fBool, fInt, fReal, fConst, fNil, fPtr, fProc, + fEnum, fSet, fError]; +end; + +function IsAggregate(t: PType): boolean; +begin + IsAggregate := t^.form in [fArray, fSlice, fRecord, fVariant]; +end; + +function Fits(v: int64; t: PType): boolean; +begin + if t^.form <> fInt then exit(t^.form = fConst); + case t^.size of + 1: if t^.signed then Fits := (v >= -128) and (v <= 127) + else Fits := (v >= 0) and (v <= 255); + 2: if t^.signed then Fits := (v >= -32768) and (v <= 32767) + else Fits := (v >= 0) and (v <= 65535); + 4: if t^.signed then Fits := (v >= -2147483648) and (v <= 2147483647) + else Fits := (v >= 0) and (v <= 4294967295); + else + { an untyped constant is 64 bits; one with the top bit set came from + a hex literal, and stands for a U64 above high(I64) } + Fits := true; + end; +end; + +{ Structural sameness of two types. Named types are the same only if + they are one declaration; a type with no name is the same as another + built alike. } +function Alike(a, b: PType): boolean; +var p, q: PObj; +begin + if a = b then exit(true); + if a^.form <> b^.form then exit(false); + case a^.form of + fPtr: Alike := (a^.vol = b^.vol) and Same(a^.base, b^.base); + fArray: Alike := (a^.len = b^.len) and Same(a^.base, b^.base); + fSlice: Alike := Same(a^.base, b^.base); + fProc: begin + if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false); + if (a^.base = nil) <> (b^.base = nil) then exit(false); + if (a^.base <> nil) and not Same(a^.base, b^.base) then exit(false); + p := a^.fields; q := b^.fields; + while p <> nil do begin + if (p^.isVar <> q^.isVar) or not Same(p^.typ, q^.typ) then exit(false); + p := p^.next; q := q^.next; + end; + Alike := true; + end; + else Alike := false; + end; +end; + +function Same(a, b: PType): boolean; +begin + if a = b then exit(true); + if (a = nil) or (b = nil) then exit(false); + if (a^.obj <> nil) and (b^.obj <> nil) then exit(false); + Same := Alike(a, b); +end; + +function TypeName(t: PType): shortstring; +var s: shortstring; +begin + if t = nil then exit('nothing'); + if t^.obj <> nil then begin + if (t^.obj^.module <> nil) and (t^.obj^.module <> curModule) then + exit(NameOf(t^.obj^.module^.name) + '.' + NameOf(t^.obj^.name)); + exit(NameOf(t^.obj^.name)); + end; + case t^.form of + fConst: TypeName := 'an integer constant'; + fNil: TypeName := 'nil'; + fStr: TypeName := 'a string'; + fPtr: if t^.vol then TypeName := '^VOLATILE ' + TypeName(t^.base) + else TypeName := '^' + TypeName(t^.base); + fArray: begin Str(t^.len, s); TypeName := '[' + s + ']' + TypeName(t^.base) end; + fSlice: TypeName := '[]' + TypeName(t^.base); + fRecord: TypeName := 'record'; + fVariant: TypeName := 'variant'; + fProc: TypeName := 'proc'; + else TypeName := '?'; + end; +end; + +{ The interface check: types of two files of one module, where a type + declared in one file stands for the type of the same name in the + other. } +function SameAcross(a, b: PType; ma, mb: PModule): boolean; +var p, q: PObj; +begin + if a = b then exit(true); + if (a = nil) or (b = nil) then exit(false); + if (a^.obj <> nil) or (b^.obj <> nil) then begin + if (a^.obj = nil) or (b^.obj = nil) then exit(false); + exit((a^.obj^.module = ma) and (b^.obj^.module = mb) + and (a^.obj^.name = b^.obj^.name)); + end; + if a^.form <> b^.form then exit(false); + case a^.form of + fPtr: SameAcross := (a^.vol = b^.vol) and SameAcross(a^.base, b^.base, ma, mb); + fArray: SameAcross := (a^.len = b^.len) and SameAcross(a^.base, b^.base, ma, mb); + fSlice: SameAcross := SameAcross(a^.base, b^.base, ma, mb); + fProc: SameAcross := SameSig(a, b, ma, mb); + fRecord, fVariant: begin + { anonymous: every field, exported or not, in order } + p := a^.fields; q := b^.fields; + while (p <> nil) and (q <> nil) do begin + if (p^.name <> q^.name) or not SameAcross(p^.typ, q^.typ, ma, mb) then exit(false); + p := p^.next; q := q^.next; + end; + SameAcross := (p = nil) and (q = nil); + end; + else SameAcross := false; + end; +end; + +function SameSig(a, b: PType; ma, mb: PModule): boolean; +var p, q: PObj; +begin + if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false); + if (a^.base = nil) <> (b^.base = nil) then exit(false); + if (a^.base <> nil) and not SameAcross(a^.base, b^.base, ma, mb) then exit(false); + p := a^.fields; q := b^.fields; + while p <> nil do begin + if (p^.isVar <> q^.isVar) or not SameAcross(p^.typ, q^.typ, ma, mb) then exit(false); + p := p^.next; q := q^.next; + end; + SameSig := true; +end; + +{ The universe } + +function Basic(const name: shortstring; form: TForm; size: int64; signed: boolean): PType; +var t: PType; o: PObj; +begin + t := NewType(form, size, size); + t^.signed := signed; + o := NewObj(oType, Intern(@name[1], length(name)), t); + o^.exported := true; + t^.obj := o; + Insert(o, 0); + Basic := t; +end; + +procedure Enter(const name: shortstring; cls: TClass; t: PType; v: int64); +var o: PObj; +begin + o := NewObj(cls, Intern(@name[1], length(name)), t); + o^.val := v; + o^.exported := true; + Insert(o, 0); +end; + +initialization + hashMask := (1 shl 14) - 1; + hashTab := GetMem((hashMask + 1) * SizeOf(PObj)); + FillChar(hashTab^, (hashMask + 1) * SizeOf(PObj), 0); + depth := 1; + scopes[0] := 0; + nextScope := 0; + curModule := nil; + tI8 := Basic('I8', fInt, 1, true); + tI16 := Basic('I16', fInt, 2, true); + tI32 := Basic('I32', fInt, 4, true); + tI64 := Basic('I64', fInt, 8, true); + tU8 := Basic('U8', fInt, 1, false); + tU16 := Basic('U16', fInt, 2, false); + tU32 := Basic('U32', fInt, 4, false); + tU64 := Basic('U64', fInt, 8, false); + tBool := Basic('BOOL', fBool, 1, false); + tReal := Basic('F64', fReal, 8, false); + tConst := NewType(fConst, 8, 8); + tConst^.signed := true; + tNil := NewType(fNil, 8, 8); + tStr := NewType(fStr, 0, 1); + tNone := NewType(fNone, 0, 1); + tPtrU8 := NewType(fPtr, 8, 8); + tPtrU8^.base := tU8; + Enter('true', oConst, tBool, 1); + Enter('false', oConst, tBool, 0); + Enter('nil', oConst, tNil, 0); + Enter('SIZE', oBuiltin, nil, bSize); + Enter('ADR', oBuiltin, nil, bAdr); + Enter('LEN', oBuiltin, nil, bLen); + Enter('NEW', oBuiltin, nil, bNew); + Enter('MSG', oBuiltin, nil, bMsg); + Enter('SYSCALL', oBuiltin, nil, bSyscall); + Enter('FENCE', oBuiltin, nil, bFence); + Enter('CAS', oBuiltin, nil, bCas); + Enter('XCHG', oBuiltin, nil, bXchg); + Enter('XADD', oBuiltin, nil, bXadd); + Enter('ARGC', oBuiltin, nil, bArgc); + Enter('ARGV', oBuiltin, nil, bArgv); +end. diff --git a/test/scantest.pas b/test/scantest.pas new file mode 100644 index 0000000..4c65137 --- /dev/null +++ b/test/scantest.pas @@ -0,0 +1,19 @@ +{ Prints the symbols of a file, one per line: a test of scan.pas. } +program scantest; +{$mode objfpc}{$H-} +uses scan; +var i: longint; +begin + if not Open(ParamStr(1)) then Fatal('no file'); + repeat + Next; + write(Where, ' ', ord(sym)); + case sym of + sIdent: write(' ', NameOf(id)); + sInt, sChar: write(' ', ival); + sReal: write(' ', rval:0:6); + sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end; + end; + writeln; + until sym = sEof; +end.