Skip to content

Commit

Permalink
Rewrite assert statements.
Browse files Browse the repository at this point in the history
  • Loading branch information
dennwc committed Oct 16, 2022
1 parent 3d13e60 commit f05df98
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 3 deletions.
16 changes: 15 additions & 1 deletion bools.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,16 @@ const (

type BoolOp string

func (op BoolOp) Negate() BoolOp {
switch op {
case BinOpAnd:
return BinOpOr
case BinOpOr:
return BinOpAnd
}
panic(op)
}

func (op BoolOp) GoToken() token.Token {
var tok token.Token
switch op {
Expand Down Expand Up @@ -253,7 +263,11 @@ func (e *BinaryBoolExpr) HasSideEffects() bool {
}

func (e *BinaryBoolExpr) Negate() BoolExpr {
return &Not{X: e}
return &BinaryBoolExpr{
X: e.X.Negate(),
Op: e.Op.Negate(),
Y: e.Y.Negate(),
}
}

func (e *BinaryBoolExpr) Uses() []types.Usage {
Expand Down
8 changes: 6 additions & 2 deletions libs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ void foo(int a) {
`,
exp: `
func foo(a int32) {
libc.Assert(a != 0)
libc.Assert(a != 5)
if a == 0 {
panic("assert failed")
}
if a == 5 {
panic("assert failed")
}
panic(0)
panic("fail")
}
Expand Down
4 changes: 4 additions & 0 deletions literals.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,10 @@ func (l FloatLit) Uses() []types.Usage {
return nil
}

func (g *translator) stringLit(s string) StringLit {
return StringLit{typ: g.env.Go().String(), val: s}
}

func (g *translator) parseCStringLit(s string) (StringLit, error) {
return StringLit{typ: g.env.Go().String(), val: s}, nil
}
Expand Down
6 changes: 6 additions & 0 deletions postproc.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@ func (g *translator) rewriteStmt(st CStmt) (CStmt, bool) {
if len(c.Args) == 1 && canAssignTo(c.Args[0]) {
return g.NewCAssignStmtP(c.Args[0], "", g.Nil()), true
}
case g.env.C().AssertFunc():
if len(c.Args) == 1 {
return g.NewCIfStmt(g.cNot(c.Args[0]), NewCExprStmt(
&CallExpr{Fun: FuncIdent{g.env.Go().PanicFunc()}, Args: []Expr{g.stringLit("assert failed")}},
), nil), true
}
}
}
}
Expand Down

0 comments on commit f05df98

Please sign in to comment.