def visitExpr(self, ctx:DecafParser.ExprContext): # Expression is a variable. if ctx.location(): var_name = ctx.location().getText() var_symbol = self.st.lookup(var_name) if "[" in var_name: split_var = var_name.split('[', 1)[0] var_symbol = self.st.lookup(split_var) if var_symbol == None: print('[Error]: Variable', var_name, 'has not been declared. Found on line', ctx.start.line) else: var_addr = var_symbol.getAddr() self.body += '\tmovq -' + str(var_addr[0]) + '(%rsp), %rax\n' # Expression is a literal (number or string/char) elif ctx.literal(): number = ctx.literal().getText() if number == 'false': number = '0' if number == 'true': number = '1' self.body += '\tmovq $' + number + ', %rax\n' # Expression length is more than 1 (more expressions present such as an operation) elif len(ctx.expr()) > 1: # Visit the first expression. self.visit(ctx.expr(0)) # Move stack pointer 1 place and save value of first expression. self.st.stack_pointer[-1] += 8 self.body += '\tmovq %rax, ' + str(-self.st.stack_pointer[-1]) + '(%rsp)\n' # Visit the second expression. self.visit(ctx.expr(1)) self.body += '\tmovq ' + str(-self.st.stack_pointer[-1]) + '(%rsp), %r10\n' self.st.stack_pointer[-1] -= 8 self.body += '\tmovq %rax, %r11\n' # If a binary operator is present, check the operator and add appropriate code. if ctx.BIN_OP(): if str(ctx.BIN_OP()) == '+': self.body += '\taddq %r10, %r11\n' if str(ctx.BIN_OP()) == '*': self.body += '\timul %r10, %r11\n' if str(ctx.BIN_OP()) == '-': self.body += '\tsubq %r10, %r11\n' if str(ctx.BIN_OP()) == '/': self.body += '\tmovq $0, rdx\n' self.body += '\tmovq %r11, rbx\n' self.body += '\tmovq %r10, rax\n' self.body += '\tidiv %rbx\n' self.body += '\tmovq %r11, %rax\n'
def visitExpr(self, ctx: DecafParser.ExprContext): if ctx.literal(): int_literal = ctx.getText() self.body += 'movq $' + int_literal + ', %rax\n' elif ctx.location(): loc_name = ctx.getText() location = self.st.lookup(loc_name) addr = str(location.getAddr()) if location.mem == HEAP: self.body += 'movq ' + addr + '(%rbp), %rax\n' else: self.body += 'movq ' + addr + '(%rsp), %rax\n' else: self.visitChildren(ctx)