From b8441c2f0564dfd3989ab07c622850d576968218 Mon Sep 17 00:00:00 2001 From: MilkeeyCat Date: Sun, 14 Jul 2024 23:18:48 +0300 Subject: [PATCH] fix(codegen): unary expression --- src/codegen/codegen.rs | 43 +++++++++++++++++------------------------- src/parser/parser.rs | 11 +---------- 2 files changed, 18 insertions(+), 36 deletions(-) diff --git a/src/codegen/codegen.rs b/src/codegen/codegen.rs index 99af54a..adfb70d 100644 --- a/src/codegen/codegen.rs +++ b/src/codegen/codegen.rs @@ -142,14 +142,12 @@ impl CodeGen { match expr { Expr::Binary(bin_expr) => self.bin_expr(bin_expr, dest), Expr::Lit(lit) => Ok(self.arch.mov(MoveSource::Lit(lit), dest, &self.scope)), - Expr::Unary(unary_expr) => self.unary_expr(unary_expr), + Expr::Unary(unary_expr) => self.unary_expr(unary_expr, dest), Expr::Ident(ident) => { - let r = self.arch.alloc()?; let symbol = self.scope.find_symbol(&ident).unwrap(); - self.arch.mov(symbol.into(), (&r).into(), &self.scope); + self.arch.mov(symbol.into(), dest, &self.scope); - //NOTE: data in r Ok(()) } Expr::Cast(cast_expr) => { @@ -168,12 +166,7 @@ impl CodeGen { } expr => expr, }; - - let r = self.arch.alloc()?; - - self.expr(expr, (&r).into())?; - - //NOTE: data in `r` + self.expr(expr, dest)?; Ok(()) } @@ -272,28 +265,26 @@ impl CodeGen { } } - fn unary_expr(&mut self, unary_expr: ExprUnary) -> Result<(), CodeGenError> { + fn unary_expr( + &mut self, + unary_expr: ExprUnary, + dest: MoveDestination, + ) -> Result<(), CodeGenError> { match unary_expr.op { UnOp::Negative => { - let r = self.arch.alloc()?; - self.expr(*unary_expr.expr, (&r).into())?; - self.arch.negate(&r); - - Ok(()) - //Ok(r) + self.expr(*unary_expr.expr, dest.clone())?; + self.arch.negate(dest.register().unwrap()); } UnOp::Not => { - let r1 = self.arch.alloc()?; - let r2 = self.arch.alloc()?; - self.expr(*unary_expr.expr, (&r1).into())?; - - self.arch.not(&r1, &r2); - self.arch.free(r1)?; + let r = self.arch.alloc()?; - //NOTE: value in r2 - Ok(()) + self.expr(*unary_expr.expr, (&r).into())?; + self.arch.not(&r, dest.register().unwrap()); + self.arch.free(r)?; } - } + }; + + Ok(()) } fn call_function(&mut self, call: ExprFunctionCall) -> Result<(), CodeGenError> { diff --git a/src/parser/parser.rs b/src/parser/parser.rs index 033b7e3..db84a8a 100644 --- a/src/parser/parser.rs +++ b/src/parser/parser.rs @@ -530,16 +530,7 @@ impl Parser { fn unary_expr(&mut self) -> Result { let op = UnOp::try_from(&self.next_token()?).map_err(|e| ParserError::Operator(e))?; - let mut expr = self.expr(Precedence::Prefix)?; - - if let UnOp::Negative = op { - if let Expr::Lit(ExprLit::UInt(uint_repr)) = expr { - let mut int_repr = IntLitRepr::try_from(uint_repr).unwrap(); - int_repr.negate(); - - expr = Expr::Lit(ExprLit::Int(int_repr)) - } - } + let expr = self.expr(Precedence::Prefix)?; Ok(Expr::Unary(ExprUnary::new(op, Box::new(expr)))) }