14.4. Allocating Storage

In other programs like this one, including the TINY compiler itself, we have already addressed the issue of declaring global variables, and the code generated for them. Let's build a vestigial version of a "compiler" here, whose only function is to allow us declare variables. Remember, the syntax for a declaration is:

<data decl> ::= VAR <identifier>

Again, we can lift a lot of the code from previous programs. The following are stripped-down versions of those procedures. They are greatly simplified since I have eliminated niceties like variable lists and initializers. In procedure Alloc, note that the new call to AddEntry will also take care of checking for duplicate declarations:

{ Allocate Storage for a Variable }
procedure Alloc(N: char);
begin
   AddEntry(N, 'v');
   WriteLn(N, ':', TAB, 'DC 0');
end;

{ Parse and Translate a Data Declaration }
procedure Decl;
var Name: char;
begin
   Match('v');
   Alloc(GetName);
end;

{ Parse and Translate Global Declarations }
procedure TopDecls;
begin
   while Look <> '.' do begin
      case Look of
        'v': Decl;
      else Abort('Unrecognized Keyword ' + Look);
      end;
      Fin;
   end;
end;

Now, in the main program, add a call to TopDecls and run the program. Try allocating a few variables, and note the resulting code generated. This is old stuff for you, so the results should look familiar. Note from the code for TopDecls that the program is ended by a terminating period.

While you're at it, try declaring two variables with the same name, and verify that the parser catches the error.