import java.io.PrintWriter; import pal.*; /** * A simple implementation of Factorial in PAL. * * @author Samuel A. Rebelsky * @version 1.0 of November 2002 */ public class FactPAL { /* Base of memory: Globals +----------------+ | input | 0 +----------------+ | result | 1 +----------------+ ... Frame for factorial upon entry. +----------------+ | Return Add. | <- SP +----------------+ | Return Val. | +----------------+ | n (parameter) | +----------------+ ... +----------------+ | whatever | <- FP +----------------+ Frame for factorial after initialization +----------------+ | Old FP | <- FP, SP +----------------+ | Return Add. | +----------------+ | Return Val. | +----------------+ | n (parameter) | +----------------+ */ public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out,true); Computer hal = new Computer(1000); Container input = new MemLoc(new IConstant(0)); Container result = new MemLoc(new IConstant(1)); Label mainLabel = new Label("MAIN"); InstructionSequence factorial = new InstructionSequence(); Label facBase = new Label("BASE"); Label facRecurse = new Label("RECURSE"); Label facCleanup = new Label("CLEANUP"); factorial.add(new Label("FACTORIAL")); factorial.add(new Push(Register.fp)); factorial.add(new Move(Register.sp, Register.fp)); factorial.add(new Comment("If n = 0 Then"); factorial.add(new JumpZero(new Offset(Register.fp, 3), facBase)); factorial.add(new Jump(facRecurse)); factorial.add(facBase); factorial.add(new Comment("Factorial := 1"); factorial.add(new Jump(facCleanup)); factorial.add(facCleanup); factorial.add(new Move(Register.fp, Register.sp)); factorial.add(new Pop(Register.fp)); factorial.add(new Jump(new MemLoc(Register.sp))); InstructionSequence mainBody = new InstructionSequence(); InstructionSequence code = new InstructionSequence(); code.add(new Label("START")); code.add(new Jump(mainBody)); code.add(factorial); code.add(mainLabel); code.add(mainBody); code.add(new LABEL("END")); code.add(new Halt()); hal.setCode(code); out.println("----- DUMP -----"); hal.dump(out); // out.println("----- RUN ------"); // hal.run(true); } // main(String[]) } // class FactPAL