Hey all, I have been stuck on this problem for weeks now. Basically I took a variation on Wirth's compiler and adding some more functionality to it. I needed to add FOR loop and CASE statement functionality to it.
I have the bulk of both of them done but when I input a test input file (labeled as 'valid.pas' in the code) it either hangs up when I run it or doesn't output anything.
here is the code for both statements. I have also attached the full compiler which can be compiled using any free pascal compiler. (**Just change from .txt to .pas**)
CASE Statement
casesym:begin
{ Code for CASE }
{counter declared as a global}
counter:=0;
getsym;
expression;
if sym <> ofsym then error(27);
getsym;
while sym <> cendsym do;
begin
getsym;
if sym <> constsym then error(29);
getsym;
counter := counter + 1; {count # of cases}
gen(CTS,0,0); {copy to top of stack}
gen(LIT,0,table[i].adr); {get value of const}
gen(OPR,0,8); {=}
cx1:=codeinx; {save codeinx}
gen(JPC,0,0);
if sym <> colon then error(39);
getsym;
statement;
if sym <> semicolon then error(17);
getsym;
if counter = 1 then
begin
cx2:=codeinx;
gen(JMP,0,0);
end
else
gen(JMP,0,cx2);
end;
{cend has been found}
code[cx2].ad:=codeinx;
gen(INT,0,-1); {get rid of copied value on stk }
end;
FOR Loop
forsym:begin
{ Code for FOR }
getsym;
if sym <> ident then error(11);
i:=position(id);
if i=0 then error(11);
if table[i].kind <> variable then error(37);
getsym;
if sym <> becomes then error(38);
getsym;
expression;
gen(STO,lev-table[i].level,table[i].adr);
if not (sym in [tosym, downtosym]) then error(11);
sym2:=sym; {store TO/DOWNTO}
getsym;
expression;
cx1:=codeinx;
{}
gen(STO,0,0);
gen(LOD,lev,table[i].adr);
if sym2=tosym then gen(OPR,0,12){to}
else
gen(OPR,0,13); {downto}
cx2:=codeinx;
gen(JPC,0,0);
{}
if sym <> dosym then error(18);
getsym;
statement;
gen(LOD,lev,table[i].adr);
gen(LIT,0,1);
if sym2=tosym then gen(OPR,0,2) {add}
else
gen(OPR,0,1);{subtract}
gen(STO,0,0);
gen(JMP,0,cx1); {jump back}
code[cx2].ad:=codeinx;
end;
Thanks for your help