Exemplo n.º 1
0
 def gen(self, context: Context, target: str):
     """Translate 'while' loop into explicit jumps.
     """
     loop_head = context.new_label("loop")
     loop_exit = context.new_label("endloop")
     context.add_line("{}:  #While loop".format(loop_head))
     reg = context.alloc_reg()
     self.cond.gen(context, target=reg)
     # Is it zero?
     context.add_line("\tSUB  r0,{},r0 ".format(reg))
     context.add_line("\tJUMP/Z {}".format(loop_exit))
     context.free_reg(reg)
     self.expr.gen(context, target)
     context.add_line("\tJUMP {}".format(loop_head))
     context.add_line("{}: ".format(loop_exit))
Exemplo n.º 2
0
    def gen(self, context: Context, target: str):
        """
        Generate code for an if/else.
        """

        # The outline of the code you should generate is:
        # <code for expression>
        # subtract expression result from zero
        # if zero, jump to elsepart
        # <code for 'then' part>
        # jump to endif
        # elsepart:
        # <code for elsepart>
        # fi:
        # Generate fresh labels for the 'elsepart' and 'fi' each time,
        # since there could be more than one 'if' statement in a program.
        # Look at the 'while' statement above for examples of code
        # generation for tests, jumps, and labels.
        #
        # Example:
        # if 10 - 9:    --->   condition
        #    ------
        #   x = 5       --->   then
        # else:
        #   x = 0       --->   else

        # initialize labels and registers
        elsepart = context.new_label("else")
        fi = context.new_label("end else")
        reg = context.alloc_reg()
        self.cond.gen(context, target=reg)  # generate condition

        # If part
        # Is it zero?
        context.add_line("\tSUB  r0,{},r0 ".format(reg))
        context.add_line("\tJUMP/Z {}".format(elsepart))
        self.thenpart.gen(context, target)  # generate then part
        context.add_line("JUMP {}".format(fi))

        # Else part
        context.add_line("{}:  #Else loop".format(elsepart))
        self.elsepart.gen(context, target)  # generate else part
        context.add_line("{}".format(fi))
        context.free_reg(reg)  # free the register