Skip to content

Commit 7fc3b4a

Browse files
authored
Merge pull request #2145 from xushiwei/q
#2143 gop/cl: compileDomainTextLit
2 parents 47f577f + bd534ac commit 7fc3b4a

File tree

4 files changed

+37
-11
lines changed

4 files changed

+37
-11
lines changed

cl/_testgop/domaintext/in.gop

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
cl, err := tpl`expr = INT % ("+" | "-")`
2+
cl.parseExpr "1+2", nil
3+
_ = err

cl/_testgop/domaintext/out.go

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package main
2+
3+
import "github.com/goplus/gop/tpl"
4+
5+
func main() {
6+
cl, err := tpl.New(`expr = INT % ("+" | "-")`)
7+
cl.ParseExpr("1+2", nil)
8+
_ = err
9+
}

cl/expr.go

+15
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,8 @@ func compileExpr(ctx *blockCtx, expr ast.Expr, inFlags ...int) {
387387
compileEnvExpr(ctx, v)
388388
/* case *ast.MatrixLit:
389389
compileMatrixLit(ctx, v) */
390+
case *ast.DomainTextLit:
391+
compileDomainTextLit(ctx, v)
390392
default:
391393
panic(ctx.newCodeErrorf(v.Pos(), "compileExpr failed: unknown - %T", v))
392394
}
@@ -1071,6 +1073,19 @@ func compileStringLitEx(ctx *blockCtx, cb *gogen.CodeBuilder, lit *ast.BasicLit)
10711073
}
10721074
}
10731075

1076+
const (
1077+
tplPkgPath = "github.com/goplus/gop/tpl"
1078+
)
1079+
1080+
func compileDomainTextLit(ctx *blockCtx, v *ast.DomainTextLit) {
1081+
switch v.Domain.Name {
1082+
case "tpl": // tpl`...` => tpl.new(`...`)
1083+
ctx.cb.Val(ctx.pkg.Import(tplPkgPath).Ref("New")).
1084+
Val(&goast.BasicLit{Kind: gotoken.STRING, Value: v.Value}, v).
1085+
Call(1)
1086+
}
1087+
}
1088+
10741089
const (
10751090
compositeLitVal = 0
10761091
compositeLitKeyVal = 1

demo/gop-parser/gopcalc-2/calc.gop

+10-11
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,6 @@ import (
33
"os"
44
)
55

6-
const tplCalc = `
7-
expr = termExpr % ("+" | "-")
8-
9-
termExpr = unaryExpr % ("*" | "/")
10-
11-
unaryExpr = operand | "-" unaryExpr
12-
13-
operand = INT | FLOAT | "(" expr ")"
14-
`
15-
166
func calc(e any) float64 {
177
switch e := e.(type) {
188
case *tpl.Token:
@@ -41,7 +31,16 @@ func calc(e any) float64 {
4131
panic("unknown expression")
4232
}
4333

44-
cl := tpl.new(tplCalc)!
34+
cl := tpl`
35+
expr = termExpr % ("+" | "-")
36+
37+
termExpr = unaryExpr % ("*" | "/")
38+
39+
unaryExpr = operand | "-" unaryExpr
40+
41+
operand = INT | FLOAT | "(" expr ")"
42+
`!
43+
4544
print "> "
4645
for line <- os.Stdin {
4746
e, err := cl.parseExpr(line, nil)

0 commit comments

Comments
 (0)