Skip to content

Commit ea8eb4c

Browse files
committedMar 1, 2025·
goplus#2143 gop/cl: compileDomainTextLit
1 parent f4f9ab1 commit ea8eb4c

File tree

4 files changed

+46
-11
lines changed

4 files changed

+46
-11
lines changed
 

‎cl/_testgop/domaintext/in.gop

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

‎cl/_testgop/domaintext/out.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package main
2+
3+
import (
4+
"github.com/goplus/gop/tpl"
5+
"github.com/qiniu/x/errors"
6+
)
7+
8+
func main() {
9+
cl := func() (_gop_ret tpl.Compiler) {
10+
var _gop_err error
11+
_gop_ret, _gop_err = tpl.New(`expr = INT % ("+" | "-")`)
12+
if _gop_err != nil {
13+
_gop_err = errors.NewFrame(_gop_err, "tpl`expr = INT % (\"+\" | \"-\")`", "/Users/xushiwei/work/gop/cl/_testgop/domaintext/in.gop", 1, "main.main")
14+
panic(_gop_err)
15+
}
16+
return
17+
}()
18+
cl.ParseExpr("1+2", nil)
19+
}

‎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)