К этому моменту мы полностью определили TINY. Он не слишком значителен... в действительности игрушечный компилятор. TINY имеет только один тип данных и не имеет подпрограмм... но это законченный, пригодный для использования язык. Пока что вы не имеете возможности написать на нем другой компилятор или сделать что-нибудь еще очень серьезное, но вы могли бы писать программы для чтения входных данных, выполнения вычислений и вывода результатов. Не слишком плохо для игрушки.
Более важно, что мы имеем твердую основу для дальнейшего развития. Я знаю, что вы будете рады слышать это: в последний раз я начал с создания синтаксического анализатора заново... с этого момента я предполагаю просто добавлять возможности в TINY пока он не превратится в KISS. Ох, будет время, когда нам понадобится попробовать некоторые вещи с новыми копиями Cradle, но как только мы разузнаем как они делаются, они будут встроены в TINY.
Какие это будут возможности? Хорошо, для начала нам понадобятся подпрограммы и функции. Затем нам нужна возможность обрабатывать различные типы, включая массивы, строки и другие структуры. Затем нам нужно работать с идеей указателей. Все это будет в следующих главах.
Увидимся.
В справочных целях полный листинг TINY версии 1.0 показан ниже:
function Lookup(T: TabPtr; s: string; n: integer): integer; var i: integer; found: Boolean; begin found := false; i := n; while (i > 0) and not found do if s = T^[i] then found := true else dec(i); Lookup := i; end;
{--------------------------------------------------------------} { Locate a Symbol in Table } { Returns the index of the entry. Zero if not present. }
function Locate(N: Symbol): integer; begin Locate := Lookup(@ST, n, MaxEntry); end;
{--------------------------------------------------------------} { Look for Symbol in Table }
function InTable(n: Symbol): Boolean; begin InTable := Lookup(@ST, n, MaxEntry) <> 0; end;
{--------------------------------------------------------------} { Add a New Entry to Symbol Table }
procedure AddEntry(N: Symbol; T: char); begin if InTable(N) then Abort('Duplicate Identifier ' + N); if NEntry = MaxEntry then Abort('Symbol Table Full'); Inc(NEntry); ST[NEntry] := N; SType[NEntry] := T; end;
{--------------------------------------------------------------} { Get an Identifier }
procedure GetName; begin NewLine; if not IsAlpha(Look) then Expected('Name'); Value := ''; while IsAlNum(Look) do begin Value := Value + UpCase(Look); GetChar; end; SkipWhite; end;
{--------------------------------------------------------------} { Get a Number }
function GetNum: integer; var Val: integer; begin NewLine; if not IsDigit(Look) then Expected('Integer'); Val := 0; while IsDigit(Look) do begin Val := 10 * Val + Ord(Look) - Ord('0'); GetChar; end; GetNum := Val; SkipWhite; end;
{--------------------------------------------------------------} { Get an Identifier and Scan it for Keywords }
{---------------------------------------------------------------} { Read Variable to Primary Register }
procedure ReadVar; begin EmitLn('BSR READ'); Store(Value[1]); end;
{ Write Variable from Primary Register }
procedure WriteVar; begin EmitLn('BSR WRITE'); end;
{--------------------------------------------------------------} { Write Header Info }
procedure Header; begin WriteLn('WARMST', TAB, 'EQU $A01E'); end;
{--------------------------------------------------------------} { Write the Prolog }
procedure Prolog; begin PostLabel('MAIN'); end;
{--------------------------------------------------------------} { Write the Epilog }
procedure Epilog; begin EmitLn('DC WARMST'); EmitLn('END MAIN'); end;
{---------------------------------------------------------------} { Parse and Translate a Math Factor }
procedure BoolExpression; Forward;
procedure Factor; begin if Look = '(' then begin Match('('); BoolExpression; Match(')'); end else if IsAlpha(Look) then begin GetName; LoadVar(Value); end else LoadConst(GetNum); end;
{--------------------------------------------------------------} { Parse and Translate a Negative Factor }
procedure NegFactor; begin Match('-'); if IsDigit(Look) then LoadConst(-GetNum) else begin Factor; Negate; end; end;
{--------------------------------------------------------------} { Parse and Translate a Leading Factor }
procedure FirstFactor; begin case Look of '+': begin Match('+'); Factor; end; '-': NegFactor; else Factor; end; end;
{--------------------------------------------------------------} { Recognize and Translate a Multiply }
procedure Multiply; begin Match('*'); Factor; PopMul; end;
{-------------------------------------------------------------} { Recognize and Translate a Divide }
procedure Divide; begin Match('/'); Factor; PopDiv; end;
{---------------------------------------------------------------} { Common Code Used by Term and FirstTerm }
procedure Term1; begin while IsMulop(Look) do begin Push; case Look of '*': Multiply; '/': Divide; end; end; end;
{---------------------------------------------------------------} { Parse and Translate a Math Term }
procedure Term; begin Factor; Term1; end;
{---------------------------------------------------------------} { Parse and Translate a Leading Term }
procedure FirstTerm; begin FirstFactor; Term1; end;
{--------------------------------------------------------------} { Recognize and Translate an Add }
procedure Add; begin Match('+'); Term; PopAdd; end;
{-------------------------------------------------------------} { Recognize and Translate a Subtract }
procedure Subtract; begin Match('-'); Term; PopSub; end;
{---------------------------------------------------------------} { Parse and Translate an Expression }
procedure Expression; begin FirstTerm; while IsAddop(Look) do begin Push; case Look of '+': Add; '-': Subtract; end; end; end;
{---------------------------------------------------------------} { Recognize and Translate a Relational "Equals" }
procedure Equal; begin Match('='); Expression; PopCompare; SetEqual; end;
{---------------------------------------------------------------} { Recognize and Translate a Relational "Less Than or Equal" }
procedure LessOrEqual; begin Match('='); Expression; PopCompare; SetLessOrEqual; end;
{---------------------------------------------------------------} { Recognize and Translate a Relational "Not Equals" }
procedure NotEqual; begin Match('>'); Expression; PopCompare; SetNEqual; end;
{---------------------------------------------------------------} { Recognize and Translate a Relational "Less Than" }
procedure Less; begin Match('<'); case Look of '=': LessOrEqual; '>': NotEqual; else begin Expression; PopCompare; SetLess; end; end; end;
{---------------------------------------------------------------} { Recognize and Translate a Relational "Greater Than" }
procedure Greater; begin Match('>'); if Look = '=' then begin Match('='); Expression; PopCompare; SetGreaterOrEqual; end else begin Expression; PopCompare; SetGreater; end; end;
{---------------------------------------------------------------} { Parse and Translate a Relation }
procedure Relation; begin Expression; if IsRelop(Look) then begin Push; case Look of '=': Equal; '<': Less; '>': Greater; end; end; end;
{---------------------------------------------------------------} { Parse and Translate a Boolean Factor with Leading NOT }
procedure NotFactor; begin if Look = '!' then begin Match('!'); Relation; NotIt; end else Relation; end;
{---------------------------------------------------------------} { Parse and Translate a Boolean Term }
procedure BoolTerm; begin NotFactor; while Look = '&' do begin Push; Match('&'); NotFactor; PopAnd; end; end;
{--------------------------------------------------------------} { Recognize and Translate a Boolean OR }
procedure BoolOr; begin Match('|'); BoolTerm; PopOr; end;
{--------------------------------------------------------------} { Recognize and Translate an Exclusive Or }
procedure BoolXor; begin Match('~'); BoolTerm; PopXor; end;
{---------------------------------------------------------------} { Parse and Translate a Boolean Expression }
procedure BoolExpression; begin BoolTerm; while IsOrOp(Look) do begin Push; case Look of '|': BoolOr; '~': BoolXor; end; end; end;
{--------------------------------------------------------------} { Parse and Translate an Assignment Statement }
procedure Assignment; var Name: string; begin Name := Value; Match('='); BoolExpression; Store(Name); end;
{---------------------------------------------------------------} { Recognize and Translate an IF Construct }
procedure Block; Forward;
procedure DoIf; var L1, L2: string; begin BoolExpression; L1 := NewLabel; L2 := L1; BranchFalse(L1); Block; if Token = 'l' then begin L2 := NewLabel; Branch(L2); PostLabel(L1); Block; end; PostLabel(L2); MatchString('ENDIF'); end;
{--------------------------------------------------------------} { Parse and Translate a WHILE Statement }
{--------------------------------------------------------------} { Process a Read Statement }
procedure DoRead; begin Match('('); GetName; ReadVar; while Look = ',' do begin Match(','); GetName; ReadVar; end; Match(')'); end;
{--------------------------------------------------------------} { Process a Write Statement }
procedure DoWrite; begin Match('('); Expression; WriteVar; while Look = ',' do begin Match(','); Expression; WriteVar; end; Match(')'); end;
{--------------------------------------------------------------} { Parse and Translate a Block of Statements }
procedure Block; begin Scan; while not(Token in ['e', 'l']) do begin case Token of 'i': DoIf; 'w': DoWhile; 'R': DoRead; 'W': DoWrite; else Assignment; end; Scan; end; end;
{--------------------------------------------------------------} { Allocate Storage for a Variable }
procedure Alloc(N: Symbol); begin if InTable(N) then Abort('Duplicate Variable Name ' + N); AddEntry(N, 'v'); Write(N, ':', TAB, 'DC '); if Look = '=' then begin Match('='); If Look = '-' then begin Write(Look); Match('-'); end; WriteLn(GetNum); end else WriteLn('0'); end;
{--------------------------------------------------------------} { Parse and Translate a Data Declaration }
procedure Decl; begin GetName; Alloc(Value); while Look = ',' do begin Match(','); GetName; Alloc(Value); end; end;
{--------------------------------------------------------------} { Parse and Translate Global Declarations }
procedure TopDecls; begin Scan; while Token <> 'b' do begin case Token of 'v': Decl; else Abort('Unrecognized Keyword ' + Value); end; Scan; end; end;
{--------------------------------------------------------------} { Parse and Translate a Main Program }
procedure Main; begin MatchString('BEGIN'); Prolog; Block; MatchString('END'); Epilog; end;
{--------------------------------------------------------------} { Parse and Translate a Program }
procedure Prog; begin MatchString('PROGRAM'); Header; TopDecls; Main; Match('.'); end;