Skip to content

Commit

Permalink
Merge pull request #5 from timothyhinrichs/master
Browse files Browse the repository at this point in the history
Add parser test
  • Loading branch information
timothyhinrichs committed Jan 4, 2016
2 parents f260b79 + cecbc34 commit b141c04
Show file tree
Hide file tree
Showing 6 changed files with 1,389 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .travis.yml
@@ -1,2 +1,4 @@
language: go

install: ./install-deps-gen-code.sh

10 changes: 10 additions & 0 deletions install-deps-gen-code.sh
@@ -0,0 +1,10 @@
#!/usr/bin/env sh

# install dependencies
go get -u github.com/PuerkitoBio/pigeon
go get golang.org/x/tools/cmd/goimports

# generate source code for parser
pigeon src/jsonlog/jsonlog.peg | goimports > src/jsonlog/parser.go


80 changes: 80 additions & 0 deletions src/jsonlog/jsonlog.peg
@@ -0,0 +1,80 @@
// Copyright 2015 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.

{

package jsonlog

// part of the initializer code block omitted for brevity

var ops = map[string]func(int, int) int {
"+": func(l, r int) int {
return l + r
},
"-": func(l, r int) int {
return l - r
},
"*": func(l, r int) int {
return l * r
},
"/": func(l, r int) int {
return l / r
},
}

func toIfaceSlice(v interface{}) []interface{} {
if v == nil {
return nil
}
return v.([]interface{})
}

func eval(first, rest interface{}) int {
l := first.(int)
restSl := toIfaceSlice(rest)
for _, v := range restSl {
restExpr := toIfaceSlice(v)
r := restExpr[3].(int)
op := restExpr[1].(string)
l = ops[op](l, r)
}
return l
}
}


Input <- expr:Expr EOF {
return expr, nil
}

Expr <- _ first:Term rest:( _ AddOp _ Term )* _ {
return eval(first, rest), nil
}

Term <- first:Factor rest:( _ MulOp _ Factor )* {
return eval(first, rest), nil
}

Factor <- '(' expr:Expr ')' {
return expr, nil
} / integer:Integer {
return integer, nil
}

AddOp <- ( '+' / '-' ) {
return string(c.text), nil
}

MulOp <- ( '*' / '/' ) {
return string(c.text), nil
}

Integer <- '-'? [0-9]+ {
return strconv.Atoi(string(c.text))
}

_ "whitespace" <- [ \n\t\r]*

EOF <- !.

0 comments on commit b141c04

Please sign in to comment.