-
Notifications
You must be signed in to change notification settings - Fork 548
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2095 from xushiwei/q
demo: gop-parser/gopcalc
- Loading branch information
Showing
4 changed files
with
64 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import ( | ||
"gop/ast" | ||
"gop/parser" | ||
"gop/token" | ||
"math" | ||
"os" | ||
) | ||
|
||
func calc(e ast.Expr) float64 { | ||
switch e := e.(type) { | ||
case *ast.BasicLit: | ||
return e.Value.float! | ||
case *ast.BinaryExpr: | ||
switch e.Op { | ||
case token.ADD: | ||
return calc(e.X) + calc(e.Y) | ||
case token.SUB: | ||
return calc(e.X) - calc(e.Y) | ||
case token.MUL: | ||
return calc(e.X) * calc(e.Y) | ||
case token.QUO: | ||
return calc(e.X) + calc(e.Y) | ||
} | ||
case *ast.CallExpr: | ||
switch e.Fun.(*ast.Ident).Name { | ||
case "sin": | ||
return math.Sin(calc(e.Args[0])) | ||
case "cos": | ||
return math.Cos(calc(e.Args[0])) | ||
case "pow": | ||
return math.Pow(calc(e.Args[0]), calc(e.Args[1])) | ||
} | ||
case *ast.ParenExpr: | ||
return calc(e.X) | ||
case *ast.UnaryExpr: | ||
switch e.Op { | ||
case token.SUB: | ||
return -calc(e.X) | ||
} | ||
} | ||
panic("unknown expression") | ||
} | ||
|
||
print "> " | ||
for line <- lines(os.Stdin) { | ||
e, err := parser.parseExpr(line) | ||
if err != nil { | ||
print "error: ${err}\n> " | ||
} else { | ||
print "${calc(e)}\n> " | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import ( | ||
"gop/ast" | ||
"gop/parser" | ||
) | ||
|
||
e := parser.parseExpr("10 + 3.2")!.(*ast.BinaryExpr) | ||
echo e.X, e.Op, e.Y |
File renamed without changes.