Skip to content

Commit

Permalink
Merge pull request #2095 from xushiwei/q
Browse files Browse the repository at this point in the history
demo: gop-parser/gopcalc
  • Loading branch information
xushiwei authored Feb 5, 2025
2 parents 5d6583e + 5bf9df9 commit 3d37fda
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 3 deletions.
8 changes: 5 additions & 3 deletions cl/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -1053,10 +1053,12 @@ func compileStringLitEx(ctx *blockCtx, cb *gogen.CodeBuilder, lit *ast.BasicLit)
t := cb.Get(-1).Type
if t.Underlying() != types.Typ[types.String] {
if _, err := cb.Member("string", gogen.MemberFlagAutoProperty); err != nil {
if e, ok := err.(*gogen.CodeError); ok {
err = ctx.newCodeErrorf(v.Pos(), "%s.string%s", ctx.LoadExpr(v), e.Msg)
if _, e2 := cb.Member("error", gogen.MemberFlagAutoProperty); e2 != nil {
if e, ok := err.(*gogen.CodeError); ok {
err = ctx.newCodeErrorf(v.Pos(), "%s.string%s", ctx.LoadExpr(v), e.Msg)
}
ctx.handleErr(err)
}
ctx.handleErr(err)
}
}
pos = v.End()
Expand Down
52 changes: 52 additions & 0 deletions demo/gop-parser/gopcalc/calc.gop
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> "
}
}
7 changes: 7 additions & 0 deletions demo/gop-parser/parser.gop
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.

0 comments on commit 3d37fda

Please sign in to comment.