(* Copyright (C) 1989, Digital Equipment Corporation *) (* All rights reserved. *) (* See the file COPYRIGHT for a full description. *) (* File: WhileStmt.m3 *) (* Last modified on Sat Feb 10 20:43:11 1990 by kalsow *) (* modified on Tue Oct 10 18:42:00 1989 by muller *) MODULE WhileStmt; IMPORT Expr, Type, Bool, Error, Emit, Marker; IMPORT Stmt, StmtRep, Token, Scanner, Temp, String; TYPE P = Stmt.T OBJECT cond : Expr.T; body : Stmt.T; METHODS bind := Bind; check := Check; precompile := Precompile; compile := Compile; END; VAR labelPrefix : String.T := NIL; nextID : INTEGER := 0; PROCEDURE Parse (READONLY fail: Token.Set): Stmt.T = TYPE TK = Token.T; VAR p: P; BEGIN p := NEW (P); StmtRep.Init (p); Scanner.Match (TK.tWHILE, fail, Token.Set {TK.tDO, TK.tEND}); p.cond := Expr.Parse (fail + Token.Set {TK.tDO, TK.tEND}); Scanner.Match (TK.tDO, fail, Token.Set {TK.tEND}); p.body := Stmt.Parse (fail + Token.Set {TK.tEND}); Scanner.Match (TK.tEND, fail, Token.Set {}); RETURN p; END Parse; PROCEDURE Bind (p: P) = BEGIN Expr.Bind (p.cond); Stmt.Bind (p.body); END Bind; PROCEDURE Check (p: P) = VAR t: Type.T; BEGIN Expr.TypeCheck (p.cond); t := Expr.TypeOf (p.cond); IF (Type.Base (t) # Bool.T) THEN Error.Msg ("WHILE condition must be a BOOLEAN"); END; Marker.PushExit (NIL, 0); Stmt.TypeCheck (p.body); Marker.Pop (); END Check; PROCEDURE Precompile (p: P) = BEGIN Marker.PushExit (NIL, 0); Stmt.Precompile (p.body); Marker.Pop (); END Precompile; PROCEDURE Compile (p: P): Stmt.Outcomes = VAR x: Temp.T; id: INTEGER; oc: Stmt.Outcomes; BEGIN id := nextID; INC (nextID); IF (labelPrefix = NIL) THEN labelPrefix := String.Add ("while_") END; x := Expr.Compile (p.cond); Emit.OpT ("if (@) do {\n\001", x); Temp.Free (x); Marker.PushExit (labelPrefix, id); oc := Stmt.Compile (p.body); Marker.Pop (); x := Expr.Compile (p.cond); Emit.OpT ("\002} while (@);\n", x); IF (Stmt.Outcome.Exits IN oc) THEN Emit.OpSI ("@@: /**/;\n", labelPrefix, id); oc := oc - Stmt.Outcomes {Stmt.Outcome.Exits} END; Temp.Free (x); (* A WHILE statement can always FallThrough; consider the case where the condition is initially FALSE *) RETURN oc + Stmt.Outcomes {Stmt.Outcome.FallThrough}; END Compile; BEGIN END WhileStmt.