Skip to content

Commit

Permalink
Merge pull request #91 from x-tyger/do
Browse files Browse the repository at this point in the history
Implements do-while statement transpilation
  • Loading branch information
elliotchance authored May 9, 2017
2 parents 8a1b0dd + e169f01 commit 61f007f
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 3 deletions.
4 changes: 2 additions & 2 deletions ast/do_stmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package ast
type DoStmt struct {
Address string
Position string
Children []interface{}
Children []Node
}

func parseDoStmt(line string) *DoStmt {
Expand All @@ -15,7 +15,7 @@ func parseDoStmt(line string) *DoStmt {
return &DoStmt{
Address: groups["address"],
Position: groups["position"],
Children: []interface{}{},
Children: []Node{},
}
}

Expand Down
2 changes: 1 addition & 1 deletion ast/do_stmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ func TestDoStmt(t *testing.T) {
`0x7ff36d0a0938 <line:11:5, line:14:23>`: &DoStmt{
Address: "0x7ff36d0a0938",
Position: "line:11:5, line:14:23",
Children: []interface{}{},
Children: []Node{},
},
}

Expand Down
10 changes: 10 additions & 0 deletions tests/do.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#include <stdio.h>

int main() {
int i = 0;

do {
printf("do loop %d\n", i);
i = i + 1;
} while( i < 4 );
}
29 changes: 29 additions & 0 deletions transpiler/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,32 @@ func transpileWhileStmt(n *ast.WhileStmt, p *program.Program) (*goast.ForStmt, e
Body: body,
}, nil
}

func transpileDoStmt(n *ast.DoStmt, p *program.Program) (*goast.ForStmt, error) {
children := n.Children

body, err := transpileToBlockStmt(children[0], p)
if err != nil {
return nil, err
}

condition, conditionType, err := transpileToExpr(children[1], p)
if err != nil {
return nil, err
}

// Add IfStmt to the end of the loop to check the condition
body.List = append(body.List, &goast.IfStmt{
Cond: &goast.UnaryExpr{
Op: token.NOT,
X: types.CastExpr(p, condition, conditionType, "bool"),
},
Body: &goast.BlockStmt{
List: []goast.Stmt{&goast.BranchStmt{Tok: token.BREAK}},
},
})

return &goast.ForStmt{
Body: body,
}, nil
}
3 changes: 3 additions & 0 deletions transpiler/transpiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ func transpileToStmt(node ast.Node, p *program.Program) (goast.Stmt, error) {
case *ast.WhileStmt:
return transpileWhileStmt(n, p)

case *ast.DoStmt:
return transpileDoStmt(n, p)

case *ast.IfStmt:
return transpileIfStmt(n, p)

Expand Down

0 comments on commit 61f007f

Please sign in to comment.