Skip to content

Commit

Permalink
fix(codegen): unary expression
Browse files Browse the repository at this point in the history
  • Loading branch information
MilkeeyCat committed Jul 14, 2024
1 parent 427f574 commit b8441c2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 36 deletions.
43 changes: 17 additions & 26 deletions src/codegen/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,14 +142,12 @@ impl<Arch: Architecture> CodeGen<Arch> {
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) => {
Expand All @@ -168,12 +166,7 @@ impl<Arch: Architecture> CodeGen<Arch> {
}
expr => expr,
};

let r = self.arch.alloc()?;

self.expr(expr, (&r).into())?;

//NOTE: data in `r`
self.expr(expr, dest)?;

Ok(())
}
Expand Down Expand Up @@ -272,28 +265,26 @@ impl<Arch: Architecture> CodeGen<Arch> {
}
}

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> {
Expand Down
11 changes: 1 addition & 10 deletions src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,16 +530,7 @@ impl Parser {

fn unary_expr(&mut self) -> Result<Expr, ParserError> {
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))))
}
Expand Down

0 comments on commit b8441c2

Please sign in to comment.