repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genintegrationtest.go | tools/goctl/api/gogen/genintegrationtest.go | package gogen
import (
_ "embed"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
)
//go:embed integration_test.tpl
var integrationTestTemplate string
func genIntegrationTest(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error {
serviceName := api.Service.Name
if len(serviceName) == 0 {
serviceName = "server"
}
filename, err := format.FileNamingFormat(cfg.NamingFormat, serviceName)
if err != nil {
return err
}
return genFile(fileGenConfig{
dir: dir,
subdir: "",
filename: filename + "_test.go",
templateName: "integrationTestTemplate",
category: category,
templateFile: integrationTestTemplateFile,
builtinTemplate: integrationTestTemplate,
data: map[string]any{
"projectPkg": projectPkg,
"serviceName": serviceName,
"version": version.BuildVersion,
"hasRoutes": len(api.Service.Routes()) > 0,
"routes": api.Service.Routes(),
},
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gen_test.go | tools/goctl/api/gogen/gen_test.go | package gogen
import (
_ "embed"
"go/ast"
goformat "go/format"
"go/importer"
goparser "go/parser"
"go/token"
"go/types"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/goctl/pkg/env"
"github.com/zeromicro/go-zero/tools/goctl/rpc/execx"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
//go:embed testdata/test_api_template.api
testApiTemplate string
//go:embed testdata/test_multi_service_template.api
testMultiServiceTemplate string
//go:embed testdata/ap_ino_info.api
apiNoInfo string
//go:embed testdata/invalid_api_file.api
invalidApiFile string
//go:embed testdata/anonymous_annotation.api
anonymousAnnotation string
//go:embed testdata/api_has_middleware.api
apiHasMiddleware string
//go:embed testdata/api_jwt.api
apiJwt string
//go:embed testdata/api_jwt_with_middleware.api
apiJwtWithMiddleware string
//go:embed testdata/api_has_no_request.api
apiHasNoRequest string
//go:embed testdata/api_route_test.api
apiRouteTest string
//go:embed testdata/has_comment_api_test.api
hasCommentApiTest string
//go:embed testdata/has_inline_no_exist_test.api
hasInlineNoExistTest string
//go:embed testdata/import_api.api
importApi string
//go:embed testdata/has_import_api.api
hasImportApi string
//go:embed testdata/no_struct_tag_api.api
noStructTagApi string
//go:embed testdata/nest_type_api.api
nestTypeApi string
//go:embed testdata/import_twice.api
importTwiceApi string
//go:embed testdata/another_import_api.api
anotherImportApi string
//go:embed testdata/example.api
exampleApi string
)
func TestParser(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(testApiTemplate), os.ModePerm)
assert.Nil(t, err)
env.Set(t, env.GoctlExperimental, "off")
t.Cleanup(func() {
os.Remove(filename)
})
api, err := parser.Parse(filename)
assert.Nil(t, err)
assert.Equal(t, len(api.Types), 2)
assert.Equal(t, len(api.Service.Routes()), 2)
assert.Equal(t, api.Service.Routes()[0].Path, "/greet/from/:name")
assert.Equal(t, api.Service.Routes()[1].Path, "/greet/get")
assert.Equal(t, api.Service.Routes()[1].RequestTypeName(), "Request")
assert.Equal(t, api.Service.Routes()[1].ResponseType, nil)
validate(t, filename)
}
func TestMultiService(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(testMultiServiceTemplate), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
api, err := parser.Parse(filename)
assert.Nil(t, err)
assert.Equal(t, len(api.Service.Routes()), 2)
assert.Equal(t, len(api.Service.Groups), 2)
validate(t, filename)
}
func TestApiNoInfo(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(apiNoInfo), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validate(t, filename)
}
func TestInvalidApiFile(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(invalidApiFile), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.NotNil(t, err)
}
func TestAnonymousAnnotation(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(anonymousAnnotation), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
api, err := parser.Parse(filename)
assert.Nil(t, err)
assert.Equal(t, len(api.Service.Routes()), 1)
assert.Equal(t, api.Service.Routes()[0].Handler, "GreetHandler")
validate(t, filename)
}
func TestApiHasMiddleware(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(apiHasMiddleware), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validate(t, filename)
}
func TestApiHasJwt(t *testing.T) {
filename := "jwt.api"
err := os.WriteFile(filename, []byte(apiJwt), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validate(t, filename)
}
func TestApiHasJwtAndMiddleware(t *testing.T) {
filename := "jwt.api"
err := os.WriteFile(filename, []byte(apiJwtWithMiddleware), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validate(t, filename)
}
func TestApiHasNoRequestBody(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(apiHasNoRequest), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
}
func TestApiRoutes(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(apiRouteTest), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validate(t, filename)
}
func TestHasCommentRoutes(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(hasCommentApiTest), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validate(t, filename)
}
func TestInlineTypeNotExist(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(hasInlineNoExistTest), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.NotNil(t, err)
}
func TestHasImportApi(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(hasImportApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
importApiName := "importApi.api"
err = os.WriteFile(importApiName, []byte(importApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(importApiName)
api, err := parser.Parse(filename)
assert.Nil(t, err)
var hasInline bool
for _, ty := range api.Types {
if ty.Name() == "ImportData" {
hasInline = true
break
}
}
assert.True(t, hasInline)
validate(t, filename)
}
func TestImportTwiceOnExperimental(t *testing.T) {
defaultExperimental := env.Get(env.GoctlExperimental)
env.Set(t, env.GoctlExperimental, "on")
defer env.Set(t, env.GoctlExperimental, defaultExperimental)
filename := "greet.api"
err := os.WriteFile(filename, []byte(importTwiceApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
importApiName := "importApi.api"
err = os.WriteFile(importApiName, []byte(importApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(importApiName)
hasImportApiName := "hasImportApi.api"
err = os.WriteFile(hasImportApiName, []byte(hasImportApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(hasImportApiName)
anotherImportApiName := "anotherImportApi.api"
err = os.WriteFile(anotherImportApiName, []byte(anotherImportApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(anotherImportApiName)
api, err := parser.Parse(filename)
assert.Nil(t, err)
var hasInline bool
for _, ty := range api.Types {
if ty.Name() == "ImportData" {
hasInline = true
break
}
}
assert.True(t, hasInline)
validate(t, filename)
}
func TestNoStructApi(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(noStructTagApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
spec, err := parser.Parse(filename)
assert.Nil(t, err)
assert.Equal(t, len(spec.Types), 5)
validate(t, filename)
}
func TestNestTypeApi(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(nestTypeApi), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.NotNil(t, err)
}
func TestCamelStyle(t *testing.T) {
filename := "greet.api"
err := os.WriteFile(filename, []byte(testApiTemplate), os.ModePerm)
assert.Nil(t, err)
defer os.Remove(filename)
_, err = parser.Parse(filename)
assert.Nil(t, err)
validateWithCamel(t, filename, "GoZero")
}
func TestExampleGen(t *testing.T) {
env.Set(t, env.GoctlExperimental, env.ExperimentalOn)
filename := "greet.api"
err := os.WriteFile(filename, []byte(exampleApi), os.ModePerm)
assert.Nil(t, err)
t.Cleanup(func() {
_ = os.Remove(filename)
})
spec, err := parser.Parse(filename)
assert.Nil(t, err)
assert.Equal(t, len(spec.Types), 10)
validate(t, filename)
}
func validate(t *testing.T, api string) {
validateWithCamel(t, api, "gozero")
}
func validateWithCamel(t *testing.T, api, camel string) {
dir := "workspace"
t.Cleanup(func() {
_ = os.RemoveAll(dir)
})
err := pathx.MkdirIfNotExist(dir)
assert.Nil(t, err)
err = initMod(dir)
assert.Nil(t, err)
err = DoGenProject(api, dir, camel, true)
assert.Nil(t, err)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".go") {
code, err := os.ReadFile(path)
assert.Nil(t, err)
assert.Nil(t, validateCode(string(code)))
if strings.HasSuffix(path, "types.go") {
assert.Nil(t, checkRedeclaredType(string(code)))
}
}
return nil
})
}
func initMod(mod string) error {
_, err := execx.Run("go mod init "+mod, mod)
return err
}
func validateCode(code string) error {
_, err := goformat.Source([]byte(code))
return err
}
func checkRedeclaredType(code string) error {
fset := token.NewFileSet()
f, err := goparser.ParseFile(fset, "", code, goparser.ParseComments)
if err != nil {
return err
}
conf := types.Config{
Error: func(err error) {},
Importer: importer.Default(),
}
info := types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
_, err = conf.Check(f.Name.Name, fset, []*ast.File{f}, &info)
return err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gentypes.go | tools/goctl/api/gogen/gentypes.go | package gogen
import (
_ "embed"
"fmt"
"io"
"os"
"path"
"sort"
"strings"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
)
const typesFile = "types"
//go:embed types.tpl
var typesTemplate string
// BuildTypes gen types to string
func BuildTypes(types []spec.Type) (string, error) {
var builder strings.Builder
first := true
for _, tp := range types {
if first {
first = false
} else {
builder.WriteString("\n\n")
}
if err := writeType(&builder, tp); err != nil {
return "", apiutil.WrapErr(err, "Type "+tp.Name()+" generate error")
}
}
return builder.String(), nil
}
func getTypeName(tp spec.Type) string {
if tp == nil {
return ""
}
switch val := tp.(type) {
case spec.DefineStruct:
typeName := util.Title(tp.Name())
return typeName
case spec.PointerType:
return getTypeName(val.Type)
case spec.ArrayType:
return getTypeName(val.Value)
}
return ""
}
func genTypesWithGroup(dir string, cfg *config.Config, api *spec.ApiSpec) error {
groupTypes := make(map[string]map[string]spec.Type)
typesBelongToFiles := make(map[string]*collection.Set[string])
for _, v := range api.Service.Groups {
group := v.GetAnnotation(groupProperty)
if len(group) == 0 {
group = groupTypeDefault
}
// convert filepath to Identifier name spec.
group = strings.TrimPrefix(group, "/")
group = strings.TrimSuffix(group, "/")
group = util.SafeString(group)
for _, v := range v.Routes {
requestTypeName := getTypeName(v.RequestType)
responseTypeName := getTypeName(v.ResponseType)
requestTypeFileSet, ok := typesBelongToFiles[requestTypeName]
if !ok {
requestTypeFileSet = collection.NewSet[string]()
}
if len(requestTypeName) > 0 {
requestTypeFileSet.Add(group)
typesBelongToFiles[requestTypeName] = requestTypeFileSet
}
responseTypeFileSet, ok := typesBelongToFiles[responseTypeName]
if !ok {
responseTypeFileSet = collection.NewSet[string]()
}
if len(responseTypeName) > 0 {
responseTypeFileSet.Add(group)
typesBelongToFiles[responseTypeName] = responseTypeFileSet
}
}
}
typesInOneFile := make(map[string]*collection.Set[string])
for typeName, fileSet := range typesBelongToFiles {
count := fileSet.Count()
switch {
case count == 0: // it means there has no structure type or no request/response body
continue
case count == 1: // it means a structure type used in only one group.
groupName := fileSet.Keys()[0]
typeSet, ok := typesInOneFile[groupName]
if !ok {
typeSet = collection.NewSet[string]()
}
typeSet.Add(typeName)
typesInOneFile[groupName] = typeSet
default: // it means this type is used in multiple groups.
continue
}
}
for _, v := range api.Types {
typeName := util.Title(v.Name())
groupSet, ok := typesBelongToFiles[typeName]
var typeCount int
if !ok {
typeCount = 0
} else {
typeCount = groupSet.Count()
}
if typeCount == 0 { // not belong to any group
types, ok := groupTypes[groupTypeDefault]
if !ok {
types = make(map[string]spec.Type)
}
types[typeName] = v
groupTypes[groupTypeDefault] = types
continue
}
if typeCount == 1 { // belong to one group
groupName := groupSet.Keys()[0]
types, ok := groupTypes[groupName]
if !ok {
types = make(map[string]spec.Type)
}
types[typeName] = v
groupTypes[groupName] = types
continue
}
// belong to multiple groups
types, ok := groupTypes[groupTypeDefault]
if !ok {
types = make(map[string]spec.Type)
}
types[typeName] = v
groupTypes[groupTypeDefault] = types
}
for group, typeGroup := range groupTypes {
types := make([]spec.Type, 0, len(typeGroup))
for _, v := range typeGroup {
types = append(types, v)
}
sort.Slice(types, func(i, j int) bool {
return types[i].Name() < types[j].Name()
})
if err := writeTypes(dir, group, cfg, types); err != nil {
return err
}
}
return nil
}
func writeTypes(dir, baseFilename string, cfg *config.Config, types []spec.Type) error {
if len(types) == 0 {
return nil
}
val, err := BuildTypes(types)
if err != nil {
return err
}
typeFilename, err := format.FileNamingFormat(cfg.NamingFormat, baseFilename)
if err != nil {
return err
}
typeFilename = typeFilename + ".go"
filename := path.Join(dir, typesDir, typeFilename)
_ = os.Remove(filename)
return genFile(fileGenConfig{
dir: dir,
subdir: typesDir,
filename: typeFilename,
templateName: "typesTemplate",
category: category,
templateFile: typesTemplateFile,
builtinTemplate: typesTemplate,
data: map[string]any{
"types": val,
"containsTime": false,
"version": version.BuildVersion,
},
})
}
func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
if VarBoolTypeGroup {
return genTypesWithGroup(dir, cfg, api)
}
return writeTypes(dir, typesFile, cfg, api.Types)
}
func writeType(writer io.Writer, tp spec.Type) error {
structType, ok := tp.(spec.DefineStruct)
if !ok {
return fmt.Errorf("unspport struct type: %s", tp.Name())
}
_, err := fmt.Fprintf(writer, "type %s struct {\n", util.Title(tp.Name()))
if err != nil {
return err
}
if err := writeMember(writer, structType.Members); err != nil {
return err
}
_, err = fmt.Fprintf(writer, "}")
return err
}
func writeMember(writer io.Writer, members []spec.Member) error {
for _, member := range members {
if member.IsInline {
if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil {
return err
}
continue
}
if err := writeProperty(writer, member.Name, member.Tag, member.GetComment(), member.Type, 1); err != nil {
return err
}
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genroutes.go | tools/goctl/api/gogen/genroutes.go | package gogen
import (
"fmt"
"os"
"path"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const (
jwtTransKey = "jwtTransition"
routesFilename = "routes"
routesTemplate = `// Code generated by goctl. DO NOT EDIT.
// goctl {{.version}}
package handler
import (
"net/http"{{if .hasTimeout}}
"time"{{end}}
{{.importPackages}}
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
{{.routesAdditions}}
}
`
routesAdditionTemplate = `
server.AddRoutes(
{{.routes}} {{.jwt}}{{.signature}} {{.prefix}} {{.timeout}} {{.maxBytes}} {{.sse}}
)
`
timeoutThreshold = time.Millisecond
)
var mapping = map[string]string{
"delete": "http.MethodDelete",
"get": "http.MethodGet",
"head": "http.MethodHead",
"post": "http.MethodPost",
"put": "http.MethodPut",
"patch": "http.MethodPatch",
"connect": "http.MethodConnect",
"options": "http.MethodOptions",
"trace": "http.MethodTrace",
}
type (
group struct {
routes []route
jwtEnabled bool
signatureEnabled bool
sseEnabled bool
authName string
timeout string
middlewares []string
prefix string
jwtTrans string
maxBytes string
}
route struct {
method string
path string
handler string
doc string
}
)
func genRoutes(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error {
var builder strings.Builder
groups, err := getRoutes(api)
if err != nil {
return err
}
templateText, err := pathx.LoadTemplate(category, routesAdditionTemplateFile, routesAdditionTemplate)
if err != nil {
return err
}
var hasTimeout bool
gt := template.Must(template.New("groupTemplate").Parse(templateText))
for _, g := range groups {
var gbuilder strings.Builder
gbuilder.WriteString("[]rest.Route{")
for _, r := range g.routes {
var routeString string
if len(r.doc) > 0 {
routeString = fmt.Sprintf(`
{
%s
Method: %s,
Path: "%s",
Handler: %s,
},`, getDoc(r.doc), r.method, r.path, r.handler)
} else {
routeString = fmt.Sprintf(`
{
Method: %s,
Path: "%s",
Handler: %s,
},`, r.method, r.path, r.handler)
}
fmt.Fprint(&gbuilder, routeString)
}
var jwt string
if g.jwtEnabled {
jwt = fmt.Sprintf("\n rest.WithJwt(serverCtx.Config.%s.AccessSecret),", g.authName)
}
if len(g.jwtTrans) > 0 {
jwt = jwt + fmt.Sprintf("\n rest.WithJwtTransition(serverCtx.Config.%s.PrevSecret,serverCtx.Config.%s.Secret),", g.jwtTrans, g.jwtTrans)
}
var signature, prefix string
if g.signatureEnabled {
signature = "\n rest.WithSignature(serverCtx.Config.Signature),"
}
var sse string
if g.sseEnabled {
sse = "\n rest.WithSSE(),"
}
if len(g.prefix) > 0 {
prefix = fmt.Sprintf(`
rest.WithPrefix("%s"),`, g.prefix)
}
var timeout string
if len(g.timeout) > 0 {
duration, err := time.ParseDuration(g.timeout)
if err != nil {
return err
}
timeout = fmt.Sprintf("\n rest.WithTimeout(%s),", formatDuration(duration))
hasTimeout = true
}
var maxBytes string
if len(g.maxBytes) > 0 {
_, err := strconv.ParseInt(g.maxBytes, 10, 64)
if err != nil {
return fmt.Errorf("maxBytes %s parse error,it is an invalid number", g.maxBytes)
}
maxBytes = fmt.Sprintf("\n rest.WithMaxBytes(%s),", g.maxBytes)
}
var routes string
if len(g.middlewares) > 0 {
gbuilder.WriteString("\n}...,")
params := g.middlewares
for i := range params {
params[i] = "serverCtx." + params[i]
}
middlewareStr := strings.Join(params, ", ")
routes = fmt.Sprintf("rest.WithMiddlewares(\n[]rest.Middleware{ %s }, \n %s \n),",
middlewareStr, strings.TrimSpace(gbuilder.String()))
} else {
gbuilder.WriteString("\n},")
routes = strings.TrimSpace(gbuilder.String())
}
if err := gt.Execute(&builder, map[string]string{
"routes": routes,
"jwt": jwt,
"signature": signature,
"sse": sse,
"prefix": prefix,
"timeout": timeout,
"maxBytes": maxBytes,
}); err != nil {
return err
}
}
routeFilename, err := format.FileNamingFormat(cfg.NamingFormat, routesFilename)
if err != nil {
return err
}
routeFilename = routeFilename + ".go"
filename := path.Join(dir, handlerDir, routeFilename)
os.Remove(filename)
return genFile(fileGenConfig{
dir: dir,
subdir: handlerDir,
filename: routeFilename,
templateName: "routesTemplate",
category: category,
templateFile: routesTemplateFile,
builtinTemplate: routesTemplate,
data: map[string]any{
"hasTimeout": hasTimeout,
"importPackages": genRouteImports(rootPkg, api),
"routesAdditions": strings.TrimSpace(builder.String()),
"version": version.BuildVersion,
"projectPkg": projectPkg,
},
})
}
func formatDuration(duration time.Duration) string {
if duration < time.Microsecond {
return fmt.Sprintf("%d * time.Nanosecond", duration.Nanoseconds())
}
if duration < time.Millisecond {
return fmt.Sprintf("%d * time.Microsecond", duration.Microseconds())
}
return fmt.Sprintf("%d * time.Millisecond", duration.Milliseconds())
}
func genRouteImports(parentPkg string, api *spec.ApiSpec) string {
importSet := collection.NewSet[string]()
importSet.Add(fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, contextDir)))
for _, group := range api.Service.Groups {
for _, route := range group.Routes {
folder := route.GetAnnotation(groupProperty)
if len(folder) == 0 {
folder = group.GetAnnotation(groupProperty)
if len(folder) == 0 {
continue
}
}
importSet.Add(fmt.Sprintf("%s \"%s\"", toPrefix(folder),
pathx.JoinPackages(parentPkg, handlerDir, folder)))
}
}
imports := importSet.Keys()
sort.Strings(imports)
projectSection := strings.Join(imports, "\n\t")
depSection := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
return fmt.Sprintf("%s\n\n\t%s", projectSection, depSection)
}
func getRoutes(api *spec.ApiSpec) ([]group, error) {
var routes []group
for _, g := range api.Service.Groups {
var groupedRoutes group
for _, r := range g.Routes {
handler := getHandlerName(r)
handler = handler + "(serverCtx)"
folder := r.GetAnnotation(groupProperty)
if len(folder) > 0 {
handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
} else {
folder = g.GetAnnotation(groupProperty)
if len(folder) > 0 {
handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
}
}
groupedRoutes.routes = append(groupedRoutes.routes, route{
method: mapping[r.Method],
path: r.Path,
handler: handler,
doc: r.JoinedDoc(),
})
}
groupedRoutes.timeout = g.GetAnnotation("timeout")
groupedRoutes.maxBytes = g.GetAnnotation("maxBytes")
jwt := g.GetAnnotation("jwt")
if len(jwt) > 0 {
groupedRoutes.authName = jwt
groupedRoutes.jwtEnabled = true
}
jwtTrans := g.GetAnnotation(jwtTransKey)
if len(jwtTrans) > 0 {
groupedRoutes.jwtTrans = jwtTrans
}
signature := g.GetAnnotation("signature")
if signature == "true" {
groupedRoutes.signatureEnabled = true
}
sse := g.GetAnnotation("sse")
if sse == "true" {
groupedRoutes.sseEnabled = true
}
middleware := g.GetAnnotation("middleware")
if len(middleware) > 0 {
groupedRoutes.middlewares = append(groupedRoutes.middlewares,
strings.Split(middleware, ",")...)
}
prefix := g.GetAnnotation(spec.RoutePrefixKey)
prefix = strings.ReplaceAll(prefix, `"`, "")
prefix = strings.TrimSpace(prefix)
if len(prefix) > 0 {
prefix = path.Join("/", prefix)
groupedRoutes.prefix = prefix
}
routes = append(routes, groupedRoutes)
}
return routes, nil
}
func toPrefix(folder string) string {
return strings.ReplaceAll(folder, "/", "")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/vars.go | tools/goctl/api/gogen/vars.go | package gogen
const (
internal = "internal/"
typesPacket = "types"
configDir = internal + "config"
contextDir = internal + "svc"
handlerDir = internal + "handler"
logicDir = internal + "logic"
middlewareDir = internal + "middleware"
typesDir = internal + typesPacket
groupProperty = "group"
groupTypeDefault="types"
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/template_test.go | tools/goctl/api/gogen/template_test.go | package gogen
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
func TestGenTemplates(t *testing.T) {
err := pathx.InitTemplates(category, templates)
assert.Nil(t, err)
dir, err := pathx.GetTemplateDir(category)
assert.Nil(t, err)
file := filepath.Join(dir, "main.tpl")
data, err := os.ReadFile(file)
assert.Nil(t, err)
assert.Equal(t, string(data), mainTemplate)
}
func TestRevertTemplate(t *testing.T) {
name := "main.tpl"
err := pathx.InitTemplates(category, templates)
assert.Nil(t, err)
dir, err := pathx.GetTemplateDir(category)
assert.Nil(t, err)
file := filepath.Join(dir, name)
data, err := os.ReadFile(file)
assert.Nil(t, err)
modifyData := string(data) + "modify"
err = pathx.CreateTemplate(category, name, modifyData)
assert.Nil(t, err)
data, err = os.ReadFile(file)
assert.Nil(t, err)
assert.Equal(t, string(data), modifyData)
assert.Nil(t, RevertTemplate(name))
data, err = os.ReadFile(file)
assert.Nil(t, err)
assert.Equal(t, mainTemplate, string(data))
}
func TestClean(t *testing.T) {
name := "main.tpl"
err := pathx.InitTemplates(category, templates)
assert.Nil(t, err)
assert.Nil(t, Clean())
dir, err := pathx.GetTemplateDir(category)
assert.Nil(t, err)
file := filepath.Join(dir, name)
_, err = os.ReadFile(file)
assert.NotNil(t, err)
}
func TestUpdate(t *testing.T) {
name := "main.tpl"
err := pathx.InitTemplates(category, templates)
assert.Nil(t, err)
dir, err := pathx.GetTemplateDir(category)
assert.Nil(t, err)
file := filepath.Join(dir, name)
data, err := os.ReadFile(file)
assert.Nil(t, err)
modifyData := string(data) + "modify"
err = pathx.CreateTemplate(category, name, modifyData)
assert.Nil(t, err)
data, err = os.ReadFile(file)
assert.Nil(t, err)
assert.Equal(t, string(data), modifyData)
assert.Nil(t, Update())
data, err = os.ReadFile(file)
assert.Nil(t, err)
assert.Equal(t, mainTemplate, string(data))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gensse_test.go | tools/goctl/api/gogen/gensse_test.go | package gogen
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSSEGeneration(t *testing.T) {
// Create a temporary directory for test
dir := t.TempDir()
// Create a test API file with SSE annotation
apiContent := `syntax = "v1"
type SseReq {
Message string ` + "`json:\"message\"`" + `
}
type SseResp {
Data string ` + "`json:\"data\"`" + `
}
@server (
sse: true
)
service Test {
@handler Sse
get /sse (SseReq) returns (SseResp)
}
`
apiFile := filepath.Join(dir, "test.api")
err := os.WriteFile(apiFile, []byte(apiContent), 0644)
assert.NoError(t, err)
// Generate code
err = DoGenProject(apiFile, dir, "gozero", false)
assert.NoError(t, err)
// Read generated handler file
handlerPath := filepath.Join(dir, "internal/handler/ssehandler.go")
handlerContent, err := os.ReadFile(handlerPath)
assert.NoError(t, err)
// Read generated logic file
logicPath := filepath.Join(dir, "internal/logic/sselogic.go")
logicContent, err := os.ReadFile(logicPath)
assert.NoError(t, err)
handlerStr := string(handlerContent)
logicStr := string(logicContent)
// Verify SSE-specific patterns in handler
// Handler should call: err := l.Sse(&req, client)
assert.Contains(t, handlerStr, "err := l.Sse(&req, client)",
"Handler should call logic with client channel parameter")
// Handler should NOT have the regular pattern: resp, err := l.Sse(&req)
assert.NotContains(t, handlerStr, "resp, err := l.Sse(&req)",
"Handler should not use regular pattern with resp return")
// Handler should use threading.GoSafeCtx
assert.Contains(t, handlerStr, "threading.GoSafeCtx",
"Handler should use threading.GoSafeCtx for SSE")
// Handler should create client channel
assert.Contains(t, handlerStr, "client := make(chan",
"Handler should create client channel")
// Verify SSE-specific patterns in logic
// Logic should have signature: Sse(req *types.SseReq, client chan<- *types.SseResp) error
assert.Contains(t, logicStr, "func (l *SseLogic) Sse(req *types.SseReq, client chan<- *types.SseResp) error",
"Logic should have SSE signature with client channel parameter")
// Logic should NOT have regular signature: Sse(req *types.SseReq) (resp *types.SseResp, err error)
assert.NotContains(t, logicStr, "(resp *types.SseResp, err error)",
"Logic should not have regular signature with resp return")
}
func TestNonSSEGeneration(t *testing.T) {
// Create a temporary directory for test
dir := t.TempDir()
// Create a test API file WITHOUT SSE annotation
apiContent := `syntax = "v1"
type SseReq {
Message string ` + "`json:\"message\"`" + `
}
type SseResp {
Data string ` + "`json:\"data\"`" + `
}
service Test {
@handler Sse
get /sse (SseReq) returns (SseResp)
}
`
apiFile := filepath.Join(dir, "test.api")
err := os.WriteFile(apiFile, []byte(apiContent), 0644)
assert.NoError(t, err)
// Generate code
err = DoGenProject(apiFile, dir, "gozero", false)
assert.NoError(t, err)
// Read generated handler file
handlerPath := filepath.Join(dir, "internal/handler/ssehandler.go")
handlerContent, err := os.ReadFile(handlerPath)
assert.NoError(t, err)
// Read generated logic file
logicPath := filepath.Join(dir, "internal/logic/sselogic.go")
logicContent, err := os.ReadFile(logicPath)
assert.NoError(t, err)
handlerStr := string(handlerContent)
logicStr := string(logicContent)
// Verify regular (non-SSE) patterns in handler
// Handler should call: resp, err := l.Sse(&req)
assert.Contains(t, handlerStr, "resp, err := l.Sse(&req)",
"Handler should use regular pattern with resp return")
// Handler should NOT have SSE pattern: err := l.Sse(&req, client)
assert.NotContains(t, handlerStr, "err := l.Sse(&req, client)",
"Handler should not use SSE pattern")
// Handler should NOT use threading.GoSafeCtx
assert.NotContains(t, handlerStr, "threading.GoSafeCtx",
"Handler should not use threading.GoSafeCtx for regular routes")
// Verify regular (non-SSE) patterns in logic
// Logic should have signature: Sse(req *types.SseReq) (resp *types.SseResp, err error)
assert.Contains(t, logicStr, "(resp *types.SseResp, err error)",
"Logic should have regular signature with resp return")
// Logic should NOT have SSE signature with client parameter
linesToCheck := strings.Split(logicStr, "\n")
hasSSESignature := false
for _, line := range linesToCheck {
if strings.Contains(line, "func (l *SseLogic) Sse") && strings.Contains(line, "client chan<-") {
hasSSESignature = true
break
}
}
assert.False(t, hasSSESignature,
"Logic should not have SSE signature with client channel parameter")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genmain.go | tools/goctl/api/gogen/genmain.go | package gogen
import (
_ "embed"
"fmt"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
//go:embed main.tpl
var mainTemplate string
func genMain(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error {
name := strings.ToLower(api.Service.Name)
filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
if err != nil {
return err
}
configName := filename
if strings.HasSuffix(filename, "-api") {
filename = strings.ReplaceAll(filename, "-api", "")
}
return genFile(fileGenConfig{
dir: dir,
subdir: "",
filename: filename + ".go",
templateName: "mainTemplate",
category: category,
templateFile: mainTemplateFile,
builtinTemplate: mainTemplate,
data: map[string]string{
"importPackages": genMainImports(rootPkg),
"serviceName": configName,
"projectPkg": projectPkg,
"version": version.BuildVersion,
},
})
}
func genMainImports(parentPkg string) string {
var imports []string
imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, configDir)))
imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, handlerDir)))
imports = append(imports, fmt.Sprintf("\"%s\"\n", pathx.JoinPackages(parentPkg, contextDir)))
imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
return strings.Join(imports, "\n\t")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genlogic.go | tools/goctl/api/gogen/genlogic.go | package gogen
import (
_ "embed"
"fmt"
"path"
"strconv"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
var (
//go:embed logic.tpl
logicTemplate string
//go:embed sse_logic.tpl
sseLogicTemplate string
)
func genLogic(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error {
for _, g := range api.Service.Groups {
for _, r := range g.Routes {
err := genLogicByRoute(dir, rootPkg, projectPkg, cfg, g, r)
if err != nil {
return err
}
}
}
return nil
}
func genLogicByRoute(dir, rootPkg, projectPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
logic := getLogicName(route)
goFile, err := format.FileNamingFormat(cfg.NamingFormat, logic)
if err != nil {
return err
}
imports := genLogicImports(route, rootPkg)
var responseString string
var returnString string
var requestString string
if len(route.ResponseTypeName()) > 0 {
resp := responseGoTypeName(route, typesPacket)
responseString = "(resp " + resp + ", err error)"
returnString = "return"
} else {
responseString = "error"
returnString = "return nil"
}
if len(route.RequestTypeName()) > 0 {
requestString = "req *" + requestGoTypeName(route, typesPacket)
}
subDir := getLogicFolderPath(group, route)
builtinTemplate := logicTemplate
templateFile := logicTemplateFile
sse := group.GetAnnotation("sse")
if sse == "true" {
builtinTemplate = sseLogicTemplate
templateFile = sseLogicTemplateFile
responseString = "error"
returnString = "return nil"
resp := responseGoTypeName(route, typesPacket)
if len(requestString) == 0 {
requestString = "client chan<- " + resp
} else {
requestString += ", client chan<- " + resp
}
}
return genFile(fileGenConfig{
dir: dir,
subdir: subDir,
filename: goFile + ".go",
templateName: "logicTemplate",
category: category,
templateFile: templateFile,
builtinTemplate: builtinTemplate,
data: map[string]any{
"pkgName": subDir[strings.LastIndex(subDir, "/")+1:],
"imports": imports,
"logic": strings.Title(logic),
"function": strings.Title(strings.TrimSuffix(logic, "Logic")),
"responseType": responseString,
"returnString": returnString,
"request": requestString,
"hasDoc": len(route.JoinedDoc()) > 0,
"doc": getDoc(route.JoinedDoc()),
"projectPkg": projectPkg,
"version": version.BuildVersion,
},
})
}
func getLogicFolderPath(group spec.Group, route spec.Route) string {
folder := route.GetAnnotation(groupProperty)
if len(folder) == 0 {
folder = group.GetAnnotation(groupProperty)
if len(folder) == 0 {
return logicDir
}
}
folder = strings.TrimPrefix(folder, "/")
folder = strings.TrimSuffix(folder, "/")
return path.Join(logicDir, folder)
}
func genLogicImports(route spec.Route, parentPkg string) string {
var imports []string
imports = append(imports, `"context"`+"\n")
imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, contextDir)))
if shallImportTypesPackage(route) {
imports = append(imports, fmt.Sprintf("\"%s\"\n", pathx.JoinPackages(parentPkg, typesDir)))
}
imports = append(imports, fmt.Sprintf("\"%s/core/logx\"", vars.ProjectOpenSourceURL))
return strings.Join(imports, "\n\t")
}
func onlyPrimitiveTypes(val string) bool {
fields := strings.FieldsFunc(val, func(r rune) bool {
return r == '[' || r == ']' || r == ' '
})
for _, field := range fields {
if field == "map" {
continue
}
// ignore array dimension number, like [5]int
if _, err := strconv.Atoi(field); err == nil {
continue
}
if !api.IsBasicType(field) {
return false
}
}
return true
}
func shallImportTypesPackage(route spec.Route) bool {
if len(route.RequestTypeName()) > 0 {
return true
}
respTypeName := route.ResponseTypeName()
if len(respTypeName) == 0 {
return false
}
if onlyPrimitiveTypes(respTypeName) {
return false
}
return true
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/template.go | tools/goctl/api/gogen/template.go | package gogen
import (
"fmt"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
category = "api"
configTemplateFile = "config.tpl"
contextTemplateFile = "context.tpl"
etcTemplateFile = "etc.tpl"
handlerTemplateFile = "handler.tpl"
sseHandlerTemplateFile = "sse_handler.tpl"
handlerTestTemplateFile = "handler_test.tpl"
logicTemplateFile = "logic.tpl"
sseLogicTemplateFile = "sse_logic.tpl"
logicTestTemplateFile = "logic_test.tpl"
mainTemplateFile = "main.tpl"
middlewareImplementCodeFile = "middleware.tpl"
routesTemplateFile = "routes.tpl"
routesAdditionTemplateFile = "route-addition.tpl"
typesTemplateFile = "types.tpl"
svcTestTemplateFile = "svc_test.tpl"
integrationTestTemplateFile = "integration_test.tpl"
)
var templates = map[string]string{
configTemplateFile: configTemplate,
contextTemplateFile: contextTemplate,
etcTemplateFile: etcTemplate,
handlerTemplateFile: handlerTemplate,
sseHandlerTemplateFile: sseHandlerTemplate,
handlerTestTemplateFile: handlerTestTemplate,
logicTemplateFile: logicTemplate,
sseLogicTemplateFile: sseLogicTemplate,
logicTestTemplateFile: logicTestTemplate,
mainTemplateFile: mainTemplate,
middlewareImplementCodeFile: middlewareImplementCode,
routesTemplateFile: routesTemplate,
routesAdditionTemplateFile: routesAdditionTemplate,
typesTemplateFile: typesTemplate,
svcTestTemplateFile: svcTestTemplate,
integrationTestTemplateFile: integrationTestTemplate,
}
// Category returns the category of the api files.
func Category() string {
return category
}
// Clean cleans the generated deployment files.
func Clean() error {
return pathx.Clean(category)
}
// GenTemplates generates api template files.
func GenTemplates() error {
return pathx.InitTemplates(category, templates)
}
// RevertTemplate reverts the given template file to the default value.
func RevertTemplate(name string) error {
content, ok := templates[name]
if !ok {
return fmt.Errorf("%s: no such file name", name)
}
return pathx.CreateTemplate(category, name, content)
}
// Update updates the template files to the templates built in current goctl.
func Update() error {
err := Clean()
if err != nil {
return err
}
return pathx.InitTemplates(category, templates)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genhandlerstest.go | tools/goctl/api/gogen/genhandlerstest.go | package gogen
import (
_ "embed"
"fmt"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
//go:embed handler_test.tpl
var handlerTestTemplate string
func genHandlerTest(dir, rootPkg, projectPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
handler := getHandlerName(route)
handlerPath := getHandlerFolderPath(group, route)
pkgName := handlerPath[strings.LastIndex(handlerPath, "/")+1:]
logicName := defaultLogicPackage
if handlerPath != handlerDir {
handler = strings.Title(handler)
logicName = pkgName
}
filename, err := format.FileNamingFormat(cfg.NamingFormat, handler)
if err != nil {
return err
}
return genFile(fileGenConfig{
dir: dir,
subdir: getHandlerFolderPath(group, route),
filename: filename + "_test.go",
templateName: "handlerTestTemplate",
category: category,
templateFile: handlerTestTemplateFile,
builtinTemplate: handlerTestTemplate,
data: map[string]any{
"PkgName": pkgName,
"ImportPackages": genHandlerTestImports(group, route, rootPkg),
"HandlerName": handler,
"RequestType": util.Title(route.RequestTypeName()),
"ResponseType": util.Title(route.ResponseTypeName()),
"LogicName": logicName,
"LogicType": strings.Title(getLogicName(route)),
"Call": strings.Title(strings.TrimSuffix(handler, "Handler")),
"HasResp": len(route.ResponseTypeName()) > 0,
"HasRequest": len(route.RequestTypeName()) > 0,
"HasDoc": len(route.JoinedDoc()) > 0,
"Doc": getDoc(route.JoinedDoc()),
"projectPkg": projectPkg,
"version": version.BuildVersion,
},
})
}
func genHandlersTest(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error {
for _, group := range api.Service.Groups {
for _, route := range group.Routes {
if err := genHandlerTest(dir, rootPkg, projectPkg, cfg, group, route); err != nil {
return err
}
}
}
return nil
}
func genHandlerTestImports(group spec.Group, route spec.Route, parentPkg string) string {
imports := []string{
//fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, getLogicFolderPath(group, route))),
fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, contextDir)),
fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, configDir)),
}
if len(route.RequestTypeName()) > 0 {
imports = append(imports, fmt.Sprintf("\"%s\"\n", pathx.JoinPackages(parentPkg, typesDir)))
}
return strings.Join(imports, "\n\t")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gensvc.go | tools/goctl/api/gogen/gensvc.go | package gogen
import (
_ "embed"
"fmt"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/config"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"github.com/zeromicro/go-zero/tools/goctl/vars"
)
const contextFilename = "service_context"
//go:embed svc.tpl
var contextTemplate string
func genServiceContext(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)
if err != nil {
return err
}
var middlewareStr string
var middlewareAssignment string
middlewares := getMiddleware(api)
for _, item := range middlewares {
middlewareStr += fmt.Sprintf("%s rest.Middleware\n", item)
name := strings.TrimSuffix(item, "Middleware") + "Middleware"
middlewareAssignment += fmt.Sprintf("%s: %s,\n", item,
fmt.Sprintf("middleware.New%s().%s", strings.Title(name), "Handle"))
}
configImport := "\"" + pathx.JoinPackages(rootPkg, configDir) + "\""
if len(middlewareStr) > 0 {
configImport += "\n\t\"" + pathx.JoinPackages(rootPkg, middlewareDir) + "\""
configImport += fmt.Sprintf("\n\t\"%s/rest\"", vars.ProjectOpenSourceURL)
}
return genFile(fileGenConfig{
dir: dir,
subdir: contextDir,
filename: filename + ".go",
templateName: "contextTemplate",
category: category,
templateFile: contextTemplateFile,
builtinTemplate: contextTemplate,
data: map[string]string{
"configImport": configImport,
"config": "config.Config",
"middleware": middlewareStr,
"middlewareAssignment": middlewareAssignment,
"projectPkg": projectPkg,
"version": version.BuildVersion,
},
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/tags_test.go | tools/goctl/api/spec/tags_test.go | package spec
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTags_Get(t *testing.T) {
tags := &Tags{
tags: []*Tag{
{Key: "json", Name: "foo", Options: []string{"omitempty"}},
{Key: "xml", Name: "bar", Options: nil},
},
}
tag, err := tags.Get("json")
assert.NoError(t, err)
assert.NotNil(t, tag)
assert.Equal(t, "json", tag.Key)
assert.Equal(t, "foo", tag.Name)
_, err = tags.Get("yaml")
assert.Error(t, err)
var nilTags *Tags
_, err = nilTags.Get("json")
assert.Error(t, err)
}
func TestTags_Keys(t *testing.T) {
tags := &Tags{
tags: []*Tag{
{Key: "json", Name: "foo", Options: []string{"omitempty"}},
{Key: "xml", Name: "bar", Options: nil},
},
}
keys := tags.Keys()
expected := []string{"json", "xml"}
assert.Equal(t, expected, keys)
var nilTags *Tags
nilKeys := nilTags.Keys()
assert.Empty(t, nilKeys)
}
func TestTags_Tags(t *testing.T) {
tags := &Tags{
tags: []*Tag{
{Key: "json", Name: "foo", Options: []string{"omitempty"}},
{Key: "xml", Name: "bar", Options: nil},
},
}
result := tags.Tags()
assert.Len(t, result, 2)
assert.Equal(t, "json", result[0].Key)
assert.Equal(t, "foo", result[0].Name)
assert.Equal(t, []string{"omitempty"}, result[0].Options)
assert.Equal(t, "xml", result[1].Key)
assert.Equal(t, "bar", result[1].Name)
assert.Nil(t, result[1].Options)
var nilTags *Tags
nilResult := nilTags.Tags()
assert.Empty(t, nilResult)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/validate.go | tools/goctl/api/spec/validate.go | package spec
import "errors"
var ErrMissingService = errors.New("missing service")
// Validate validates Validate the integrity of the spec.
func (s *ApiSpec) Validate() error {
if len(s.Service.Name) == 0 {
return ErrMissingService
}
if len(s.Service.Groups) == 0 {
return ErrMissingService
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/spec.go | tools/goctl/api/spec/spec.go | package spec
// RoutePrefixKey is the prefix keyword for the routes.
const RoutePrefixKey = "prefix"
type (
// Doc describes document
Doc []string
// Annotation defines key-value
Annotation struct {
Properties map[string]string
}
// ApiSyntax describes the syntax grammar
ApiSyntax struct {
Version string
Doc Doc
Comment Doc
}
// ApiSpec describes an api file
ApiSpec struct {
Info Info
Syntax ApiSyntax // Deprecated: useless expression
Imports []Import // Deprecated: useless expression
Types []Type
Service Service
}
// Import describes api import
Import struct {
Value string
Doc Doc
Comment Doc
}
// Group defines a set of routing information
Group struct {
Annotation Annotation
Routes []Route
}
// Info describes info grammar block
Info struct {
// Deprecated: use Properties instead
Title string
// Deprecated: use Properties instead
Desc string
// Deprecated: use Properties instead
Version string
// Deprecated: use Properties instead
Author string
// Deprecated: use Properties instead
Email string
Properties map[string]string
}
// Member describes the field of a structure
Member struct {
Name string
// data type, for example, string、map[int]string、[]int64、[]*User
Type Type
Tag string
Comment string
// document for the field
Docs Doc
IsInline bool
}
// Route describes api route
Route struct {
// Deprecated: Use Service AtServer instead.
AtServerAnnotation Annotation
Method string
Path string
RequestType Type
ResponseType Type
Docs Doc
Handler string
AtDoc AtDoc
HandlerDoc Doc
HandlerComment Doc
Doc Doc
Comment Doc
}
// Service describes api service
Service struct {
Name string
Groups []Group
}
// Type defines api type
Type interface {
Name() string
Comments() []string
Documents() []string
}
// DefineStruct describes api structure
DefineStruct struct {
RawName string
Members []Member
Docs Doc
}
// NestedStruct describes a structure nested in structure.
NestedStruct struct {
RawName string
Members []Member
Docs Doc
}
// PrimitiveType describes the basic golang type, such as bool,int32,int64, ...
PrimitiveType struct {
RawName string
}
// MapType describes a map for api
MapType struct {
RawName string
// only support the PrimitiveType
Key string
// it can be asserted as PrimitiveType: int、bool、
// PointerType: *string、*User、
// MapType: map[${PrimitiveType}]interface、
// ArrayType:[]int、[]User、[]*User
// InterfaceType: interface{}
// Type
Value Type
}
// ArrayType describes a slice for api
ArrayType struct {
RawName string
Value Type
}
// InterfaceType describes an interface for api
InterfaceType struct {
RawName string
}
// PointerType describes a pointer for api
PointerType struct {
RawName string
Type Type
}
// AtDoc describes a metadata for api grammar: @doc(...)
AtDoc struct {
Properties map[string]string
Text string
}
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/tags.go | tools/goctl/api/spec/tags.go | package spec
import (
"errors"
"strings"
"github.com/fatih/structtag"
)
var errTagNotExist = errors.New("tag does not exist")
type (
// Tag defines a tag for structure filed
Tag struct {
// Key is the tag key, such as json, xml, etc..
// i.e: `json:"foo,omitempty". Here key is: "json"
Key string
// Name is a part of the value
// i.e: `json:"foo,omitempty". Here name is: "foo"
Name string
// Options is a part of the value. It contains a slice of tag options i.e:
// `json:"foo,omitempty". Here options is: ["omitempty"]
Options []string
}
// Tags defines a slice for Tag
Tags struct {
tags []*Tag
}
)
// Parse converts tag string into Tag
func Parse(tag string) (*Tags, error) {
tag = strings.TrimPrefix(tag, "`")
tag = strings.TrimSuffix(tag, "`")
tags, err := structtag.Parse(tag)
if err != nil {
return nil, err
}
var result Tags
for _, item := range tags.Tags() {
result.tags = append(result.tags, &Tag{Key: item.Key, Name: item.Name, Options: item.Options})
}
return &result, nil
}
// Get gets tag value by specified key
func (t *Tags) Get(key string) (*Tag, error) {
if t == nil {
return nil, errTagNotExist
}
for _, tag := range t.tags {
if tag.Key == key {
return tag, nil
}
}
return nil, errTagNotExist
}
// Keys returns all keys in Tags
func (t *Tags) Keys() []string {
if t == nil {
return []string{}
}
keys := make([]string, 0, len(t.tags))
for _, tag := range t.tags {
keys = append(keys, tag.Key)
}
return keys
}
// Tags returns all tags in Tags
func (t *Tags) Tags() []*Tag {
if t == nil {
return []*Tag{}
}
return t.tags
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/fn.go | tools/goctl/api/spec/fn.go | package spec
import (
"errors"
"path"
"slices"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/util"
)
const (
bodyTagKey = "json"
formTagKey = "form"
pathTagKey = "path"
headerTagKey = "header"
defaultSummaryKey = "summary"
)
var definedKeys = []string{bodyTagKey, formTagKey, pathTagKey, headerTagKey}
func (s Service) JoinPrefix() Service {
groups := make([]Group, 0, len(s.Groups))
for _, g := range s.Groups {
prefix := strings.TrimSpace(g.GetAnnotation(RoutePrefixKey))
prefix = strings.ReplaceAll(prefix, `"`, "")
routes := make([]Route, 0, len(g.Routes))
for _, r := range g.Routes {
r.Path = path.Join("/", prefix, r.Path)
routes = append(routes, r)
}
g.Routes = routes
groups = append(groups, g)
}
s.Groups = groups
return s
}
// Routes returns all routes in api service
func (s Service) Routes() []Route {
var result []Route
for _, group := range s.Groups {
result = append(result, group.Routes...)
}
return result
}
// Tags returns all tags in Member
func (m Member) Tags() []*Tag {
tags, err := Parse(m.Tag)
if err != nil {
panic(m.Tag + ", " + err.Error())
}
return tags.Tags()
}
// IsOptional returns true if tag is optional
func (m Member) IsOptional() bool {
if !m.IsBodyMember() && !m.IsFormMember() {
return false
}
tag := m.Tags()
for _, item := range tag {
if item.Key == bodyTagKey || item.Key == formTagKey {
if slices.Contains(item.Options, "optional") {
return true
}
}
}
return false
}
// IsOmitEmpty returns true if tag contains omitempty
func (m Member) IsOmitEmpty() bool {
if !m.IsBodyMember() {
return false
}
tag := m.Tags()
for _, item := range tag {
if item.Key == bodyTagKey {
if slices.Contains(item.Options, "omitempty") {
return true
}
}
}
return false
}
// GetPropertyName returns json tag value
func (m Member) GetPropertyName() (string, error) {
tags := m.Tags()
for _, tag := range tags {
if slices.Contains(definedKeys, tag.Key) {
if tag.Name == "-" {
return util.Untitle(m.Name), nil
}
return tag.Name, nil
}
}
return "", errors.New("json property name not exist, member: " + m.Name)
}
// GetComment returns comment value of Member
func (m Member) GetComment() string {
return strings.TrimSpace(m.Comment)
}
// IsBodyMember returns true if contains json tag
func (m Member) IsBodyMember() bool {
if m.IsInline {
return true
}
tags := m.Tags()
for _, tag := range tags {
if tag.Key == bodyTagKey {
return true
}
}
return false
}
// IsFormMember returns true if contains form tag
func (m Member) IsFormMember() bool {
if m.IsInline {
return false
}
tags := m.Tags()
for _, tag := range tags {
if tag.Key == formTagKey {
return true
}
}
return false
}
// IsTagMember returns true if contains given tag
func (m Member) IsTagMember(tagKey string) bool {
if m.IsInline {
return true
}
tags := m.Tags()
for _, tag := range tags {
if tag.Key == tagKey {
return true
}
}
return false
}
// GetEnumOptions return a slice contains all enumeration options
func (m Member) GetEnumOptions() []string {
if !m.IsBodyMember() {
return nil
}
tags := m.Tags()
for _, tag := range tags {
if tag.Key == bodyTagKey {
options := tag.Options
for _, option := range options {
if strings.Index(option, "options=") == 0 {
option = strings.TrimPrefix(option, "options=")
return strings.Split(option, "|")
}
}
}
}
return nil
}
// GetBodyMembers returns all json fields
func (t DefineStruct) GetBodyMembers() []Member {
var result []Member
for _, member := range t.Members {
if member.IsBodyMember() {
result = append(result, member)
}
}
return result
}
// GetFormMembers returns all form fields
func (t DefineStruct) GetFormMembers() []Member {
var result []Member
for _, member := range t.Members {
if member.IsFormMember() {
result = append(result, member)
}
}
return result
}
// GetNonBodyMembers returns all have no tag fields
func (t DefineStruct) GetNonBodyMembers() []Member {
var result []Member
for _, member := range t.Members {
if !member.IsBodyMember() {
result = append(result, member)
}
}
return result
}
// GetTagMembers returns all given key fields
func (t DefineStruct) GetTagMembers(tagKey string) []Member {
var result []Member
for _, member := range t.Members {
if member.IsTagMember(tagKey) {
result = append(result, member)
}
}
return result
}
// JoinedDoc joins comments and summary value in AtDoc
func (r Route) JoinedDoc() string {
doc := r.AtDoc.Text
if r.AtDoc.Properties != nil {
doc += r.AtDoc.Properties[defaultSummaryKey]
}
doc += strings.Join(r.Docs, " ")
return strings.TrimSpace(doc)
}
// GetAnnotation returns the value by specified key from @server
func (r Route) GetAnnotation(key string) string {
if r.AtServerAnnotation.Properties == nil {
return ""
}
return r.AtServerAnnotation.Properties[key]
}
// GetAnnotation returns the value by specified key from @server
func (g Group) GetAnnotation(key string) string {
if g.Annotation.Properties == nil {
return ""
}
return g.Annotation.Properties[key]
}
// ResponseTypeName returns response type name of route
func (r Route) ResponseTypeName() string {
if r.ResponseType == nil {
return ""
}
return r.ResponseType.Name()
}
// RequestTypeName returns request type name of route
func (r Route) RequestTypeName() string {
if r.RequestType == nil {
return ""
}
return r.RequestType.Name()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/name.go | tools/goctl/api/spec/name.go | package spec
// Name returns a basic string, such as int32,int64
func (t PrimitiveType) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t PrimitiveType) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t PrimitiveType) Documents() []string {
return nil
}
// Name returns a structure string, such as User
func (t DefineStruct) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t DefineStruct) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t DefineStruct) Documents() []string {
return t.Docs
}
// Name returns a structure string, such as User
func (t NestedStruct) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t NestedStruct) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t NestedStruct) Documents() []string {
return t.Docs
}
// Name returns a map string, such as map[string]int
func (t MapType) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t MapType) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t MapType) Documents() []string {
return nil
}
// Name returns a slice string, such as []int
func (t ArrayType) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t ArrayType) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t ArrayType) Documents() []string {
return nil
}
// Name returns a pointer string, such as *User
func (t PointerType) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t PointerType) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t PointerType) Documents() []string {
return nil
}
// Name returns an interface string, Its fixed value is any
func (t InterfaceType) Name() string {
return t.RawName
}
// Comments returns the comments of struct
func (t InterfaceType) Comments() []string {
return nil
}
// Documents returns the documents of struct
func (t InterfaceType) Documents() []string {
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/spec/example_test.go | tools/goctl/api/spec/example_test.go | package spec_test
import (
"fmt"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)
func ExampleMember_GetEnumOptions() {
member := spec.Member{
Tag: `json:"foo,options=foo|bar|options|123"`,
}
fmt.Println(member.GetEnumOptions())
// Output:
// [foo bar options 123]
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/docgen/gen.go | tools/goctl/api/docgen/gen.go | package docgen
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
// VarStringDir describes a directory.
VarStringDir string
// VarStringOutput describes an output directory.
VarStringOutput string
)
// DocCommand generate Markdown doc file
func DocCommand(_ *cobra.Command, _ []string) error {
dir := VarStringDir
if len(dir) == 0 {
return errors.New("missing -dir")
}
outputDir := VarStringOutput
if len(outputDir) == 0 {
var err error
outputDir, err = os.Getwd()
if err != nil {
return err
}
}
if !pathx.FileExists(dir) {
return fmt.Errorf("dir %s not exist", dir)
}
dir, err := filepath.Abs(dir)
if err != nil {
return err
}
files, err := filePathWalkDir(dir)
if err != nil {
return err
}
for _, p := range files {
api, err := parser.Parse(p)
if err != nil {
return fmt.Errorf("parse file: %s, err: %w", p, err)
}
api.Service = api.Service.JoinPrefix()
err = genDoc(api, filepath.Dir(filepath.Join(outputDir, p[len(dir):])),
strings.Replace(p[len(filepath.Dir(p)):], ".api", ".md", 1))
if err != nil {
return err
}
}
return nil
}
func filePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && strings.HasSuffix(path, ".api") {
files = append(files, path)
}
return nil
})
return files, err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/docgen/doc.go | tools/goctl/api/docgen/doc.go | package docgen
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"io"
"strconv"
"strings"
"github.com/zeromicro/go-zero/core/stringx"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/util"
)
//go:embed markdown.tpl
var markdownTemplate string
func genDoc(api *spec.ApiSpec, dir, filename string) error {
if len(api.Service.Routes()) == 0 {
return nil
}
fp, _, err := apiutil.MaybeCreateFile(dir, "", filename)
if err != nil {
return err
}
defer fp.Close()
var builder strings.Builder
for index, route := range api.Service.Routes() {
routeComment := route.JoinedDoc()
if len(routeComment) == 0 {
routeComment = "N/A"
}
requestContent, err := buildDoc(route.RequestType, api.Types)
if err != nil {
return err
}
responseContent, err := buildDoc(route.ResponseType, api.Types)
if err != nil {
return err
}
t := template.Must(template.New("markdownTemplate").Parse(markdownTemplate))
var tmplBytes bytes.Buffer
err = t.Execute(&tmplBytes, map[string]string{
"index": strconv.Itoa(index + 1),
"routeComment": routeComment,
"method": strings.ToUpper(route.Method),
"uri": route.Path,
"requestType": "`" + stringx.TakeOne(route.RequestTypeName(), "-") + "`",
"responseType": "`" + stringx.TakeOne(route.ResponseTypeName(), "-") + "`",
"requestContent": requestContent,
"responseContent": responseContent,
})
if err != nil {
return err
}
builder.Write(tmplBytes.Bytes())
}
_, err = fp.WriteString(strings.Replace(builder.String(), """, `"`, -1))
return err
}
func buildDoc(route spec.Type, types []spec.Type) (string, error) {
if route == nil || len(route.Name()) == 0 {
return "", nil
}
tps := make([]spec.Type, 0)
tps = append(tps, route)
if definedType, ok := route.(spec.DefineStruct); ok {
associatedTypes(definedType, &tps)
}
value, err := buildTypes(tps, types)
if err != nil {
return "", err
}
return fmt.Sprintf("\n\n```golang\n%s\n```\n", value), nil
}
func associatedTypes(tp spec.DefineStruct, tps *[]spec.Type) {
hasAdded := false
for _, item := range *tps {
if item.Name() == tp.Name() {
hasAdded = true
break
}
}
if !hasAdded {
*tps = append(*tps, tp)
}
for _, item := range tp.Members {
if definedType, ok := item.Type.(spec.DefineStruct); ok {
associatedTypes(definedType, tps)
}
}
}
// buildTypes gen types to string
func buildTypes(types, all []spec.Type) (string, error) {
var builder strings.Builder
first := true
for _, tp := range types {
if first {
first = false
} else {
builder.WriteString("\n\n")
}
if err := writeType(&builder, tp, all); err != nil {
return "", apiutil.WrapErr(err, "Type "+tp.Name()+" generate error")
}
}
return builder.String(), nil
}
func writeType(writer io.Writer, tp spec.Type, all []spec.Type) error {
fmt.Fprintf(writer, "type %s struct {\n", util.Title(tp.Name()))
if err := writerMembers(writer, tp, all); err != nil {
return err
}
fmt.Fprintf(writer, "}")
return nil
}
func writerMembers(writer io.Writer, tp spec.Type, all []spec.Type) error {
structType, ok := tp.(spec.DefineStruct)
if !ok {
return fmt.Errorf("unspport struct type: %s", tp.Name())
}
getTargetType := func(tp string) spec.Type {
for _, v := range all {
if v.Name() == tp {
return v
}
}
return nil
}
for _, member := range structType.Members {
if member.IsInline {
inlineType := getTargetType(member.Type.Name())
if inlineType == nil {
if _, err := fmt.Fprintf(writer, "%s\n", strings.Title(member.Type.Name())); err != nil {
return err
}
} else {
if err := writerMembers(writer, inlineType, all); err != nil {
return err
}
}
continue
}
if err := writeProperty(writer, member.Name, member.Tag, member.GetComment(), member.Type, 1); err != nil {
return err
}
}
return nil
}
func writeProperty(writer io.Writer, name, tag, comment string, tp spec.Type, indent int) error {
apiutil.WriteIndent(writer, indent)
var err error
if len(comment) > 0 {
comment = strings.TrimPrefix(comment, "//")
comment = "//" + comment
_, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp.Name(), tag, comment)
} else {
_, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp.Name(), tag)
}
return err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/format/format.go | tools/goctl/api/format/format.go | package format
import (
"bufio"
"errors"
"fmt"
"go/format"
"go/scanner"
"io"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/pkg/env"
apiF "github.com/zeromicro/go-zero/tools/goctl/pkg/parser/api/format"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
leftParenthesis = "("
rightParenthesis = ")"
leftBrace = "{"
rightBrace = "}"
)
var (
// VarBoolUseStdin describes whether to use stdin or not.
VarBoolUseStdin bool
// VarBoolSkipCheckDeclare describes whether to skip.
VarBoolSkipCheckDeclare bool
// VarStringDir describes the directory.
VarStringDir string
// VarBoolIgnore describes whether to ignore.
VarBoolIgnore bool
)
// GoFormatApi format api file
func GoFormatApi(_ *cobra.Command, _ []string) error {
var be errorx.BatchError
if VarBoolUseStdin {
if env.UseExperimental() {
data, err := io.ReadAll(os.Stdin)
if err != nil {
be.Add(err)
} else {
if err := apiF.Source(data, os.Stdout); err != nil {
be.Add(err)
}
}
} else {
if err := apiFormatReader(os.Stdin, VarStringDir, VarBoolSkipCheckDeclare); err != nil {
be.Add(err)
}
}
} else {
if len(VarStringDir) == 0 {
return errors.New("missing -dir")
}
_, err := os.Lstat(VarStringDir)
if err != nil {
return errors.New(VarStringDir + ": No such file or directory")
}
err = filepath.Walk(VarStringDir, func(path string, fi os.FileInfo, errBack error) (err error) {
if strings.HasSuffix(path, ".api") {
if err := ApiFormatByPath(path, VarBoolSkipCheckDeclare); err != nil {
be.Add(util.WrapErr(err, fi.Name()))
}
}
return nil
})
be.Add(err)
}
if be.NotNil() {
scanner.PrintError(os.Stderr, be.Err())
os.Exit(1)
}
return be.Err()
}
// apiFormatReader
// filename is needed when there are `import` literals.
func apiFormatReader(reader io.Reader, filename string, skipCheckDeclare bool) error {
data, err := io.ReadAll(reader)
if err != nil {
return err
}
result, err := apiFormat(string(data), skipCheckDeclare, filename)
if err != nil {
return err
}
_, err = fmt.Print(result)
return err
}
// ApiFormatByPath format api from file path
func ApiFormatByPath(apiFilePath string, skipCheckDeclare bool) error {
if env.UseExperimental() {
return apiF.File(apiFilePath)
}
data, err := os.ReadFile(apiFilePath)
if err != nil {
return err
}
abs, err := filepath.Abs(apiFilePath)
if err != nil {
return err
}
result, err := apiFormat(string(data), skipCheckDeclare, abs)
if err != nil {
return err
}
_, err = parser.ParseContentWithParserSkipCheckTypeDeclaration(result, abs)
if err != nil {
return err
}
return os.WriteFile(apiFilePath, []byte(result), os.ModePerm)
}
func apiFormat(data string, skipCheckDeclare bool, filename ...string) (string, error) {
var err error
if skipCheckDeclare {
_, err = parser.ParseContentWithParserSkipCheckTypeDeclaration(data, filename...)
} else {
_, err = parser.ParseContent(data, filename...)
}
if err != nil {
return "", err
}
var builder strings.Builder
s := bufio.NewScanner(strings.NewReader(data))
tapCount := 0
newLineCount := 0
var preLine string
for s.Scan() {
line := strings.TrimSpace(s.Text())
if len(line) == 0 {
if newLineCount > 0 {
continue
}
newLineCount++
} else {
if preLine == rightBrace {
builder.WriteString(pathx.NL)
}
newLineCount = 0
}
if tapCount == 0 {
ft, err := formatGoTypeDef(line, s, &builder)
if err != nil {
return "", err
}
if ft {
continue
}
}
noCommentLine := util.RemoveComment(line)
if noCommentLine == rightParenthesis || noCommentLine == rightBrace {
tapCount--
}
if tapCount < 0 {
line := strings.TrimSuffix(noCommentLine, rightBrace)
line = strings.TrimSpace(line)
if strings.HasSuffix(line, leftBrace) {
tapCount++
}
}
if line != "" {
util.WriteIndent(&builder, tapCount)
}
builder.WriteString(line + pathx.NL)
if strings.HasSuffix(noCommentLine, leftParenthesis) || strings.HasSuffix(noCommentLine, leftBrace) {
tapCount++
}
preLine = line
}
return strings.TrimSpace(builder.String()), nil
}
func formatGoTypeDef(line string, scanner *bufio.Scanner, builder *strings.Builder) (bool, error) {
noCommentLine := util.RemoveComment(line)
tokenCount := 0
if strings.HasPrefix(noCommentLine, "type") && (strings.HasSuffix(noCommentLine, leftParenthesis) ||
strings.HasSuffix(noCommentLine, leftBrace)) {
var typeBuilder strings.Builder
typeBuilder.WriteString(mayInsertStructKeyword(line, &tokenCount) + pathx.NL)
for scanner.Scan() {
noCommentLine := util.RemoveComment(scanner.Text())
typeBuilder.WriteString(mayInsertStructKeyword(scanner.Text(), &tokenCount) + pathx.NL)
if noCommentLine == rightBrace || noCommentLine == rightParenthesis {
tokenCount--
}
if tokenCount == 0 {
ts, err := format.Source([]byte(typeBuilder.String()))
if err != nil {
return false, errors.New("error format \n" + typeBuilder.String())
}
result := strings.ReplaceAll(string(ts), " struct ", " ")
result = strings.ReplaceAll(result, "type ()", "")
builder.WriteString(result)
break
}
}
return true, nil
}
return false, nil
}
func mayInsertStructKeyword(line string, token *int) string {
insertStruct := func() string {
if strings.Contains(line, " struct") {
return line
}
index := strings.Index(line, leftBrace)
return line[:index] + " struct " + line[index:]
}
noCommentLine := util.RemoveComment(line)
if strings.HasSuffix(noCommentLine, leftBrace) {
*token++
return insertStruct()
}
if strings.HasSuffix(noCommentLine, rightBrace) {
noCommentLine = strings.TrimSuffix(noCommentLine, rightBrace)
noCommentLine = util.RemoveComment(noCommentLine)
if strings.HasSuffix(noCommentLine, leftBrace) {
return insertStruct()
}
}
if strings.HasSuffix(noCommentLine, leftParenthesis) {
*token++
}
if strings.Contains(noCommentLine, "`") {
return util.UpperFirst(strings.TrimSpace(line))
}
return line
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/format/format_test.go | tools/goctl/api/format/format_test.go | package format
import (
"fmt"
"io/fs"
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
notFormattedStr = `
type Request struct {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response struct {
Message string ` + "`" + `json:"message"` + "`" + `
Students []Student ` + "`" + `json:"students"` + "`" + `
}
service A-api {
@server(
handler: GreetHandler
)
get /greet/from/:name(Request) returns (Response)
@server(
handler: GreetHandler2
)
get /greet/from2/:name(Request) returns (Response)
}
`
formattedStr = `type Request {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response {
Message string ` + "`" + `json:"message"` + "`" + `
Students []Student ` + "`" + `json:"students"` + "`" + `
}
service A-api {
@server(
handler: GreetHandler
)
get /greet/from/:name(Request) returns (Response)
@server(
handler: GreetHandler2
)
get /greet/from2/:name(Request) returns (Response)
}`
)
func TestFormat(t *testing.T) {
r, err := apiFormat(notFormattedStr, true)
assert.Nil(t, err)
assert.Equal(t, formattedStr, r)
_, err = apiFormat(notFormattedStr, false)
assert.Errorf(t, err, " line 7:13 can not find declaration 'Student' in context")
}
func Test_apiFormatReader_issue1721(t *testing.T) {
dir, err := os.MkdirTemp("", "goctl-api-format")
require.NoError(t, err)
defer os.RemoveAll(dir)
subDir := path.Join(dir, "sub")
err = os.MkdirAll(subDir, fs.ModePerm)
require.NoError(t, err)
importedFilename := path.Join(dir, "foo.api")
err = os.WriteFile(importedFilename, []byte{}, fs.ModePerm)
require.NoError(t, err)
filename := path.Join(subDir, "bar.api")
err = os.WriteFile(filename, []byte(fmt.Sprintf(`import "%s"`, importedFilename)), 0o644)
require.NoError(t, err)
f, err := os.Open(filename)
require.NoError(t, err)
err = apiFormatReader(f, filename, false)
assert.NoError(t, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/genpacket.go | tools/goctl/api/tsgen/genpacket.go | package tsgen
import (
_ "embed"
"fmt"
"path"
"strings"
"text/template"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
//go:embed handler.tpl
var handlerTemplate string
func genHandler(dir, webAPI, caller string, api *spec.ApiSpec, unwrapAPI bool) error {
filename := strings.Replace(api.Service.Name, "-api", "", 1) + ".ts"
if err := pathx.RemoveIfExist(path.Join(dir, filename)); err != nil {
return err
}
fp, created, err := apiutil.MaybeCreateFile(dir, "", filename)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
imports := ""
if len(caller) == 0 {
caller = "webapi"
}
importCaller := caller
if unwrapAPI {
importCaller = "{ " + importCaller + " }"
}
if len(webAPI) > 0 {
imports += `import ` + importCaller + ` from ` + `"./gocliRequest"`
}
if len(api.Types) != 0 {
if len(imports) > 0 {
imports += pathx.NL
}
outputFile := apiutil.ComponentName(api)
imports += fmt.Sprintf(`import * as components from "%s"`, "./"+outputFile)
imports += fmt.Sprintf(`%sexport * from "%s"`, pathx.NL, "./"+outputFile)
}
apis, err := genAPI(api, caller)
if err != nil {
return err
}
t := template.Must(template.New("handlerTemplate").Parse(handlerTemplate))
return t.Execute(fp, map[string]string{
"imports": imports,
"apis": strings.TrimSpace(apis),
})
}
func genAPI(api *spec.ApiSpec, caller string) (string, error) {
var builder strings.Builder
for _, group := range api.Service.Groups {
for _, route := range group.Routes {
handler := route.Handler
if len(handler) == 0 {
return "", fmt.Errorf("missing handler annotation for route %q", route.Path)
}
handler = util.Untitle(handler)
handler = strings.Replace(handler, "Handler", "", 1)
comment := commentForRoute(route)
if len(comment) > 0 {
fmt.Fprintf(&builder, "%s\n", comment)
}
fmt.Fprintf(&builder, "export function %s(%s) {\n", handler, paramsForRoute(route))
writeIndent(&builder, 1)
responseGeneric := "<null>"
if len(route.ResponseTypeName()) > 0 {
val, err := goTypeToTs(route.ResponseType, true)
if err != nil {
return "", err
}
responseGeneric = fmt.Sprintf("<%s>", val)
}
fmt.Fprintf(&builder, `return %s.%s%s(%s)`, caller, strings.ToLower(route.Method),
util.Title(responseGeneric), callParamsForRoute(route, group))
builder.WriteString("\n}\n\n")
}
}
apis := builder.String()
return apis, nil
}
func paramsForRoute(route spec.Route) string {
if route.RequestType == nil {
return ""
}
hasParams := pathHasParams(route)
hasBody := hasRequestBody(route)
hasHeader := hasRequestHeader(route)
hasPath := hasRequestPath(route)
rt, err := goTypeToTs(route.RequestType, true)
if err != nil {
fmt.Println(err.Error())
return ""
}
var params []string
if hasParams {
params = append(params, fmt.Sprintf("params: %s", rt+"Params"))
}
if hasBody {
params = append(params, fmt.Sprintf("req: %s", rt))
}
if hasHeader {
params = append(params, fmt.Sprintf("headers: %s", rt+"Headers"))
}
if hasPath {
ds, ok := route.RequestType.(spec.DefineStruct)
if !ok {
fmt.Printf("invalid route.RequestType: {%v}\n", route.RequestType)
}
members := ds.GetTagMembers(pathTagKey)
for _, member := range members {
tags := member.Tags()
if len(tags) > 0 && tags[0].Key == pathTagKey {
valueType, err := goTypeToTs(member.Type, false)
if err != nil {
fmt.Println(err.Error())
return ""
}
params = append(params, fmt.Sprintf("%s: %s", tags[0].Name, valueType))
}
}
}
return strings.Join(params, ", ")
}
func commentForRoute(route spec.Route) string {
var builder strings.Builder
comment := route.JoinedDoc()
builder.WriteString("/**")
builder.WriteString("\n * @description " + comment)
hasParams := pathHasParams(route)
hasBody := hasRequestBody(route)
hasHeader := hasRequestHeader(route)
if hasParams {
builder.WriteString("\n * @param params")
}
if hasBody {
builder.WriteString("\n * @param req")
}
if hasHeader {
builder.WriteString("\n * @param headers")
}
builder.WriteString("\n */")
return builder.String()
}
func callParamsForRoute(route spec.Route, group spec.Group) string {
hasParams := pathHasParams(route)
hasBody := hasRequestBody(route)
hasHeader := hasRequestHeader(route)
var params = []string{pathForRoute(route, group)}
if hasParams {
params = append(params, "params")
}
if hasBody {
params = append(params, "req")
}
if hasHeader {
params = append(params, "headers")
}
return strings.Join(params, ", ")
}
func pathForRoute(route spec.Route, group spec.Group) string {
prefix := group.GetAnnotation(pathPrefix)
routePath := route.Path
if strings.Contains(routePath, ":") {
pathSlice := strings.Split(routePath, "/")
for i, part := range pathSlice {
if strings.Contains(part, ":") {
pathSlice[i] = fmt.Sprintf("${%s}", part[1:])
}
}
routePath = strings.Join(pathSlice, "/")
}
if len(prefix) == 0 {
return "`" + routePath + "`"
}
prefix = strings.TrimPrefix(prefix, `"`)
prefix = strings.TrimSuffix(prefix, `"`)
return fmt.Sprintf("`%s/%s`", prefix, strings.TrimPrefix(routePath, "/"))
}
func pathHasParams(route spec.Route) bool {
ds, ok := route.RequestType.(spec.DefineStruct)
if !ok {
return false
}
return len(ds.Members) != len(ds.GetBodyMembers())
}
func hasRequestBody(route spec.Route) bool {
ds, ok := route.RequestType.(spec.DefineStruct)
if !ok {
return false
}
return len(route.RequestTypeName()) > 0 && len(ds.GetBodyMembers()) > 0
}
func hasRequestPath(route spec.Route) bool {
ds, ok := route.RequestType.(spec.DefineStruct)
if !ok {
return false
}
return len(route.RequestTypeName()) > 0 && len(ds.GetTagMembers(pathTagKey)) > 0
}
func hasRequestHeader(route spec.Route) bool {
ds, ok := route.RequestType.(spec.DefineStruct)
if !ok {
return false
}
return len(route.RequestTypeName()) > 0 && len(ds.GetTagMembers(headerTagKey)) > 0
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/gen.go | tools/goctl/api/tsgen/gen.go | package tsgen
import (
"errors"
"fmt"
"github.com/gookit/color"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
// VarStringDir describes a directory.
VarStringDir string
// VarStringAPI describes an API file.
VarStringAPI string
// VarStringWebAPI describes a web API file.
VarStringWebAPI string
// VarStringCaller describes a caller.
VarStringCaller string
// VarBoolUnWrap describes whether wrap or not.
VarBoolUnWrap bool
)
// TsCommand provides the entry to generate typescript codes
func TsCommand(_ *cobra.Command, _ []string) error {
apiFile := VarStringAPI
dir := VarStringDir
webAPI := VarStringWebAPI
caller := VarStringCaller
unwrapAPI := VarBoolUnWrap
if len(apiFile) == 0 {
return errors.New("missing -api")
}
if len(dir) == 0 {
return errors.New("missing -dir")
}
if len(webAPI) == 0 {
webAPI = "."
}
api, err := parser.Parse(apiFile)
if err != nil {
fmt.Println(color.Red.Render("Failed"))
return err
}
if err := api.Validate(); err != nil {
return err
}
api.Service = api.Service.JoinPrefix()
logx.Must(pathx.MkdirIfNotExist(dir))
logx.Must(genRequest(dir))
logx.Must(genHandler(dir, webAPI, caller, api, unwrapAPI))
logx.Must(genComponents(dir, api))
fmt.Println(color.Green.Render("Done."))
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/util.go | tools/goctl/api/tsgen/util.go | package tsgen
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/util"
)
const (
formTagKey = "form"
pathTagKey = "path"
headerTagKey = "header"
)
func writeProperty(writer io.Writer, member spec.Member, indent int) error {
writeIndent(writer, indent)
ty, err := genTsType(member, indent)
if err != nil {
return err
}
optionalTag := ""
if member.IsOptional() || member.IsOmitEmpty() {
optionalTag = "?"
}
name, err := member.GetPropertyName()
if err != nil {
return err
}
if strings.Contains(name, "-") {
name = fmt.Sprintf("'%s'", name)
}
comment := member.GetComment()
if len(comment) > 0 {
comment = strings.TrimPrefix(comment, "//")
comment = " // " + strings.TrimSpace(comment)
}
if len(member.Docs) > 0 {
fmt.Fprintf(writer, "%s\n", strings.Join(member.Docs, ""))
writeIndent(writer, indent)
}
_, err = fmt.Fprintf(writer, "%s%s: %s%s\n", name, optionalTag, ty, comment)
return err
}
func writeIndent(writer io.Writer, indent int) {
for i := 0; i < indent; i++ {
fmt.Fprint(writer, "\t")
}
}
func genTsType(m spec.Member, indent int) (ty string, err error) {
v, ok := m.Type.(spec.NestedStruct)
if ok {
writer := bytes.NewBuffer(nil)
_, err := fmt.Fprintf(writer, "{\n")
if err != nil {
return "", err
}
if err := writeMembers(writer, v, false, indent+1); err != nil {
return "", err
}
writeIndent(writer, indent)
_, err = fmt.Fprintf(writer, "}")
if err != nil {
return "", err
}
return writer.String(), nil
}
ty, err = goTypeToTs(m.Type, false)
if enums := m.GetEnumOptions(); enums != nil {
if ty == "string" {
for i := range enums {
enums[i] = "'" + enums[i] + "'"
}
}
ty = strings.Join(enums, " | ")
}
return
}
func goTypeToTs(tp spec.Type, fromPacket bool) (string, error) {
switch v := tp.(type) {
case spec.DefineStruct:
return addPrefix(tp, fromPacket), nil
case spec.PrimitiveType:
r, ok := primitiveType(tp.Name())
if !ok {
return "", errors.New("unsupported primitive type " + tp.Name())
}
return r, nil
case spec.MapType:
valueType, err := goTypeToTs(v.Value, fromPacket)
if err != nil {
return "", err
}
return fmt.Sprintf("{ [key: string]: %s }", valueType), nil
case spec.ArrayType:
if tp.Name() == "[]byte" {
return "Blob", nil
}
valueType, err := goTypeToTs(v.Value, fromPacket)
if err != nil {
return "", err
}
return fmt.Sprintf("Array<%s>", valueType), nil
case spec.InterfaceType:
return "any", nil
case spec.PointerType:
return goTypeToTs(v.Type, fromPacket)
}
return "", errors.New("unsupported type " + tp.Name())
}
func addPrefix(tp spec.Type, fromPacket bool) string {
if fromPacket {
return packagePrefix + util.Title(tp.Name())
}
return util.Title(tp.Name())
}
func primitiveType(tp string) (string, bool) {
switch tp {
case "string":
return "string", true
case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64":
return "number", true
case "float", "float32", "float64":
return "number", true
case "bool":
return "boolean", true
case "[]byte":
return "Blob", true
case "interface{}":
return "any", true
}
return "", false
}
func writeType(writer io.Writer, tp spec.Type) error {
fmt.Fprintf(writer, "export interface %s {\n", util.Title(tp.Name()))
if err := writeMembers(writer, tp, false, 1); err != nil {
return err
}
fmt.Fprintf(writer, "}\n")
return genParamsTypesIfNeed(writer, tp)
}
func genParamsTypesIfNeed(writer io.Writer, tp spec.Type) error {
definedType, ok := tp.(spec.DefineStruct)
if !ok {
return errors.New("no members of type " + tp.Name())
}
members := definedType.GetNonBodyMembers()
if len(members) == 0 {
return nil
}
fmt.Fprintf(writer, "export interface %sParams {\n", util.Title(tp.Name()))
if err := writeTagMembers(writer, tp, formTagKey); err != nil {
return err
}
fmt.Fprintf(writer, "}\n")
if len(definedType.GetTagMembers(headerTagKey)) > 0 {
fmt.Fprintf(writer, "export interface %sHeaders {\n", util.Title(tp.Name()))
if err := writeTagMembers(writer, tp, headerTagKey); err != nil {
return err
}
fmt.Fprintf(writer, "}\n")
}
return nil
}
func writeMembers(writer io.Writer, tp spec.Type, isParam bool, indent int) error {
definedType, ok := tp.(spec.DefineStruct)
if !ok {
pointType, ok := tp.(spec.PointerType)
if ok {
return writeMembers(writer, pointType.Type, isParam, indent)
}
return fmt.Errorf("type %s not supported", tp.Name())
}
members := definedType.GetBodyMembers()
if isParam {
members = definedType.GetNonBodyMembers()
}
for _, member := range members {
if member.IsInline {
if err := writeMembers(writer, member.Type, isParam, indent); err != nil {
return err
}
continue
}
if err := writeProperty(writer, member, indent); err != nil {
return apiutil.WrapErr(err, " type "+tp.Name())
}
}
return nil
}
func writeTagMembers(writer io.Writer, tp spec.Type, tagKey string) error {
definedType, ok := tp.(spec.DefineStruct)
if !ok {
pointType, ok := tp.(spec.PointerType)
if ok {
return writeTagMembers(writer, pointType.Type, tagKey)
}
return fmt.Errorf("type %s not supported", tp.Name())
}
members := definedType.GetTagMembers(tagKey)
for _, member := range members {
if member.IsInline {
if err := writeTagMembers(writer, member.Type, tagKey); err != nil {
return err
}
continue
}
if err := writeProperty(writer, member, 1); err != nil {
return apiutil.WrapErr(err, " type "+tp.Name())
}
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/gencomponents.go | tools/goctl/api/tsgen/gencomponents.go | package tsgen
import (
_ "embed"
"path"
"strings"
"text/template"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util"
"github.com/zeromicro/go-zero/tools/goctl/internal/version"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
//go:embed components.tpl
var componentsTemplate string
// BuildTypes generates the typescript code for the types.
func BuildTypes(types []spec.Type) (string, error) {
var builder strings.Builder
first := true
for _, tp := range types {
if first {
first = false
} else {
builder.WriteString("\n")
}
if err := writeType(&builder, tp); err != nil {
return "", apiutil.WrapErr(err, "Type "+tp.Name()+" generate error")
}
}
return builder.String(), nil
}
func genComponents(dir string, api *spec.ApiSpec) error {
types := api.Types
if len(types) == 0 {
return nil
}
val, err := BuildTypes(types)
if err != nil {
return err
}
outputFile := apiutil.ComponentName(api) + ".ts"
filename := path.Join(dir, outputFile)
if err := pathx.RemoveIfExist(filename); err != nil {
return err
}
fp, created, err := apiutil.MaybeCreateFile(dir, ".", outputFile)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
t := template.Must(template.New("componentsTemplate").Parse(componentsTemplate))
return t.Execute(fp, map[string]string{
"componentTypes": val,
"version": version.BuildVersion,
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/vars.go | tools/goctl/api/tsgen/vars.go | package tsgen
const (
packagePrefix = "components."
pathPrefix = "pathPrefix"
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/genrequest.go | tools/goctl/api/tsgen/genrequest.go | package tsgen
import (
_ "embed"
"os"
"path/filepath"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
//go:embed request.ts
var requestTemplate string
func genRequest(dir string) error {
abs, err := filepath.Abs(dir)
if err != nil {
return err
}
filename := filepath.Join(abs, "gocliRequest.ts")
if pathx.FileExists(filename) {
return nil
}
return os.WriteFile(filename, []byte(requestTemplate), 0644)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/tsgen/util_test.go | tools/goctl/api/tsgen/util_test.go | package tsgen
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)
func TestGenTsType(t *testing.T) {
member := spec.Member{
Name: "foo",
Type: spec.PrimitiveType{RawName: "string"},
Tag: `json:"foo,options=foo|bar|options|123"`,
Comment: "",
Docs: nil,
IsInline: false,
}
ty, err := genTsType(member, 1)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, `'foo' | 'bar' | 'options' | '123'`, ty)
member.IsInline = true
ty, err = genTsType(member, 1)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, `'foo' | 'bar' | 'options' | '123'`, ty)
member.Type = spec.PrimitiveType{RawName: "int"}
member.Tag = `json:"foo,options=1|3|4|123"`
ty, err = genTsType(member, 1)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, `1 | 3 | 4 | 123`, ty)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/parser.go | tools/goctl/api/parser/parser.go | package parser
import (
"fmt"
"path/filepath"
"unicode"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/pkg/env"
apiParser "github.com/zeromicro/go-zero/tools/goctl/pkg/parser/api/parser"
)
type parser struct {
ast *ast.Api
spec *spec.ApiSpec
}
// Parse parses the api file.
// Deprecated: use tools/goctl/pkg/parser/api/parser/parser.go:18 instead,
// it will be removed in the future.
func Parse(filename string) (*spec.ApiSpec, error) {
if env.UseExperimental() {
return apiParser.Parse(filename, "")
}
astParser := ast.NewParser(ast.WithParserPrefix(filepath.Base(filename)), ast.WithParserDebug())
parsedApi, err := astParser.Parse(filename)
if err != nil {
return nil, err
}
apiSpec := new(spec.ApiSpec)
p := parser{ast: parsedApi, spec: apiSpec}
err = p.convert2Spec()
if err != nil {
return nil, err
}
return apiSpec, nil
}
func parseContent(content string, skipCheckTypeDeclaration bool, filename ...string) (*spec.ApiSpec, error) {
var astParser *ast.Parser
if skipCheckTypeDeclaration {
astParser = ast.NewParser(ast.WithParserSkipCheckTypeDeclaration())
} else {
astParser = ast.NewParser()
}
parsedApi, err := astParser.ParseContent(content, filename...)
if err != nil {
return nil, err
}
apiSpec := new(spec.ApiSpec)
p := parser{ast: parsedApi, spec: apiSpec}
err = p.convert2Spec()
if err != nil {
return nil, err
}
return apiSpec, nil
}
// Deprecated: use tools/goctl/pkg/parser/api/parser/parser.go:18 instead,
// it will be removed in the future.
// ParseContent parses the api content
func ParseContent(content string, filename ...string) (*spec.ApiSpec, error) {
return parseContent(content, false, filename...)
}
// Deprecated: use tools/goctl/pkg/parser/api/parser/parser.go:18 instead,
// it will be removed in the future.
// ParseContentWithParserSkipCheckTypeDeclaration parses the api content with skip check type declaration
func ParseContentWithParserSkipCheckTypeDeclaration(content string, filename ...string) (*spec.ApiSpec, error) {
return parseContent(content, true, filename...)
}
func (p parser) convert2Spec() error {
p.fillInfo()
p.fillSyntax()
p.fillImport()
err := p.fillTypes()
if err != nil {
return err
}
return p.fillService()
}
func (p parser) fillInfo() {
properties := make(map[string]string)
if p.ast.Info != nil {
for _, kv := range p.ast.Info.Kvs {
properties[kv.Key.Text()] = kv.Value.Text()
}
}
p.spec.Info.Properties = properties
}
func (p parser) fillSyntax() {
if p.ast.Syntax != nil {
p.spec.Syntax = spec.ApiSyntax{
Version: p.ast.Syntax.Version.Text(),
Doc: p.stringExprs(p.ast.Syntax.DocExpr),
Comment: p.stringExprs([]ast.Expr{p.ast.Syntax.CommentExpr}),
}
}
}
func (p parser) fillImport() {
if len(p.ast.Import) > 0 {
for _, item := range p.ast.Import {
p.spec.Imports = append(p.spec.Imports, spec.Import{
Value: item.Value.Text(),
Doc: p.stringExprs(item.DocExpr),
Comment: p.stringExprs([]ast.Expr{item.CommentExpr}),
})
}
}
}
func (p parser) fillTypes() error {
for _, item := range p.ast.Type {
switch v := (item).(type) {
case *ast.TypeStruct:
members := make([]spec.Member, 0, len(v.Fields))
for _, item := range v.Fields {
members = append(members, p.fieldToMember(item))
}
p.spec.Types = append(p.spec.Types, spec.DefineStruct{
RawName: v.Name.Text(),
Members: members,
Docs: p.stringExprs(v.Doc()),
})
default:
return fmt.Errorf("unknown type %+v", v)
}
}
var types []spec.Type
for _, item := range p.spec.Types {
switch v := (item).(type) {
case spec.DefineStruct:
var members []spec.Member
for _, member := range v.Members {
switch v := member.Type.(type) {
case spec.DefineStruct:
tp, err := p.findDefinedType(v.RawName)
if err != nil {
return err
}
member.Type = *tp
}
members = append(members, member)
}
v.Members = members
types = append(types, v)
default:
return fmt.Errorf("unknown type %+v", v)
}
}
p.spec.Types = types
return nil
}
func (p parser) findDefinedType(name string) (*spec.Type, error) {
for _, item := range p.spec.Types {
if _, ok := item.(spec.DefineStruct); ok {
if item.Name() == name {
return &item, nil
}
}
}
return nil, fmt.Errorf("type %s not defined", name)
}
func (p parser) fieldToMember(field *ast.TypeField) spec.Member {
var name string
var tag string
if !field.IsAnonymous {
name = field.Name.Text()
if field.Tag != nil {
tag = field.Tag.Text()
}
}
return spec.Member{
Name: name,
Type: p.astTypeToSpec(field.DataType),
Tag: tag,
Comment: p.commentExprs(field.Comment()),
Docs: p.stringExprs(field.Doc()),
IsInline: field.IsAnonymous,
}
}
func (p parser) astTypeToSpec(in ast.DataType) spec.Type {
switch v := (in).(type) {
case *ast.Literal:
raw := v.Literal.Text()
if api.IsBasicType(raw) {
return spec.PrimitiveType{
RawName: raw,
}
}
return spec.DefineStruct{
RawName: raw,
}
case *ast.Interface:
return spec.InterfaceType{RawName: v.Literal.Text()}
case *ast.Map:
return spec.MapType{RawName: v.MapExpr.Text(), Key: v.Key.Text(), Value: p.astTypeToSpec(v.Value)}
case *ast.Array:
return spec.ArrayType{RawName: v.ArrayExpr.Text(), Value: p.astTypeToSpec(v.Literal)}
case *ast.Pointer:
raw := v.Name.Text()
if api.IsBasicType(raw) {
return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.PrimitiveType{RawName: raw}}
}
return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.DefineStruct{RawName: raw}}
}
panic(fmt.Sprintf("unsupported type %+v", in))
}
func (p parser) stringExprs(docs []ast.Expr) []string {
var result []string
for _, item := range docs {
if item == nil {
continue
}
result = append(result, item.Text())
}
return result
}
func (p parser) commentExprs(comment ast.Expr) string {
if comment == nil {
return ""
}
return comment.Text()
}
func (p parser) fillService() error {
var groups []spec.Group
for _, item := range p.ast.Service {
var group spec.Group
p.fillAtServer(item, &group)
for _, astRoute := range item.ServiceApi.ServiceRoute {
route := spec.Route{
AtServerAnnotation: spec.Annotation{},
Method: astRoute.Route.Method.Text(),
Path: astRoute.Route.Path.Text(),
Doc: p.stringExprs(astRoute.Route.DocExpr),
Comment: p.stringExprs([]ast.Expr{astRoute.Route.CommentExpr}),
}
if astRoute.AtHandler != nil {
route.Handler = astRoute.AtHandler.Name.Text()
route.HandlerDoc = append(route.HandlerDoc, p.stringExprs(astRoute.AtHandler.DocExpr)...)
route.HandlerComment = append(route.HandlerComment, p.stringExprs([]ast.Expr{astRoute.AtHandler.CommentExpr})...)
}
err := p.fillRouteAtServer(astRoute, &route)
if err != nil {
return err
}
if astRoute.Route.Req != nil {
route.RequestType = p.astTypeToSpec(astRoute.Route.Req.Name)
}
if astRoute.Route.Reply != nil {
route.ResponseType = p.astTypeToSpec(astRoute.Route.Reply.Name)
}
if astRoute.AtDoc != nil {
properties := make(map[string]string)
for _, kv := range astRoute.AtDoc.Kv {
properties[kv.Key.Text()] = kv.Value.Text()
}
route.AtDoc.Properties = properties
if astRoute.AtDoc.LineDoc != nil {
route.AtDoc.Text = astRoute.AtDoc.LineDoc.Text()
}
}
err = p.fillRouteType(&route)
if err != nil {
return err
}
group.Routes = append(group.Routes, route)
name := item.ServiceApi.Name.Text()
if len(p.spec.Service.Name) > 0 && p.spec.Service.Name != name {
return fmt.Errorf("multiple service names defined %s and %s",
name, p.spec.Service.Name)
}
p.spec.Service.Name = name
}
groups = append(groups, group)
}
p.spec.Service.Groups = groups
return nil
}
func (p parser) fillRouteAtServer(astRoute *ast.ServiceRoute, route *spec.Route) error {
if astRoute.AtServer != nil {
properties := make(map[string]string)
for _, kv := range astRoute.AtServer.Kv {
properties[kv.Key.Text()] = kv.Value.Text()
}
route.AtServerAnnotation.Properties = properties
if len(route.Handler) == 0 {
route.Handler = properties["handler"]
}
if len(route.Handler) == 0 {
return fmt.Errorf("missing handler annotation for %q", route.Path)
}
for _, char := range route.Handler {
if !unicode.IsDigit(char) && !unicode.IsLetter(char) {
return fmt.Errorf("route [%s] handler [%s] invalid, handler name should only contains letter or digit",
route.Path, route.Handler)
}
}
}
return nil
}
func (p parser) fillAtServer(item *ast.Service, group *spec.Group) {
if item.AtServer != nil {
properties := make(map[string]string)
for _, kv := range item.AtServer.Kv {
properties[kv.Key.Text()] = kv.Value.Text()
}
group.Annotation.Properties = properties
}
}
func (p parser) fillRouteType(route *spec.Route) error {
if route.RequestType != nil {
switch route.RequestType.(type) {
case spec.DefineStruct:
tp, err := p.findDefinedType(route.RequestType.Name())
if err != nil {
return err
}
route.RequestType = *tp
}
}
if route.ResponseType != nil {
switch route.ResponseType.(type) {
case spec.DefineStruct:
tp, err := p.findDefinedType(route.ResponseType.Name())
if err != nil {
return err
}
route.ResponseType = *tp
}
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/parser_test.go | tools/goctl/api/parser/parser_test.go | package parser
import (
_ "embed"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
)
//go:embed testdata/test.api
var testApi string
func TestParseContent(t *testing.T) {
sp, err := ParseContent(testApi)
assert.Nil(t, err)
assert.Equal(t, spec.Doc{`// syntax doc`}, sp.Syntax.Doc)
assert.Equal(t, spec.Doc{`// syntax comment`}, sp.Syntax.Comment)
for _, tp := range sp.Types {
if tp.Name() == "Request" {
assert.Equal(t, []string{`// type doc`}, tp.Documents())
}
}
for _, e := range sp.Service.Routes() {
if e.Handler == "GreetHandler" {
assert.Equal(t, spec.Doc{"// handler doc"}, e.HandlerDoc)
assert.Equal(t, spec.Doc{"// handler comment"}, e.HandlerComment)
}
}
}
func TestMissingService(t *testing.T) {
sp, err := ParseContent("")
assert.Nil(t, err)
err = sp.Validate()
assert.Equal(t, spec.ErrMissingService, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/baseparser_test.go | tools/goctl/api/parser/g4/gen/api/baseparser_test.go | package api
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMatch(t *testing.T) {
assert.False(t, matchRegex("v1ddd", versionRegex))
}
func TestImportRegex(t *testing.T) {
tests := []struct {
value string
matched bool
}{
{`"bar.api"`, true},
{`"foo/bar.api"`, true},
{`"/foo/bar.api"`, true},
{`"../foo/bar.api"`, true},
{`"../../foo/bar.api"`, true},
{`"//bar.api"`, false},
{`"/foo/foo_bar.api"`, true},
}
for _, tt := range tests {
t.Run(tt.value, func(t *testing.T) {
assert.Equal(t, tt.matched, matchRegex(tt.value, importValueRegex))
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser3.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser3.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 3
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
// ITypeBlockBodyContext is an interface to support dynamic dispatch.
type ITypeBlockBodyContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsTypeBlockBodyContext differentiates from other interfaces.
IsTypeBlockBodyContext()
}
type TypeBlockBodyContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyTypeBlockBodyContext() *TypeBlockBodyContext {
var p = new(TypeBlockBodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeBlockBody
return p
}
func (*TypeBlockBodyContext) IsTypeBlockBodyContext() {}
func NewTypeBlockBodyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeBlockBodyContext {
var p = new(TypeBlockBodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeBlockBody
return p
}
func (s *TypeBlockBodyContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeBlockBodyContext) TypeBlockStruct() ITypeBlockStructContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeBlockStructContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeBlockStructContext)
}
func (s *TypeBlockBodyContext) TypeBlockAlias() ITypeBlockAliasContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeBlockAliasContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeBlockAliasContext)
}
func (s *TypeBlockBodyContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeBlockBodyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeBlockBodyContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeBlockBody(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeBlockBody() (localctx ITypeBlockBodyContext) {
localctx = NewTypeBlockBodyContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 26, ApiParserParserRULE_typeBlockBody)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(153)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 8, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
{
p.SetState(151)
p.TypeBlockStruct()
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(152)
p.TypeBlockAlias()
}
}
return localctx
}
// ITypeStructContext is an interface to support dynamic dispatch.
type ITypeStructContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetStructName returns the structName token.
GetStructName() antlr.Token
// GetStructToken returns the structToken token.
GetStructToken() antlr.Token
// GetLbrace returns the lbrace token.
GetLbrace() antlr.Token
// GetRbrace returns the rbrace token.
GetRbrace() antlr.Token
// SetStructName sets the structName token.
SetStructName(antlr.Token)
// SetStructToken sets the structToken token.
SetStructToken(antlr.Token)
// SetLbrace sets the lbrace token.
SetLbrace(antlr.Token)
// SetRbrace sets the rbrace token.
SetRbrace(antlr.Token)
// IsTypeStructContext differentiates from other interfaces.
IsTypeStructContext()
}
type TypeStructContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
structName antlr.Token
structToken antlr.Token
lbrace antlr.Token
rbrace antlr.Token
}
func NewEmptyTypeStructContext() *TypeStructContext {
var p = new(TypeStructContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeStruct
return p
}
func (*TypeStructContext) IsTypeStructContext() {}
func NewTypeStructContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeStructContext {
var p = new(TypeStructContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeStruct
return p
}
func (s *TypeStructContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeStructContext) GetStructName() antlr.Token { return s.structName }
func (s *TypeStructContext) GetStructToken() antlr.Token { return s.structToken }
func (s *TypeStructContext) GetLbrace() antlr.Token { return s.lbrace }
func (s *TypeStructContext) GetRbrace() antlr.Token { return s.rbrace }
func (s *TypeStructContext) SetStructName(v antlr.Token) { s.structName = v }
func (s *TypeStructContext) SetStructToken(v antlr.Token) { s.structToken = v }
func (s *TypeStructContext) SetLbrace(v antlr.Token) { s.lbrace = v }
func (s *TypeStructContext) SetRbrace(v antlr.Token) { s.rbrace = v }
func (s *TypeStructContext) AllID() []antlr.TerminalNode {
return s.GetTokens(ApiParserParserID)
}
func (s *TypeStructContext) ID(i int) antlr.TerminalNode {
return s.GetToken(ApiParserParserID, i)
}
func (s *TypeStructContext) AllField() []IFieldContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IFieldContext)(nil)).Elem())
var tst = make([]IFieldContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IFieldContext)
}
}
return tst
}
func (s *TypeStructContext) Field(i int) IFieldContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFieldContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IFieldContext)
}
func (s *TypeStructContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeStructContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeStructContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeStruct(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeStruct() (localctx ITypeStructContext) {
localctx = NewTypeStructContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 28, ApiParserParserRULE_typeStruct)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
var _alt int
p.EnterOuterAlt(localctx, 1)
checkKeyword(p)
{
p.SetState(156)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeStructContext).structName = _m
}
p.SetState(158)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserID {
{
p.SetState(157)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeStructContext).structToken = _m
}
}
{
p.SetState(160)
var _m = p.Match(ApiParserParserT__3)
localctx.(*TypeStructContext).lbrace = _m
}
p.SetState(164)
p.GetErrorHandler().Sync(p)
_alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 10, p.GetParserRuleContext())
for _alt != 2 && _alt != antlr.ATNInvalidAltNumber {
if _alt == 1 {
{
p.SetState(161)
p.Field()
}
}
p.SetState(166)
p.GetErrorHandler().Sync(p)
_alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 10, p.GetParserRuleContext())
}
{
p.SetState(167)
var _m = p.Match(ApiParserParserT__4)
localctx.(*TypeStructContext).rbrace = _m
}
return localctx
}
// ITypeAliasContext is an interface to support dynamic dispatch.
type ITypeAliasContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetAlias returns the alias token.
GetAlias() antlr.Token
// GetAssign returns the assign token.
GetAssign() antlr.Token
// SetAlias sets the alias token.
SetAlias(antlr.Token)
// SetAssign sets the assign token.
SetAssign(antlr.Token)
// IsTypeAliasContext differentiates from other interfaces.
IsTypeAliasContext()
}
type TypeAliasContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
alias antlr.Token
assign antlr.Token
}
func NewEmptyTypeAliasContext() *TypeAliasContext {
var p = new(TypeAliasContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeAlias
return p
}
func (*TypeAliasContext) IsTypeAliasContext() {}
func NewTypeAliasContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeAliasContext {
var p = new(TypeAliasContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeAlias
return p
}
func (s *TypeAliasContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeAliasContext) GetAlias() antlr.Token { return s.alias }
func (s *TypeAliasContext) GetAssign() antlr.Token { return s.assign }
func (s *TypeAliasContext) SetAlias(v antlr.Token) { s.alias = v }
func (s *TypeAliasContext) SetAssign(v antlr.Token) { s.assign = v }
func (s *TypeAliasContext) DataType() IDataTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDataTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDataTypeContext)
}
func (s *TypeAliasContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *TypeAliasContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeAliasContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeAliasContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeAlias(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeAlias() (localctx ITypeAliasContext) {
localctx = NewTypeAliasContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 30, ApiParserParserRULE_typeAlias)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
checkKeyword(p)
{
p.SetState(170)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeAliasContext).alias = _m
}
p.SetState(172)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__0 {
{
p.SetState(171)
var _m = p.Match(ApiParserParserT__0)
localctx.(*TypeAliasContext).assign = _m
}
}
{
p.SetState(174)
p.DataType()
}
return localctx
}
// ITypeBlockStructContext is an interface to support dynamic dispatch.
type ITypeBlockStructContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetStructName returns the structName token.
GetStructName() antlr.Token
// GetStructToken returns the structToken token.
GetStructToken() antlr.Token
// GetLbrace returns the lbrace token.
GetLbrace() antlr.Token
// GetRbrace returns the rbrace token.
GetRbrace() antlr.Token
// SetStructName sets the structName token.
SetStructName(antlr.Token)
// SetStructToken sets the structToken token.
SetStructToken(antlr.Token)
// SetLbrace sets the lbrace token.
SetLbrace(antlr.Token)
// SetRbrace sets the rbrace token.
SetRbrace(antlr.Token)
// IsTypeBlockStructContext differentiates from other interfaces.
IsTypeBlockStructContext()
}
type TypeBlockStructContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
structName antlr.Token
structToken antlr.Token
lbrace antlr.Token
rbrace antlr.Token
}
func NewEmptyTypeBlockStructContext() *TypeBlockStructContext {
var p = new(TypeBlockStructContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeBlockStruct
return p
}
func (*TypeBlockStructContext) IsTypeBlockStructContext() {}
func NewTypeBlockStructContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeBlockStructContext {
var p = new(TypeBlockStructContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeBlockStruct
return p
}
func (s *TypeBlockStructContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeBlockStructContext) GetStructName() antlr.Token { return s.structName }
func (s *TypeBlockStructContext) GetStructToken() antlr.Token { return s.structToken }
func (s *TypeBlockStructContext) GetLbrace() antlr.Token { return s.lbrace }
func (s *TypeBlockStructContext) GetRbrace() antlr.Token { return s.rbrace }
func (s *TypeBlockStructContext) SetStructName(v antlr.Token) { s.structName = v }
func (s *TypeBlockStructContext) SetStructToken(v antlr.Token) { s.structToken = v }
func (s *TypeBlockStructContext) SetLbrace(v antlr.Token) { s.lbrace = v }
func (s *TypeBlockStructContext) SetRbrace(v antlr.Token) { s.rbrace = v }
func (s *TypeBlockStructContext) AllID() []antlr.TerminalNode {
return s.GetTokens(ApiParserParserID)
}
func (s *TypeBlockStructContext) ID(i int) antlr.TerminalNode {
return s.GetToken(ApiParserParserID, i)
}
func (s *TypeBlockStructContext) AllField() []IFieldContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IFieldContext)(nil)).Elem())
var tst = make([]IFieldContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IFieldContext)
}
}
return tst
}
func (s *TypeBlockStructContext) Field(i int) IFieldContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFieldContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IFieldContext)
}
func (s *TypeBlockStructContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeBlockStructContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeBlockStructContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeBlockStruct(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeBlockStruct() (localctx ITypeBlockStructContext) {
localctx = NewTypeBlockStructContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 32, ApiParserParserRULE_typeBlockStruct)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
var _alt int
p.EnterOuterAlt(localctx, 1)
checkKeyword(p)
{
p.SetState(177)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeBlockStructContext).structName = _m
}
p.SetState(179)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserID {
{
p.SetState(178)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeBlockStructContext).structToken = _m
}
}
{
p.SetState(181)
var _m = p.Match(ApiParserParserT__3)
localctx.(*TypeBlockStructContext).lbrace = _m
}
p.SetState(185)
p.GetErrorHandler().Sync(p)
_alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 13, p.GetParserRuleContext())
for _alt != 2 && _alt != antlr.ATNInvalidAltNumber {
if _alt == 1 {
{
p.SetState(182)
p.Field()
}
}
p.SetState(187)
p.GetErrorHandler().Sync(p)
_alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 13, p.GetParserRuleContext())
}
{
p.SetState(188)
var _m = p.Match(ApiParserParserT__4)
localctx.(*TypeBlockStructContext).rbrace = _m
}
return localctx
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser7.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser7.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 7
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
// IAtHandlerContext is an interface to support dynamic dispatch.
type IAtHandlerContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsAtHandlerContext differentiates from other interfaces.
IsAtHandlerContext()
}
type AtHandlerContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyAtHandlerContext() *AtHandlerContext {
var p = new(AtHandlerContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_atHandler
return p
}
func (*AtHandlerContext) IsAtHandlerContext() {}
func NewAtHandlerContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *AtHandlerContext {
var p = new(AtHandlerContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_atHandler
return p
}
func (s *AtHandlerContext) GetParser() antlr.Parser { return s.parser }
func (s *AtHandlerContext) ATHANDLER() antlr.TerminalNode {
return s.GetToken(ApiParserParserATHANDLER, 0)
}
func (s *AtHandlerContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *AtHandlerContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *AtHandlerContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *AtHandlerContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitAtHandler(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) AtHandler() (localctx IAtHandlerContext) {
localctx = NewAtHandlerContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 60, ApiParserParserRULE_atHandler)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(289)
p.Match(ApiParserParserATHANDLER)
}
{
p.SetState(290)
p.Match(ApiParserParserID)
}
return localctx
}
// IRouteContext is an interface to support dynamic dispatch.
type IRouteContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetHttpMethod returns the httpMethod token.
GetHttpMethod() antlr.Token
// SetHttpMethod sets the httpMethod token.
SetHttpMethod(antlr.Token)
// GetRequest returns the request rule contexts.
GetRequest() IBodyContext
// GetResponse returns the response rule contexts.
GetResponse() IReplybodyContext
// SetRequest sets the request rule contexts.
SetRequest(IBodyContext)
// SetResponse sets the response rule contexts.
SetResponse(IReplybodyContext)
// IsRouteContext differentiates from other interfaces.
IsRouteContext()
}
type RouteContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
httpMethod antlr.Token
request IBodyContext
response IReplybodyContext
}
func NewEmptyRouteContext() *RouteContext {
var p = new(RouteContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_route
return p
}
func (*RouteContext) IsRouteContext() {}
func NewRouteContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *RouteContext {
var p = new(RouteContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_route
return p
}
func (s *RouteContext) GetParser() antlr.Parser { return s.parser }
func (s *RouteContext) GetHttpMethod() antlr.Token { return s.httpMethod }
func (s *RouteContext) SetHttpMethod(v antlr.Token) { s.httpMethod = v }
func (s *RouteContext) GetRequest() IBodyContext { return s.request }
func (s *RouteContext) GetResponse() IReplybodyContext { return s.response }
func (s *RouteContext) SetRequest(v IBodyContext) { s.request = v }
func (s *RouteContext) SetResponse(v IReplybodyContext) { s.response = v }
func (s *RouteContext) Path() IPathContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IPathContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IPathContext)
}
func (s *RouteContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *RouteContext) Body() IBodyContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IBodyContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IBodyContext)
}
func (s *RouteContext) Replybody() IReplybodyContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IReplybodyContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IReplybodyContext)
}
func (s *RouteContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *RouteContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *RouteContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitRoute(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Route() (localctx IRouteContext) {
localctx = NewRouteContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 62, ApiParserParserRULE_route)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
checkHTTPMethod(p)
{
p.SetState(293)
var _m = p.Match(ApiParserParserID)
localctx.(*RouteContext).httpMethod = _m
}
{
p.SetState(294)
p.Path()
}
p.SetState(296)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__1 {
{
p.SetState(295)
var _x = p.Body()
localctx.(*RouteContext).request = _x
}
}
p.SetState(299)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__9 {
{
p.SetState(298)
var _x = p.Replybody()
localctx.(*RouteContext).response = _x
}
}
return localctx
}
// IBodyContext is an interface to support dynamic dispatch.
type IBodyContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetLp returns the lp token.
GetLp() antlr.Token
// GetRp returns the rp token.
GetRp() antlr.Token
// SetLp sets the lp token.
SetLp(antlr.Token)
// SetRp sets the rp token.
SetRp(antlr.Token)
// IsBodyContext differentiates from other interfaces.
IsBodyContext()
}
type BodyContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
lp antlr.Token
rp antlr.Token
}
func NewEmptyBodyContext() *BodyContext {
var p = new(BodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_body
return p
}
func (*BodyContext) IsBodyContext() {}
func NewBodyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *BodyContext {
var p = new(BodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_body
return p
}
func (s *BodyContext) GetParser() antlr.Parser { return s.parser }
func (s *BodyContext) GetLp() antlr.Token { return s.lp }
func (s *BodyContext) GetRp() antlr.Token { return s.rp }
func (s *BodyContext) SetLp(v antlr.Token) { s.lp = v }
func (s *BodyContext) SetRp(v antlr.Token) { s.rp = v }
func (s *BodyContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *BodyContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *BodyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *BodyContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitBody(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Body() (localctx IBodyContext) {
localctx = NewBodyContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 64, ApiParserParserRULE_body)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(301)
var _m = p.Match(ApiParserParserT__1)
localctx.(*BodyContext).lp = _m
}
p.SetState(303)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserID {
{
p.SetState(302)
p.Match(ApiParserParserID)
}
}
{
p.SetState(305)
var _m = p.Match(ApiParserParserT__2)
localctx.(*BodyContext).rp = _m
}
return localctx
}
// IReplybodyContext is an interface to support dynamic dispatch.
type IReplybodyContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetReturnToken returns the returnToken token.
GetReturnToken() antlr.Token
// GetLp returns the lp token.
GetLp() antlr.Token
// GetRp returns the rp token.
GetRp() antlr.Token
// SetReturnToken sets the returnToken token.
SetReturnToken(antlr.Token)
// SetLp sets the lp token.
SetLp(antlr.Token)
// SetRp sets the rp token.
SetRp(antlr.Token)
// IsReplybodyContext differentiates from other interfaces.
IsReplybodyContext()
}
type ReplybodyContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
returnToken antlr.Token
lp antlr.Token
rp antlr.Token
}
func NewEmptyReplybodyContext() *ReplybodyContext {
var p = new(ReplybodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_replybody
return p
}
func (*ReplybodyContext) IsReplybodyContext() {}
func NewReplybodyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ReplybodyContext {
var p = new(ReplybodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_replybody
return p
}
func (s *ReplybodyContext) GetParser() antlr.Parser { return s.parser }
func (s *ReplybodyContext) GetReturnToken() antlr.Token { return s.returnToken }
func (s *ReplybodyContext) GetLp() antlr.Token { return s.lp }
func (s *ReplybodyContext) GetRp() antlr.Token { return s.rp }
func (s *ReplybodyContext) SetReturnToken(v antlr.Token) { s.returnToken = v }
func (s *ReplybodyContext) SetLp(v antlr.Token) { s.lp = v }
func (s *ReplybodyContext) SetRp(v antlr.Token) { s.rp = v }
func (s *ReplybodyContext) DataType() IDataTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDataTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDataTypeContext)
}
func (s *ReplybodyContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ReplybodyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ReplybodyContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitReplybody(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Replybody() (localctx IReplybodyContext) {
localctx = NewReplybodyContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 66, ApiParserParserRULE_replybody)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(307)
var _m = p.Match(ApiParserParserT__9)
localctx.(*ReplybodyContext).returnToken = _m
}
{
p.SetState(308)
var _m = p.Match(ApiParserParserT__1)
localctx.(*ReplybodyContext).lp = _m
}
p.SetState(310)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if ((_la)&-(0x1f+1)) == 0 && ((1<<uint(_la))&((1<<ApiParserParserT__5)|(1<<ApiParserParserT__6)|(1<<ApiParserParserT__7)|(1<<ApiParserParserINTERFACE)|(1<<ApiParserParserID))) != 0 {
{
p.SetState(309)
p.DataType()
}
}
{
p.SetState(312)
var _m = p.Match(ApiParserParserT__2)
localctx.(*ReplybodyContext).rp = _m
}
return localctx
}
// IKvLitContext is an interface to support dynamic dispatch.
type IKvLitContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetKey returns the key token.
GetKey() antlr.Token
// GetValue returns the value token.
GetValue() antlr.Token
// SetKey sets the key token.
SetKey(antlr.Token)
// SetValue sets the value token.
SetValue(antlr.Token)
// IsKvLitContext differentiates from other interfaces.
IsKvLitContext()
}
type KvLitContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
key antlr.Token
value antlr.Token
}
func NewEmptyKvLitContext() *KvLitContext {
var p = new(KvLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_kvLit
return p
}
func (*KvLitContext) IsKvLitContext() {}
func NewKvLitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *KvLitContext {
var p = new(KvLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_kvLit
return p
}
func (s *KvLitContext) GetParser() antlr.Parser { return s.parser }
func (s *KvLitContext) GetKey() antlr.Token { return s.key }
func (s *KvLitContext) GetValue() antlr.Token { return s.value }
func (s *KvLitContext) SetKey(v antlr.Token) { s.key = v }
func (s *KvLitContext) SetValue(v antlr.Token) { s.value = v }
func (s *KvLitContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *KvLitContext) LINE_VALUE() antlr.TerminalNode {
return s.GetToken(ApiParserParserLINE_VALUE, 0)
}
func (s *KvLitContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *KvLitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_lexer.go | tools/goctl/api/parser/g4/gen/api/apiparser_lexer.go | package api
import (
"fmt"
"unicode"
"github.com/zeromicro/antlr"
)
// Suppress unused import error
var _ = fmt.Printf
var _ = unicode.IsLetter
var serializedLexerAtn = []uint16{
3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 2, 27, 276,
8, 1, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7,
9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12,
4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4,
18, 9, 18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 4, 23,
9, 23, 4, 24, 9, 24, 4, 25, 9, 25, 4, 26, 9, 26, 4, 27, 9, 27, 4, 28, 9,
28, 4, 29, 9, 29, 4, 30, 9, 30, 4, 31, 9, 31, 4, 32, 9, 32, 3, 2, 3, 2,
3, 3, 3, 3, 3, 4, 3, 4, 3, 5, 3, 5, 3, 6, 3, 6, 3, 7, 3, 7, 3, 8, 3, 8,
3, 8, 3, 8, 3, 8, 3, 8, 3, 8, 3, 8, 3, 8, 3, 8, 3, 9, 3, 9, 3, 10, 3, 10,
3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 12, 3, 12, 3,
13, 3, 13, 3, 14, 3, 14, 3, 14, 3, 15, 3, 15, 3, 15, 3, 15, 3, 15, 3, 16,
3, 16, 3, 16, 3, 16, 3, 16, 3, 16, 3, 16, 3, 16, 3, 16, 3, 17, 3, 17, 3,
17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 18,
3, 18, 3, 18, 3, 18, 3, 18, 3, 18, 3, 18, 3, 18, 3, 19, 6, 19, 142, 10,
19, 13, 19, 14, 19, 143, 3, 19, 3, 19, 3, 20, 3, 20, 3, 20, 3, 20, 7, 20,
152, 10, 20, 12, 20, 14, 20, 155, 11, 20, 3, 20, 3, 20, 3, 20, 3, 20, 3,
20, 3, 21, 3, 21, 3, 21, 3, 21, 7, 21, 166, 10, 21, 12, 21, 14, 21, 169,
11, 21, 3, 21, 3, 21, 3, 22, 3, 22, 3, 22, 7, 22, 176, 10, 22, 12, 22,
14, 22, 179, 11, 22, 3, 22, 3, 22, 3, 23, 3, 23, 3, 23, 6, 23, 186, 10,
23, 13, 23, 14, 23, 187, 3, 23, 3, 23, 3, 24, 3, 24, 7, 24, 194, 10, 24,
12, 24, 14, 24, 197, 11, 24, 3, 24, 3, 24, 7, 24, 201, 10, 24, 12, 24,
14, 24, 204, 11, 24, 5, 24, 206, 10, 24, 3, 25, 3, 25, 7, 25, 210, 10,
25, 12, 25, 14, 25, 213, 11, 25, 3, 26, 3, 26, 5, 26, 217, 10, 26, 3, 27,
3, 27, 5, 27, 221, 10, 27, 3, 27, 3, 27, 3, 28, 3, 28, 3, 28, 3, 28, 5,
28, 229, 10, 28, 3, 28, 5, 28, 232, 10, 28, 3, 28, 3, 28, 3, 28, 6, 28,
237, 10, 28, 13, 28, 14, 28, 238, 3, 28, 3, 28, 3, 28, 3, 28, 3, 28, 5,
28, 246, 10, 28, 3, 29, 3, 29, 3, 29, 7, 29, 251, 10, 29, 12, 29, 14, 29,
254, 11, 29, 3, 29, 5, 29, 257, 10, 29, 3, 30, 3, 30, 3, 31, 3, 31, 7,
31, 263, 10, 31, 12, 31, 14, 31, 266, 11, 31, 3, 31, 5, 31, 269, 10, 31,
3, 32, 3, 32, 3, 32, 3, 32, 5, 32, 275, 10, 32, 3, 153, 2, 33, 3, 3, 5,
4, 7, 5, 9, 6, 11, 7, 13, 8, 15, 9, 17, 10, 19, 11, 21, 12, 23, 13, 25,
14, 27, 15, 29, 16, 31, 17, 33, 18, 35, 19, 37, 20, 39, 21, 41, 22, 43,
23, 45, 24, 47, 25, 49, 26, 51, 27, 53, 2, 55, 2, 57, 2, 59, 2, 61, 2,
63, 2, 3, 2, 20, 5, 2, 11, 12, 14, 15, 34, 34, 4, 2, 12, 12, 15, 15, 4,
2, 36, 36, 94, 94, 6, 2, 12, 12, 15, 15, 94, 94, 98, 98, 4, 2, 11, 11,
34, 34, 6, 2, 12, 12, 15, 15, 36, 36, 98, 98, 3, 2, 50, 59, 4, 2, 71, 71,
103, 103, 4, 2, 45, 45, 47, 47, 10, 2, 36, 36, 41, 41, 94, 94, 100, 100,
104, 104, 112, 112, 116, 116, 118, 118, 3, 2, 50, 53, 3, 2, 50, 57, 5,
2, 50, 59, 67, 72, 99, 104, 4, 2, 50, 59, 97, 97, 6, 2, 38, 38, 67, 92,
97, 97, 99, 124, 4, 2, 2, 129, 55298, 56321, 3, 2, 55298, 56321, 3, 2,
56322, 57345, 2, 294, 2, 3, 3, 2, 2, 2, 2, 5, 3, 2, 2, 2, 2, 7, 3, 2, 2,
2, 2, 9, 3, 2, 2, 2, 2, 11, 3, 2, 2, 2, 2, 13, 3, 2, 2, 2, 2, 15, 3, 2,
2, 2, 2, 17, 3, 2, 2, 2, 2, 19, 3, 2, 2, 2, 2, 21, 3, 2, 2, 2, 2, 23, 3,
2, 2, 2, 2, 25, 3, 2, 2, 2, 2, 27, 3, 2, 2, 2, 2, 29, 3, 2, 2, 2, 2, 31,
3, 2, 2, 2, 2, 33, 3, 2, 2, 2, 2, 35, 3, 2, 2, 2, 2, 37, 3, 2, 2, 2, 2,
39, 3, 2, 2, 2, 2, 41, 3, 2, 2, 2, 2, 43, 3, 2, 2, 2, 2, 45, 3, 2, 2, 2,
2, 47, 3, 2, 2, 2, 2, 49, 3, 2, 2, 2, 2, 51, 3, 2, 2, 2, 3, 65, 3, 2, 2,
2, 5, 67, 3, 2, 2, 2, 7, 69, 3, 2, 2, 2, 9, 71, 3, 2, 2, 2, 11, 73, 3,
2, 2, 2, 13, 75, 3, 2, 2, 2, 15, 77, 3, 2, 2, 2, 17, 87, 3, 2, 2, 2, 19,
89, 3, 2, 2, 2, 21, 91, 3, 2, 2, 2, 23, 99, 3, 2, 2, 2, 25, 101, 3, 2,
2, 2, 27, 103, 3, 2, 2, 2, 29, 106, 3, 2, 2, 2, 31, 111, 3, 2, 2, 2, 33,
120, 3, 2, 2, 2, 35, 132, 3, 2, 2, 2, 37, 141, 3, 2, 2, 2, 39, 147, 3,
2, 2, 2, 41, 161, 3, 2, 2, 2, 43, 172, 3, 2, 2, 2, 45, 182, 3, 2, 2, 2,
47, 191, 3, 2, 2, 2, 49, 207, 3, 2, 2, 2, 51, 216, 3, 2, 2, 2, 53, 218,
3, 2, 2, 2, 55, 245, 3, 2, 2, 2, 57, 247, 3, 2, 2, 2, 59, 258, 3, 2, 2,
2, 61, 260, 3, 2, 2, 2, 63, 274, 3, 2, 2, 2, 65, 66, 7, 63, 2, 2, 66, 4,
3, 2, 2, 2, 67, 68, 7, 42, 2, 2, 68, 6, 3, 2, 2, 2, 69, 70, 7, 43, 2, 2,
70, 8, 3, 2, 2, 2, 71, 72, 7, 125, 2, 2, 72, 10, 3, 2, 2, 2, 73, 74, 7,
127, 2, 2, 74, 12, 3, 2, 2, 2, 75, 76, 7, 44, 2, 2, 76, 14, 3, 2, 2, 2,
77, 78, 7, 118, 2, 2, 78, 79, 7, 107, 2, 2, 79, 80, 7, 111, 2, 2, 80, 81,
7, 103, 2, 2, 81, 82, 7, 48, 2, 2, 82, 83, 7, 86, 2, 2, 83, 84, 7, 107,
2, 2, 84, 85, 7, 111, 2, 2, 85, 86, 7, 103, 2, 2, 86, 16, 3, 2, 2, 2, 87,
88, 7, 93, 2, 2, 88, 18, 3, 2, 2, 2, 89, 90, 7, 95, 2, 2, 90, 20, 3, 2,
2, 2, 91, 92, 7, 116, 2, 2, 92, 93, 7, 103, 2, 2, 93, 94, 7, 118, 2, 2,
94, 95, 7, 119, 2, 2, 95, 96, 7, 116, 2, 2, 96, 97, 7, 112, 2, 2, 97, 98,
7, 117, 2, 2, 98, 22, 3, 2, 2, 2, 99, 100, 7, 47, 2, 2, 100, 24, 3, 2,
2, 2, 101, 102, 7, 49, 2, 2, 102, 26, 3, 2, 2, 2, 103, 104, 7, 49, 2, 2,
104, 105, 7, 60, 2, 2, 105, 28, 3, 2, 2, 2, 106, 107, 7, 66, 2, 2, 107,
108, 7, 102, 2, 2, 108, 109, 7, 113, 2, 2, 109, 110, 7, 101, 2, 2, 110,
30, 3, 2, 2, 2, 111, 112, 7, 66, 2, 2, 112, 113, 7, 106, 2, 2, 113, 114,
7, 99, 2, 2, 114, 115, 7, 112, 2, 2, 115, 116, 7, 102, 2, 2, 116, 117,
7, 110, 2, 2, 117, 118, 7, 103, 2, 2, 118, 119, 7, 116, 2, 2, 119, 32,
3, 2, 2, 2, 120, 121, 7, 107, 2, 2, 121, 122, 7, 112, 2, 2, 122, 123, 7,
118, 2, 2, 123, 124, 7, 103, 2, 2, 124, 125, 7, 116, 2, 2, 125, 126, 7,
104, 2, 2, 126, 127, 7, 99, 2, 2, 127, 128, 7, 101, 2, 2, 128, 129, 7,
103, 2, 2, 129, 130, 7, 125, 2, 2, 130, 131, 7, 127, 2, 2, 131, 34, 3,
2, 2, 2, 132, 133, 7, 66, 2, 2, 133, 134, 7, 117, 2, 2, 134, 135, 7, 103,
2, 2, 135, 136, 7, 116, 2, 2, 136, 137, 7, 120, 2, 2, 137, 138, 7, 103,
2, 2, 138, 139, 7, 116, 2, 2, 139, 36, 3, 2, 2, 2, 140, 142, 9, 2, 2, 2,
141, 140, 3, 2, 2, 2, 142, 143, 3, 2, 2, 2, 143, 141, 3, 2, 2, 2, 143,
144, 3, 2, 2, 2, 144, 145, 3, 2, 2, 2, 145, 146, 8, 19, 2, 2, 146, 38,
3, 2, 2, 2, 147, 148, 7, 49, 2, 2, 148, 149, 7, 44, 2, 2, 149, 153, 3,
2, 2, 2, 150, 152, 11, 2, 2, 2, 151, 150, 3, 2, 2, 2, 152, 155, 3, 2, 2,
2, 153, 154, 3, 2, 2, 2, 153, 151, 3, 2, 2, 2, 154, 156, 3, 2, 2, 2, 155,
153, 3, 2, 2, 2, 156, 157, 7, 44, 2, 2, 157, 158, 7, 49, 2, 2, 158, 159,
3, 2, 2, 2, 159, 160, 8, 20, 3, 2, 160, 40, 3, 2, 2, 2, 161, 162, 7, 49,
2, 2, 162, 163, 7, 49, 2, 2, 163, 167, 3, 2, 2, 2, 164, 166, 10, 3, 2,
2, 165, 164, 3, 2, 2, 2, 166, 169, 3, 2, 2, 2, 167, 165, 3, 2, 2, 2, 167,
168, 3, 2, 2, 2, 168, 170, 3, 2, 2, 2, 169, 167, 3, 2, 2, 2, 170, 171,
8, 21, 3, 2, 171, 42, 3, 2, 2, 2, 172, 177, 7, 36, 2, 2, 173, 176, 10,
4, 2, 2, 174, 176, 5, 55, 28, 2, 175, 173, 3, 2, 2, 2, 175, 174, 3, 2,
2, 2, 176, 179, 3, 2, 2, 2, 177, 175, 3, 2, 2, 2, 177, 178, 3, 2, 2, 2,
178, 180, 3, 2, 2, 2, 179, 177, 3, 2, 2, 2, 180, 181, 7, 36, 2, 2, 181,
44, 3, 2, 2, 2, 182, 185, 7, 98, 2, 2, 183, 186, 10, 5, 2, 2, 184, 186,
5, 55, 28, 2, 185, 183, 3, 2, 2, 2, 185, 184, 3, 2, 2, 2, 186, 187, 3,
2, 2, 2, 187, 185, 3, 2, 2, 2, 187, 188, 3, 2, 2, 2, 188, 189, 3, 2, 2,
2, 189, 190, 7, 98, 2, 2, 190, 46, 3, 2, 2, 2, 191, 195, 7, 60, 2, 2, 192,
194, 9, 6, 2, 2, 193, 192, 3, 2, 2, 2, 194, 197, 3, 2, 2, 2, 195, 193,
3, 2, 2, 2, 195, 196, 3, 2, 2, 2, 196, 205, 3, 2, 2, 2, 197, 195, 3, 2,
2, 2, 198, 206, 5, 43, 22, 2, 199, 201, 10, 7, 2, 2, 200, 199, 3, 2, 2,
2, 201, 204, 3, 2, 2, 2, 202, 200, 3, 2, 2, 2, 202, 203, 3, 2, 2, 2, 203,
206, 3, 2, 2, 2, 204, 202, 3, 2, 2, 2, 205, 198, 3, 2, 2, 2, 205, 202,
3, 2, 2, 2, 206, 48, 3, 2, 2, 2, 207, 211, 5, 63, 32, 2, 208, 210, 5, 51,
26, 2, 209, 208, 3, 2, 2, 2, 210, 213, 3, 2, 2, 2, 211, 209, 3, 2, 2, 2,
211, 212, 3, 2, 2, 2, 212, 50, 3, 2, 2, 2, 213, 211, 3, 2, 2, 2, 214, 217,
5, 63, 32, 2, 215, 217, 9, 8, 2, 2, 216, 214, 3, 2, 2, 2, 216, 215, 3,
2, 2, 2, 217, 52, 3, 2, 2, 2, 218, 220, 9, 9, 2, 2, 219, 221, 9, 10, 2,
2, 220, 219, 3, 2, 2, 2, 220, 221, 3, 2, 2, 2, 221, 222, 3, 2, 2, 2, 222,
223, 5, 61, 31, 2, 223, 54, 3, 2, 2, 2, 224, 225, 7, 94, 2, 2, 225, 246,
9, 11, 2, 2, 226, 231, 7, 94, 2, 2, 227, 229, 9, 12, 2, 2, 228, 227, 3,
2, 2, 2, 228, 229, 3, 2, 2, 2, 229, 230, 3, 2, 2, 2, 230, 232, 9, 13, 2,
2, 231, 228, 3, 2, 2, 2, 231, 232, 3, 2, 2, 2, 232, 233, 3, 2, 2, 2, 233,
246, 9, 13, 2, 2, 234, 236, 7, 94, 2, 2, 235, 237, 7, 119, 2, 2, 236, 235,
3, 2, 2, 2, 237, 238, 3, 2, 2, 2, 238, 236, 3, 2, 2, 2, 238, 239, 3, 2,
2, 2, 239, 240, 3, 2, 2, 2, 240, 241, 5, 59, 30, 2, 241, 242, 5, 59, 30,
2, 242, 243, 5, 59, 30, 2, 243, 244, 5, 59, 30, 2, 244, 246, 3, 2, 2, 2,
245, 224, 3, 2, 2, 2, 245, 226, 3, 2, 2, 2, 245, 234, 3, 2, 2, 2, 246,
56, 3, 2, 2, 2, 247, 256, 5, 59, 30, 2, 248, 251, 5, 59, 30, 2, 249, 251,
7, 97, 2, 2, 250, 248, 3, 2, 2, 2, 250, 249, 3, 2, 2, 2, 251, 254, 3, 2,
2, 2, 252, 250, 3, 2, 2, 2, 252, 253, 3, 2, 2, 2, 253, 255, 3, 2, 2, 2,
254, 252, 3, 2, 2, 2, 255, 257, 5, 59, 30, 2, 256, 252, 3, 2, 2, 2, 256,
257, 3, 2, 2, 2, 257, 58, 3, 2, 2, 2, 258, 259, 9, 14, 2, 2, 259, 60, 3,
2, 2, 2, 260, 268, 9, 8, 2, 2, 261, 263, 9, 15, 2, 2, 262, 261, 3, 2, 2,
2, 263, 266, 3, 2, 2, 2, 264, 262, 3, 2, 2, 2, 264, 265, 3, 2, 2, 2, 265,
267, 3, 2, 2, 2, 266, 264, 3, 2, 2, 2, 267, 269, 9, 8, 2, 2, 268, 264,
3, 2, 2, 2, 268, 269, 3, 2, 2, 2, 269, 62, 3, 2, 2, 2, 270, 275, 9, 16,
2, 2, 271, 275, 10, 17, 2, 2, 272, 273, 9, 18, 2, 2, 273, 275, 9, 19, 2,
2, 274, 270, 3, 2, 2, 2, 274, 271, 3, 2, 2, 2, 274, 272, 3, 2, 2, 2, 275,
64, 3, 2, 2, 2, 26, 2, 143, 153, 167, 175, 177, 185, 187, 195, 202, 205,
211, 216, 220, 228, 231, 238, 245, 250, 252, 256, 264, 268, 274, 4, 2,
3, 2, 2, 90, 2,
}
var lexerChannelNames = []string{
"DEFAULT_TOKEN_CHANNEL", "HIDDEN",
}
var lexerModeNames = []string{
"DEFAULT_MODE",
}
var lexerLiteralNames = []string{
"", "'='", "'('", "')'", "'{'", "'}'", "'*'", "'time.Time'", "'['", "']'",
"'returns'", "'-'", "'/'", "'/:'", "'@doc'", "'@handler'", "'interface{}'",
"'@server'",
}
var lexerSymbolicNames = []string{
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "ATDOC", "ATHANDLER",
"INTERFACE", "ATSERVER", "WS", "COMMENT", "LINE_COMMENT", "STRING", "RAW_STRING",
"LINE_VALUE", "ID", "LetterOrDigit",
}
var lexerRuleNames = []string{
"T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8",
"T__9", "T__10", "T__11", "T__12", "ATDOC", "ATHANDLER", "INTERFACE", "ATSERVER",
"WS", "COMMENT", "LINE_COMMENT", "STRING", "RAW_STRING", "LINE_VALUE",
"ID", "LetterOrDigit", "ExponentPart", "EscapeSequence", "HexDigits", "HexDigit",
"Digits", "Letter",
}
type ApiParserLexer struct {
*antlr.BaseLexer
channelNames []string
modeNames []string
// TODO: EOF string
}
// NewApiParserLexer produces a new lexer instance for the optional input antlr.CharStream.
//
// The *ApiParserLexer instance produced may be reused by calling the SetInputStream method.
// The initial lexer configuration is expensive to construct, and the object is not thread-safe;
// however, if used within a Golang sync.Pool, the construction cost amortizes well and the
// objects can be used in a thread-safe manner.
func NewApiParserLexer(input antlr.CharStream) *ApiParserLexer {
l := new(ApiParserLexer)
lexerDeserializer := antlr.NewATNDeserializer(nil)
lexerAtn := lexerDeserializer.DeserializeFromUInt16(serializedLexerAtn)
lexerDecisionToDFA := make([]*antlr.DFA, len(lexerAtn.DecisionToState))
for index, ds := range lexerAtn.DecisionToState {
lexerDecisionToDFA[index] = antlr.NewDFA(ds, index)
}
l.BaseLexer = antlr.NewBaseLexer(input)
l.Interpreter = antlr.NewLexerATNSimulator(l, lexerAtn, lexerDecisionToDFA, antlr.NewPredictionContextCache())
l.channelNames = lexerChannelNames
l.modeNames = lexerModeNames
l.RuleNames = lexerRuleNames
l.LiteralNames = lexerLiteralNames
l.SymbolicNames = lexerSymbolicNames
l.GrammarFileName = "ApiParser.g4"
// TODO: l.EOF = antlr.TokenEOF
return l
}
// ApiParserLexer tokens.
const (
ApiParserLexerT__0 = 1
ApiParserLexerT__1 = 2
ApiParserLexerT__2 = 3
ApiParserLexerT__3 = 4
ApiParserLexerT__4 = 5
ApiParserLexerT__5 = 6
ApiParserLexerT__6 = 7
ApiParserLexerT__7 = 8
ApiParserLexerT__8 = 9
ApiParserLexerT__9 = 10
ApiParserLexerT__10 = 11
ApiParserLexerT__11 = 12
ApiParserLexerT__12 = 13
ApiParserLexerATDOC = 14
ApiParserLexerATHANDLER = 15
ApiParserLexerINTERFACE = 16
ApiParserLexerATSERVER = 17
ApiParserLexerWS = 18
ApiParserLexerCOMMENT = 19
ApiParserLexerLINE_COMMENT = 20
ApiParserLexerSTRING = 21
ApiParserLexerRAW_STRING = 22
ApiParserLexerLINE_VALUE = 23
ApiParserLexerID = 24
ApiParserLexerLetterOrDigit = 25
)
const COMMENTS = 88
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser5.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser5.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 5
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
func (p *ApiParserParser) DataType() (localctx IDataTypeContext) {
localctx = NewDataTypeContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 42, ApiParserParserRULE_dataType)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(221)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 18, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
isInterface(p)
{
p.SetState(214)
p.Match(ApiParserParserID)
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(215)
p.MapType()
}
case 3:
p.EnterOuterAlt(localctx, 3)
{
p.SetState(216)
p.ArrayType()
}
case 4:
p.EnterOuterAlt(localctx, 4)
{
p.SetState(217)
var _m = p.Match(ApiParserParserINTERFACE)
localctx.(*DataTypeContext).inter = _m
}
case 5:
p.EnterOuterAlt(localctx, 5)
{
p.SetState(218)
var _m = p.Match(ApiParserParserT__6)
localctx.(*DataTypeContext).time = _m
}
case 6:
p.EnterOuterAlt(localctx, 6)
{
p.SetState(219)
p.PointerType()
}
case 7:
p.EnterOuterAlt(localctx, 7)
{
p.SetState(220)
p.TypeStruct()
}
}
return localctx
}
// IPointerTypeContext is an interface to support dynamic dispatch.
type IPointerTypeContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetStar returns the star token.
GetStar() antlr.Token
// SetStar sets the star token.
SetStar(antlr.Token)
// IsPointerTypeContext differentiates from other interfaces.
IsPointerTypeContext()
}
type PointerTypeContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
star antlr.Token
}
func NewEmptyPointerTypeContext() *PointerTypeContext {
var p = new(PointerTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_pointerType
return p
}
func (*PointerTypeContext) IsPointerTypeContext() {}
func NewPointerTypeContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *PointerTypeContext {
var p = new(PointerTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_pointerType
return p
}
func (s *PointerTypeContext) GetParser() antlr.Parser { return s.parser }
func (s *PointerTypeContext) GetStar() antlr.Token { return s.star }
func (s *PointerTypeContext) SetStar(v antlr.Token) { s.star = v }
func (s *PointerTypeContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *PointerTypeContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *PointerTypeContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *PointerTypeContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitPointerType(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) PointerType() (localctx IPointerTypeContext) {
localctx = NewPointerTypeContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 44, ApiParserParserRULE_pointerType)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(223)
var _m = p.Match(ApiParserParserT__5)
localctx.(*PointerTypeContext).star = _m
}
checkKeyword(p)
{
p.SetState(225)
p.Match(ApiParserParserID)
}
return localctx
}
// IMapTypeContext is an interface to support dynamic dispatch.
type IMapTypeContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetMapToken returns the mapToken token.
GetMapToken() antlr.Token
// GetLbrack returns the lbrack token.
GetLbrack() antlr.Token
// GetKey returns the key token.
GetKey() antlr.Token
// GetRbrack returns the rbrack token.
GetRbrack() antlr.Token
// SetMapToken sets the mapToken token.
SetMapToken(antlr.Token)
// SetLbrack sets the lbrack token.
SetLbrack(antlr.Token)
// SetKey sets the key token.
SetKey(antlr.Token)
// SetRbrack sets the rbrack token.
SetRbrack(antlr.Token)
// GetValue returns the value rule contexts.
GetValue() IDataTypeContext
// SetValue sets the value rule contexts.
SetValue(IDataTypeContext)
// IsMapTypeContext differentiates from other interfaces.
IsMapTypeContext()
}
type MapTypeContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
mapToken antlr.Token
lbrack antlr.Token
key antlr.Token
rbrack antlr.Token
value IDataTypeContext
}
func NewEmptyMapTypeContext() *MapTypeContext {
var p = new(MapTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_mapType
return p
}
func (*MapTypeContext) IsMapTypeContext() {}
func NewMapTypeContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *MapTypeContext {
var p = new(MapTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_mapType
return p
}
func (s *MapTypeContext) GetParser() antlr.Parser { return s.parser }
func (s *MapTypeContext) GetMapToken() antlr.Token { return s.mapToken }
func (s *MapTypeContext) GetLbrack() antlr.Token { return s.lbrack }
func (s *MapTypeContext) GetKey() antlr.Token { return s.key }
func (s *MapTypeContext) GetRbrack() antlr.Token { return s.rbrack }
func (s *MapTypeContext) SetMapToken(v antlr.Token) { s.mapToken = v }
func (s *MapTypeContext) SetLbrack(v antlr.Token) { s.lbrack = v }
func (s *MapTypeContext) SetKey(v antlr.Token) { s.key = v }
func (s *MapTypeContext) SetRbrack(v antlr.Token) { s.rbrack = v }
func (s *MapTypeContext) GetValue() IDataTypeContext { return s.value }
func (s *MapTypeContext) SetValue(v IDataTypeContext) { s.value = v }
func (s *MapTypeContext) AllID() []antlr.TerminalNode {
return s.GetTokens(ApiParserParserID)
}
func (s *MapTypeContext) ID(i int) antlr.TerminalNode {
return s.GetToken(ApiParserParserID, i)
}
func (s *MapTypeContext) DataType() IDataTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDataTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDataTypeContext)
}
func (s *MapTypeContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *MapTypeContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *MapTypeContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitMapType(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) MapType() (localctx IMapTypeContext) {
localctx = NewMapTypeContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 46, ApiParserParserRULE_mapType)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "map")
{
p.SetState(228)
var _m = p.Match(ApiParserParserID)
localctx.(*MapTypeContext).mapToken = _m
}
{
p.SetState(229)
var _m = p.Match(ApiParserParserT__7)
localctx.(*MapTypeContext).lbrack = _m
}
checkKey(p)
{
p.SetState(231)
var _m = p.Match(ApiParserParserID)
localctx.(*MapTypeContext).key = _m
}
{
p.SetState(232)
var _m = p.Match(ApiParserParserT__8)
localctx.(*MapTypeContext).rbrack = _m
}
{
p.SetState(233)
var _x = p.DataType()
localctx.(*MapTypeContext).value = _x
}
return localctx
}
// IArrayTypeContext is an interface to support dynamic dispatch.
type IArrayTypeContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetLbrack returns the lbrack token.
GetLbrack() antlr.Token
// GetRbrack returns the rbrack token.
GetRbrack() antlr.Token
// SetLbrack sets the lbrack token.
SetLbrack(antlr.Token)
// SetRbrack sets the rbrack token.
SetRbrack(antlr.Token)
// IsArrayTypeContext differentiates from other interfaces.
IsArrayTypeContext()
}
type ArrayTypeContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
lbrack antlr.Token
rbrack antlr.Token
}
func NewEmptyArrayTypeContext() *ArrayTypeContext {
var p = new(ArrayTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_arrayType
return p
}
func (*ArrayTypeContext) IsArrayTypeContext() {}
func NewArrayTypeContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ArrayTypeContext {
var p = new(ArrayTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_arrayType
return p
}
func (s *ArrayTypeContext) GetParser() antlr.Parser { return s.parser }
func (s *ArrayTypeContext) GetLbrack() antlr.Token { return s.lbrack }
func (s *ArrayTypeContext) GetRbrack() antlr.Token { return s.rbrack }
func (s *ArrayTypeContext) SetLbrack(v antlr.Token) { s.lbrack = v }
func (s *ArrayTypeContext) SetRbrack(v antlr.Token) { s.rbrack = v }
func (s *ArrayTypeContext) DataType() IDataTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDataTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDataTypeContext)
}
func (s *ArrayTypeContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ArrayTypeContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ArrayTypeContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitArrayType(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ArrayType() (localctx IArrayTypeContext) {
localctx = NewArrayTypeContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 48, ApiParserParserRULE_arrayType)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(235)
var _m = p.Match(ApiParserParserT__7)
localctx.(*ArrayTypeContext).lbrack = _m
}
{
p.SetState(236)
var _m = p.Match(ApiParserParserT__8)
localctx.(*ArrayTypeContext).rbrack = _m
}
{
p.SetState(237)
p.DataType()
}
return localctx
}
// IServiceSpecContext is an interface to support dynamic dispatch.
type IServiceSpecContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsServiceSpecContext differentiates from other interfaces.
IsServiceSpecContext()
}
type ServiceSpecContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyServiceSpecContext() *ServiceSpecContext {
var p = new(ServiceSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_serviceSpec
return p
}
func (*ServiceSpecContext) IsServiceSpecContext() {}
func NewServiceSpecContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ServiceSpecContext {
var p = new(ServiceSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_serviceSpec
return p
}
func (s *ServiceSpecContext) GetParser() antlr.Parser { return s.parser }
func (s *ServiceSpecContext) ServiceApi() IServiceApiContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IServiceApiContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IServiceApiContext)
}
func (s *ServiceSpecContext) AtServer() IAtServerContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IAtServerContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IAtServerContext)
}
func (s *ServiceSpecContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ServiceSpecContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ServiceSpecContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitServiceSpec(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ServiceSpec() (localctx IServiceSpecContext) {
localctx = NewServiceSpecContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 50, ApiParserParserRULE_serviceSpec)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(240)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserATSERVER {
{
p.SetState(239)
p.AtServer()
}
}
{
p.SetState(242)
p.ServiceApi()
}
return localctx
}
// IAtServerContext is an interface to support dynamic dispatch.
type IAtServerContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetLp returns the lp token.
GetLp() antlr.Token
// GetRp returns the rp token.
GetRp() antlr.Token
// SetLp sets the lp token.
SetLp(antlr.Token)
// SetRp sets the rp token.
SetRp(antlr.Token)
// IsAtServerContext differentiates from other interfaces.
IsAtServerContext()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser2.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser2.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 2
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
type InfoSpecContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
infoToken antlr.Token
lp antlr.Token
rp antlr.Token
}
func NewEmptyInfoSpecContext() *InfoSpecContext {
var p = new(InfoSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_infoSpec
return p
}
func (*InfoSpecContext) IsInfoSpecContext() {}
func NewInfoSpecContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *InfoSpecContext {
var p = new(InfoSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_infoSpec
return p
}
func (s *InfoSpecContext) GetParser() antlr.Parser { return s.parser }
func (s *InfoSpecContext) GetInfoToken() antlr.Token { return s.infoToken }
func (s *InfoSpecContext) GetLp() antlr.Token { return s.lp }
func (s *InfoSpecContext) GetRp() antlr.Token { return s.rp }
func (s *InfoSpecContext) SetInfoToken(v antlr.Token) { s.infoToken = v }
func (s *InfoSpecContext) SetLp(v antlr.Token) { s.lp = v }
func (s *InfoSpecContext) SetRp(v antlr.Token) { s.rp = v }
func (s *InfoSpecContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *InfoSpecContext) AllKvLit() []IKvLitContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IKvLitContext)(nil)).Elem())
var tst = make([]IKvLitContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IKvLitContext)
}
}
return tst
}
func (s *InfoSpecContext) KvLit(i int) IKvLitContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IKvLitContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IKvLitContext)
}
func (s *InfoSpecContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *InfoSpecContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *InfoSpecContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitInfoSpec(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) InfoSpec() (localctx IInfoSpecContext) {
localctx = NewInfoSpecContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 16, ApiParserParserRULE_infoSpec)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "info")
{
p.SetState(119)
var _m = p.Match(ApiParserParserID)
localctx.(*InfoSpecContext).infoToken = _m
}
{
p.SetState(120)
var _m = p.Match(ApiParserParserT__1)
localctx.(*InfoSpecContext).lp = _m
}
p.SetState(122)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserID {
{
p.SetState(121)
p.KvLit()
}
p.SetState(124)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(126)
var _m = p.Match(ApiParserParserT__2)
localctx.(*InfoSpecContext).rp = _m
}
return localctx
}
// ITypeSpecContext is an interface to support dynamic dispatch.
type ITypeSpecContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsTypeSpecContext differentiates from other interfaces.
IsTypeSpecContext()
}
type TypeSpecContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyTypeSpecContext() *TypeSpecContext {
var p = new(TypeSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeSpec
return p
}
func (*TypeSpecContext) IsTypeSpecContext() {}
func NewTypeSpecContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeSpecContext {
var p = new(TypeSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeSpec
return p
}
func (s *TypeSpecContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeSpecContext) TypeLit() ITypeLitContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeLitContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeLitContext)
}
func (s *TypeSpecContext) TypeBlock() ITypeBlockContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeBlockContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeBlockContext)
}
func (s *TypeSpecContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeSpecContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeSpecContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeSpec(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeSpec() (localctx ITypeSpecContext) {
localctx = NewTypeSpecContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 18, ApiParserParserRULE_typeSpec)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(130)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 5, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
{
p.SetState(128)
p.TypeLit()
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(129)
p.TypeBlock()
}
}
return localctx
}
// ITypeLitContext is an interface to support dynamic dispatch.
type ITypeLitContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetTypeToken returns the typeToken token.
GetTypeToken() antlr.Token
// SetTypeToken sets the typeToken token.
SetTypeToken(antlr.Token)
// IsTypeLitContext differentiates from other interfaces.
IsTypeLitContext()
}
type TypeLitContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
typeToken antlr.Token
}
func NewEmptyTypeLitContext() *TypeLitContext {
var p = new(TypeLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeLit
return p
}
func (*TypeLitContext) IsTypeLitContext() {}
func NewTypeLitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeLitContext {
var p = new(TypeLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeLit
return p
}
func (s *TypeLitContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeLitContext) GetTypeToken() antlr.Token { return s.typeToken }
func (s *TypeLitContext) SetTypeToken(v antlr.Token) { s.typeToken = v }
func (s *TypeLitContext) TypeLitBody() ITypeLitBodyContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeLitBodyContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeLitBodyContext)
}
func (s *TypeLitContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *TypeLitContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeLitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeLitContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeLit(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeLit() (localctx ITypeLitContext) {
localctx = NewTypeLitContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 20, ApiParserParserRULE_typeLit)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "type")
{
p.SetState(133)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeLitContext).typeToken = _m
}
{
p.SetState(134)
p.TypeLitBody()
}
return localctx
}
// ITypeBlockContext is an interface to support dynamic dispatch.
type ITypeBlockContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetTypeToken returns the typeToken token.
GetTypeToken() antlr.Token
// GetLp returns the lp token.
GetLp() antlr.Token
// GetRp returns the rp token.
GetRp() antlr.Token
// SetTypeToken sets the typeToken token.
SetTypeToken(antlr.Token)
// SetLp sets the lp token.
SetLp(antlr.Token)
// SetRp sets the rp token.
SetRp(antlr.Token)
// IsTypeBlockContext differentiates from other interfaces.
IsTypeBlockContext()
}
type TypeBlockContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
typeToken antlr.Token
lp antlr.Token
rp antlr.Token
}
func NewEmptyTypeBlockContext() *TypeBlockContext {
var p = new(TypeBlockContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeBlock
return p
}
func (*TypeBlockContext) IsTypeBlockContext() {}
func NewTypeBlockContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeBlockContext {
var p = new(TypeBlockContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeBlock
return p
}
func (s *TypeBlockContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeBlockContext) GetTypeToken() antlr.Token { return s.typeToken }
func (s *TypeBlockContext) GetLp() antlr.Token { return s.lp }
func (s *TypeBlockContext) GetRp() antlr.Token { return s.rp }
func (s *TypeBlockContext) SetTypeToken(v antlr.Token) { s.typeToken = v }
func (s *TypeBlockContext) SetLp(v antlr.Token) { s.lp = v }
func (s *TypeBlockContext) SetRp(v antlr.Token) { s.rp = v }
func (s *TypeBlockContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *TypeBlockContext) AllTypeBlockBody() []ITypeBlockBodyContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*ITypeBlockBodyContext)(nil)).Elem())
var tst = make([]ITypeBlockBodyContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(ITypeBlockBodyContext)
}
}
return tst
}
func (s *TypeBlockContext) TypeBlockBody(i int) ITypeBlockBodyContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeBlockBodyContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(ITypeBlockBodyContext)
}
func (s *TypeBlockContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeBlockContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeBlockContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeBlock(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeBlock() (localctx ITypeBlockContext) {
localctx = NewTypeBlockContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 22, ApiParserParserRULE_typeBlock)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "type")
{
p.SetState(137)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeBlockContext).typeToken = _m
}
{
p.SetState(138)
var _m = p.Match(ApiParserParserT__1)
localctx.(*TypeBlockContext).lp = _m
}
p.SetState(142)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ApiParserParserID {
{
p.SetState(139)
p.TypeBlockBody()
}
p.SetState(144)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(145)
var _m = p.Match(ApiParserParserT__2)
localctx.(*TypeBlockContext).rp = _m
}
return localctx
}
// ITypeLitBodyContext is an interface to support dynamic dispatch.
type ITypeLitBodyContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsTypeLitBodyContext differentiates from other interfaces.
IsTypeLitBodyContext()
}
type TypeLitBodyContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyTypeLitBodyContext() *TypeLitBodyContext {
var p = new(TypeLitBodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeLitBody
return p
}
func (*TypeLitBodyContext) IsTypeLitBodyContext() {}
func NewTypeLitBodyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeLitBodyContext {
var p = new(TypeLitBodyContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeLitBody
return p
}
func (s *TypeLitBodyContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeLitBodyContext) TypeStruct() ITypeStructContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeStructContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeStructContext)
}
func (s *TypeLitBodyContext) TypeAlias() ITypeAliasContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeAliasContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeAliasContext)
}
func (s *TypeLitBodyContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeLitBodyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeLitBodyContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeLitBody(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeLitBody() (localctx ITypeLitBodyContext) {
localctx = NewTypeLitBodyContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 24, ApiParserParserRULE_typeLitBody)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(149)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 7, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
{
p.SetState(147)
p.TypeStruct()
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(148)
p.TypeAlias()
}
}
return localctx
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser4.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser4.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 4
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
// ITypeBlockAliasContext is an interface to support dynamic dispatch.
type ITypeBlockAliasContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetAlias returns the alias token.
GetAlias() antlr.Token
// GetAssign returns the assign token.
GetAssign() antlr.Token
// SetAlias sets the alias token.
SetAlias(antlr.Token)
// SetAssign sets the assign token.
SetAssign(antlr.Token)
// IsTypeBlockAliasContext differentiates from other interfaces.
IsTypeBlockAliasContext()
}
type TypeBlockAliasContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
alias antlr.Token
assign antlr.Token
}
func NewEmptyTypeBlockAliasContext() *TypeBlockAliasContext {
var p = new(TypeBlockAliasContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_typeBlockAlias
return p
}
func (*TypeBlockAliasContext) IsTypeBlockAliasContext() {}
func NewTypeBlockAliasContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TypeBlockAliasContext {
var p = new(TypeBlockAliasContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_typeBlockAlias
return p
}
func (s *TypeBlockAliasContext) GetParser() antlr.Parser { return s.parser }
func (s *TypeBlockAliasContext) GetAlias() antlr.Token { return s.alias }
func (s *TypeBlockAliasContext) GetAssign() antlr.Token { return s.assign }
func (s *TypeBlockAliasContext) SetAlias(v antlr.Token) { s.alias = v }
func (s *TypeBlockAliasContext) SetAssign(v antlr.Token) { s.assign = v }
func (s *TypeBlockAliasContext) DataType() IDataTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDataTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDataTypeContext)
}
func (s *TypeBlockAliasContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *TypeBlockAliasContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TypeBlockAliasContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TypeBlockAliasContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitTypeBlockAlias(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) TypeBlockAlias() (localctx ITypeBlockAliasContext) {
localctx = NewTypeBlockAliasContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 34, ApiParserParserRULE_typeBlockAlias)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
checkKeyword(p)
{
p.SetState(191)
var _m = p.Match(ApiParserParserID)
localctx.(*TypeBlockAliasContext).alias = _m
}
p.SetState(193)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__0 {
{
p.SetState(192)
var _m = p.Match(ApiParserParserT__0)
localctx.(*TypeBlockAliasContext).assign = _m
}
}
{
p.SetState(195)
p.DataType()
}
return localctx
}
// IFieldContext is an interface to support dynamic dispatch.
type IFieldContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsFieldContext differentiates from other interfaces.
IsFieldContext()
}
type FieldContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyFieldContext() *FieldContext {
var p = new(FieldContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_field
return p
}
func (*FieldContext) IsFieldContext() {}
func NewFieldContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *FieldContext {
var p = new(FieldContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_field
return p
}
func (s *FieldContext) GetParser() antlr.Parser { return s.parser }
func (s *FieldContext) NormalField() INormalFieldContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*INormalFieldContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(INormalFieldContext)
}
func (s *FieldContext) AnonymousFiled() IAnonymousFiledContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IAnonymousFiledContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IAnonymousFiledContext)
}
func (s *FieldContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FieldContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *FieldContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitField(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Field() (localctx IFieldContext) {
localctx = NewFieldContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 36, ApiParserParserRULE_field)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(200)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 15, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
p.SetState(197)
if !(isNormal(p)) {
panic(antlr.NewFailedPredicateException(p, "isNormal(p)", ""))
}
{
p.SetState(198)
p.NormalField()
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(199)
p.AnonymousFiled()
}
}
return localctx
}
// INormalFieldContext is an interface to support dynamic dispatch.
type INormalFieldContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetFieldName returns the fieldName token.
GetFieldName() antlr.Token
// GetTag returns the tag token.
GetTag() antlr.Token
// SetFieldName sets the fieldName token.
SetFieldName(antlr.Token)
// SetTag sets the tag token.
SetTag(antlr.Token)
// IsNormalFieldContext differentiates from other interfaces.
IsNormalFieldContext()
}
type NormalFieldContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
fieldName antlr.Token
tag antlr.Token
}
func NewEmptyNormalFieldContext() *NormalFieldContext {
var p = new(NormalFieldContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_normalField
return p
}
func (*NormalFieldContext) IsNormalFieldContext() {}
func NewNormalFieldContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *NormalFieldContext {
var p = new(NormalFieldContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_normalField
return p
}
func (s *NormalFieldContext) GetParser() antlr.Parser { return s.parser }
func (s *NormalFieldContext) GetFieldName() antlr.Token { return s.fieldName }
func (s *NormalFieldContext) GetTag() antlr.Token { return s.tag }
func (s *NormalFieldContext) SetFieldName(v antlr.Token) { s.fieldName = v }
func (s *NormalFieldContext) SetTag(v antlr.Token) { s.tag = v }
func (s *NormalFieldContext) DataType() IDataTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDataTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDataTypeContext)
}
func (s *NormalFieldContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *NormalFieldContext) RAW_STRING() antlr.TerminalNode {
return s.GetToken(ApiParserParserRAW_STRING, 0)
}
func (s *NormalFieldContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *NormalFieldContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *NormalFieldContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitNormalField(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) NormalField() (localctx INormalFieldContext) {
localctx = NewNormalFieldContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 38, ApiParserParserRULE_normalField)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
checkKeyword(p)
{
p.SetState(203)
var _m = p.Match(ApiParserParserID)
localctx.(*NormalFieldContext).fieldName = _m
}
{
p.SetState(204)
p.DataType()
}
p.SetState(206)
p.GetErrorHandler().Sync(p)
if p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 16, p.GetParserRuleContext()) == 1 {
{
p.SetState(205)
var _m = p.Match(ApiParserParserRAW_STRING)
localctx.(*NormalFieldContext).tag = _m
}
}
return localctx
}
// IAnonymousFiledContext is an interface to support dynamic dispatch.
type IAnonymousFiledContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetStar returns the star token.
GetStar() antlr.Token
// SetStar sets the star token.
SetStar(antlr.Token)
// IsAnonymousFiledContext differentiates from other interfaces.
IsAnonymousFiledContext()
}
type AnonymousFiledContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
star antlr.Token
}
func NewEmptyAnonymousFiledContext() *AnonymousFiledContext {
var p = new(AnonymousFiledContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_anonymousFiled
return p
}
func (*AnonymousFiledContext) IsAnonymousFiledContext() {}
func NewAnonymousFiledContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *AnonymousFiledContext {
var p = new(AnonymousFiledContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_anonymousFiled
return p
}
func (s *AnonymousFiledContext) GetParser() antlr.Parser { return s.parser }
func (s *AnonymousFiledContext) GetStar() antlr.Token { return s.star }
func (s *AnonymousFiledContext) SetStar(v antlr.Token) { s.star = v }
func (s *AnonymousFiledContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *AnonymousFiledContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *AnonymousFiledContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *AnonymousFiledContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitAnonymousFiled(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) AnonymousFiled() (localctx IAnonymousFiledContext) {
localctx = NewAnonymousFiledContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 40, ApiParserParserRULE_anonymousFiled)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(209)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__5 {
{
p.SetState(208)
var _m = p.Match(ApiParserParserT__5)
localctx.(*AnonymousFiledContext).star = _m
}
}
{
p.SetState(211)
p.Match(ApiParserParserID)
}
return localctx
}
// IDataTypeContext is an interface to support dynamic dispatch.
type IDataTypeContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetInter returns the inter token.
GetInter() antlr.Token
// GetTime returns the time token.
GetTime() antlr.Token
// SetInter sets the inter token.
SetInter(antlr.Token)
// SetTime sets the time token.
SetTime(antlr.Token)
// IsDataTypeContext differentiates from other interfaces.
IsDataTypeContext()
}
type DataTypeContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
inter antlr.Token
time antlr.Token
}
func NewEmptyDataTypeContext() *DataTypeContext {
var p = new(DataTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_dataType
return p
}
func (*DataTypeContext) IsDataTypeContext() {}
func NewDataTypeContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *DataTypeContext {
var p = new(DataTypeContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_dataType
return p
}
func (s *DataTypeContext) GetParser() antlr.Parser { return s.parser }
func (s *DataTypeContext) GetInter() antlr.Token { return s.inter }
func (s *DataTypeContext) GetTime() antlr.Token { return s.time }
func (s *DataTypeContext) SetInter(v antlr.Token) { s.inter = v }
func (s *DataTypeContext) SetTime(v antlr.Token) { s.time = v }
func (s *DataTypeContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *DataTypeContext) MapType() IMapTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IMapTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IMapTypeContext)
}
func (s *DataTypeContext) ArrayType() IArrayTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IArrayTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IArrayTypeContext)
}
func (s *DataTypeContext) INTERFACE() antlr.TerminalNode {
return s.GetToken(ApiParserParserINTERFACE, 0)
}
func (s *DataTypeContext) PointerType() IPointerTypeContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IPointerTypeContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IPointerTypeContext)
}
func (s *DataTypeContext) TypeStruct() ITypeStructContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeStructContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeStructContext)
}
func (s *DataTypeContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *DataTypeContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *DataTypeContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitDataType(s)
default:
return t.VisitChildren(s)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser8.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser8.go | package api
import (
"fmt"
"reflect"
"github.com/zeromicro/antlr"
)
// Part 8
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
func (s *KvLitContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitKvLit(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) KvLit() (localctx IKvLitContext) {
localctx = NewKvLitContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 68, ApiParserParserRULE_kvLit)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(314)
var _m = p.Match(ApiParserParserID)
localctx.(*KvLitContext).key = _m
}
checkKeyValue(p)
{
p.SetState(316)
var _m = p.Match(ApiParserParserLINE_VALUE)
localctx.(*KvLitContext).value = _m
}
return localctx
}
// IServiceNameContext is an interface to support dynamic dispatch.
type IServiceNameContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsServiceNameContext differentiates from other interfaces.
IsServiceNameContext()
}
type ServiceNameContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyServiceNameContext() *ServiceNameContext {
var p = new(ServiceNameContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_serviceName
return p
}
func (*ServiceNameContext) IsServiceNameContext() {}
func NewServiceNameContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ServiceNameContext {
var p = new(ServiceNameContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_serviceName
return p
}
func (s *ServiceNameContext) GetParser() antlr.Parser { return s.parser }
func (s *ServiceNameContext) AllID() []antlr.TerminalNode {
return s.GetTokens(ApiParserParserID)
}
func (s *ServiceNameContext) ID(i int) antlr.TerminalNode {
return s.GetToken(ApiParserParserID, i)
}
func (s *ServiceNameContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ServiceNameContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ServiceNameContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitServiceName(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ServiceName() (localctx IServiceNameContext) {
localctx = NewServiceNameContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 70, ApiParserParserRULE_serviceName)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(322)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserID {
{
p.SetState(318)
p.Match(ApiParserParserID)
}
p.SetState(320)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__10 {
{
p.SetState(319)
p.Match(ApiParserParserT__10)
}
}
p.SetState(324)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
return localctx
}
// IPathContext is an interface to support dynamic dispatch.
type IPathContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsPathContext differentiates from other interfaces.
IsPathContext()
}
type PathContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyPathContext() *PathContext {
var p = new(PathContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_path
return p
}
func (*PathContext) IsPathContext() {}
func NewPathContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *PathContext {
var p = new(PathContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_path
return p
}
func (s *PathContext) GetParser() antlr.Parser { return s.parser }
func (s *PathContext) AllPathItem() []IPathItemContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IPathItemContext)(nil)).Elem())
var tst = make([]IPathItemContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IPathItemContext)
}
}
return tst
}
func (s *PathContext) PathItem(i int) IPathItemContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IPathItemContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IPathItemContext)
}
func (s *PathContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *PathContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *PathContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitPath(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Path() (localctx IPathContext) {
localctx = NewPathContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 72, ApiParserParserRULE_path)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(346)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 38, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
p.SetState(341)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserT__11 || _la == ApiParserParserT__12 {
p.SetState(341)
p.GetErrorHandler().Sync(p)
switch p.GetTokenStream().LA(1) {
case ApiParserParserT__11:
{
p.SetState(326)
p.Match(ApiParserParserT__11)
}
{
p.SetState(327)
p.PathItem()
}
p.SetState(332)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ApiParserParserT__10 {
{
p.SetState(328)
p.Match(ApiParserParserT__10)
}
{
p.SetState(329)
p.PathItem()
}
p.SetState(334)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
case ApiParserParserT__12:
{
p.SetState(335)
p.Match(ApiParserParserT__12)
}
{
p.SetState(336)
p.PathItem()
}
p.SetState(339)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__10 {
{
p.SetState(337)
p.Match(ApiParserParserT__10)
}
{
p.SetState(338)
p.PathItem()
}
}
default:
panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
}
p.SetState(343)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(345)
p.Match(ApiParserParserT__11)
}
}
return localctx
}
// IPathItemContext is an interface to support dynamic dispatch.
type IPathItemContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsPathItemContext differentiates from other interfaces.
IsPathItemContext()
}
type PathItemContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyPathItemContext() *PathItemContext {
var p = new(PathItemContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_pathItem
return p
}
func (*PathItemContext) IsPathItemContext() {}
func NewPathItemContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *PathItemContext {
var p = new(PathItemContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_pathItem
return p
}
func (s *PathItemContext) GetParser() antlr.Parser { return s.parser }
func (s *PathItemContext) AllID() []antlr.TerminalNode {
return s.GetTokens(ApiParserParserID)
}
func (s *PathItemContext) ID(i int) antlr.TerminalNode {
return s.GetToken(ApiParserParserID, i)
}
func (s *PathItemContext) AllLetterOrDigit() []antlr.TerminalNode {
return s.GetTokens(ApiParserParserLetterOrDigit)
}
func (s *PathItemContext) LetterOrDigit(i int) antlr.TerminalNode {
return s.GetToken(ApiParserParserLetterOrDigit, i)
}
func (s *PathItemContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *PathItemContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *PathItemContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitPathItem(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) PathItem() (localctx IPathItemContext) {
localctx = NewPathItemContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 74, ApiParserParserRULE_pathItem)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(349)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserID || _la == ApiParserParserLetterOrDigit {
{
p.SetState(348)
_la = p.GetTokenStream().LA(1)
if !(_la == ApiParserParserID || _la == ApiParserParserLetterOrDigit) {
p.GetErrorHandler().RecoverInline(p)
} else {
p.GetErrorHandler().ReportMatch(p)
p.Consume()
}
}
p.SetState(351)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
return localctx
}
func (p *ApiParserParser) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int) bool {
switch ruleIndex {
case 18:
var t *FieldContext = nil
if localctx != nil {
t = localctx.(*FieldContext)
}
return p.Field_Sempred(t, predIndex)
default:
panic("No predicate with index: " + fmt.Sprint(ruleIndex))
}
}
func (p *ApiParserParser) Field_Sempred(localctx antlr.RuleContext, predIndex int) bool {
switch predIndex {
case 0:
return isNormal(p)
default:
panic("No predicate with index: " + fmt.Sprint(predIndex))
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser1.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser1.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 1
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
func (s *SyntaxLitContext) STRING() antlr.TerminalNode {
return s.GetToken(ApiParserParserSTRING, 0)
}
func (s *SyntaxLitContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *SyntaxLitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *SyntaxLitContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitSyntaxLit(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) SyntaxLit() (localctx ISyntaxLitContext) {
localctx = NewSyntaxLitContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 4, ApiParserParserRULE_syntaxLit)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "syntax")
{
p.SetState(90)
var _m = p.Match(ApiParserParserID)
localctx.(*SyntaxLitContext).syntaxToken = _m
}
{
p.SetState(91)
var _m = p.Match(ApiParserParserT__0)
localctx.(*SyntaxLitContext).assign = _m
}
checkVersion(p)
{
p.SetState(93)
var _m = p.Match(ApiParserParserSTRING)
localctx.(*SyntaxLitContext).version = _m
}
return localctx
}
// IImportSpecContext is an interface to support dynamic dispatch.
type IImportSpecContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsImportSpecContext differentiates from other interfaces.
IsImportSpecContext()
}
type ImportSpecContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyImportSpecContext() *ImportSpecContext {
var p = new(ImportSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_importSpec
return p
}
func (*ImportSpecContext) IsImportSpecContext() {}
func NewImportSpecContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ImportSpecContext {
var p = new(ImportSpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_importSpec
return p
}
func (s *ImportSpecContext) GetParser() antlr.Parser { return s.parser }
func (s *ImportSpecContext) ImportLit() IImportLitContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportLitContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IImportLitContext)
}
func (s *ImportSpecContext) ImportBlock() IImportBlockContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportBlockContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IImportBlockContext)
}
func (s *ImportSpecContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ImportSpecContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ImportSpecContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitImportSpec(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ImportSpec() (localctx IImportSpecContext) {
localctx = NewImportSpecContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 6, ApiParserParserRULE_importSpec)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(97)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 2, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
{
p.SetState(95)
p.ImportLit()
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(96)
p.ImportBlock()
}
}
return localctx
}
// IImportLitContext is an interface to support dynamic dispatch.
type IImportLitContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetImportToken returns the importToken token.
GetImportToken() antlr.Token
// SetImportToken sets the importToken token.
SetImportToken(antlr.Token)
// IsImportLitContext differentiates from other interfaces.
IsImportLitContext()
}
type ImportLitContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
importToken antlr.Token
}
func NewEmptyImportLitContext() *ImportLitContext {
var p = new(ImportLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_importLit
return p
}
func (*ImportLitContext) IsImportLitContext() {}
func NewImportLitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ImportLitContext {
var p = new(ImportLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_importLit
return p
}
func (s *ImportLitContext) GetParser() antlr.Parser { return s.parser }
func (s *ImportLitContext) GetImportToken() antlr.Token { return s.importToken }
func (s *ImportLitContext) SetImportToken(v antlr.Token) { s.importToken = v }
func (s *ImportLitContext) ImportValue() IImportValueContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportValueContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IImportValueContext)
}
func (s *ImportLitContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *ImportLitContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ImportLitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ImportLitContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitImportLit(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ImportLit() (localctx IImportLitContext) {
localctx = NewImportLitContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 8, ApiParserParserRULE_importLit)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "import")
{
p.SetState(100)
var _m = p.Match(ApiParserParserID)
localctx.(*ImportLitContext).importToken = _m
}
{
p.SetState(101)
p.ImportValue()
}
return localctx
}
// IImportBlockContext is an interface to support dynamic dispatch.
type IImportBlockContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetImportToken returns the importToken token.
GetImportToken() antlr.Token
// SetImportToken sets the importToken token.
SetImportToken(antlr.Token)
// IsImportBlockContext differentiates from other interfaces.
IsImportBlockContext()
}
type ImportBlockContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
importToken antlr.Token
}
func NewEmptyImportBlockContext() *ImportBlockContext {
var p = new(ImportBlockContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_importBlock
return p
}
func (*ImportBlockContext) IsImportBlockContext() {}
func NewImportBlockContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ImportBlockContext {
var p = new(ImportBlockContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_importBlock
return p
}
func (s *ImportBlockContext) GetParser() antlr.Parser { return s.parser }
func (s *ImportBlockContext) GetImportToken() antlr.Token { return s.importToken }
func (s *ImportBlockContext) SetImportToken(v antlr.Token) { s.importToken = v }
func (s *ImportBlockContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *ImportBlockContext) AllImportBlockValue() []IImportBlockValueContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IImportBlockValueContext)(nil)).Elem())
var tst = make([]IImportBlockValueContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IImportBlockValueContext)
}
}
return tst
}
func (s *ImportBlockContext) ImportBlockValue(i int) IImportBlockValueContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportBlockValueContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IImportBlockValueContext)
}
func (s *ImportBlockContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ImportBlockContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ImportBlockContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitImportBlock(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ImportBlock() (localctx IImportBlockContext) {
localctx = NewImportBlockContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 10, ApiParserParserRULE_importBlock)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "import")
{
p.SetState(104)
var _m = p.Match(ApiParserParserID)
localctx.(*ImportBlockContext).importToken = _m
}
{
p.SetState(105)
p.Match(ApiParserParserT__1)
}
p.SetState(107)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserSTRING {
{
p.SetState(106)
p.ImportBlockValue()
}
p.SetState(109)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(111)
p.Match(ApiParserParserT__2)
}
return localctx
}
// IImportBlockValueContext is an interface to support dynamic dispatch.
type IImportBlockValueContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsImportBlockValueContext differentiates from other interfaces.
IsImportBlockValueContext()
}
type ImportBlockValueContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyImportBlockValueContext() *ImportBlockValueContext {
var p = new(ImportBlockValueContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_importBlockValue
return p
}
func (*ImportBlockValueContext) IsImportBlockValueContext() {}
func NewImportBlockValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ImportBlockValueContext {
var p = new(ImportBlockValueContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_importBlockValue
return p
}
func (s *ImportBlockValueContext) GetParser() antlr.Parser { return s.parser }
func (s *ImportBlockValueContext) ImportValue() IImportValueContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportValueContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IImportValueContext)
}
func (s *ImportBlockValueContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ImportBlockValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ImportBlockValueContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitImportBlockValue(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ImportBlockValue() (localctx IImportBlockValueContext) {
localctx = NewImportBlockValueContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 12, ApiParserParserRULE_importBlockValue)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(113)
p.ImportValue()
}
return localctx
}
// IImportValueContext is an interface to support dynamic dispatch.
type IImportValueContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsImportValueContext differentiates from other interfaces.
IsImportValueContext()
}
type ImportValueContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyImportValueContext() *ImportValueContext {
var p = new(ImportValueContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_importValue
return p
}
func (*ImportValueContext) IsImportValueContext() {}
func NewImportValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ImportValueContext {
var p = new(ImportValueContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_importValue
return p
}
func (s *ImportValueContext) GetParser() antlr.Parser { return s.parser }
func (s *ImportValueContext) STRING() antlr.TerminalNode {
return s.GetToken(ApiParserParserSTRING, 0)
}
func (s *ImportValueContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ImportValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ImportValueContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitImportValue(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ImportValue() (localctx IImportValueContext) {
localctx = NewImportValueContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 14, ApiParserParserRULE_importValue)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
checkImportValue(p)
{
p.SetState(116)
p.Match(ApiParserParserSTRING)
}
return localctx
}
// IInfoSpecContext is an interface to support dynamic dispatch.
type IInfoSpecContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetInfoToken returns the infoToken token.
GetInfoToken() antlr.Token
// GetLp returns the lp token.
GetLp() antlr.Token
// GetRp returns the rp token.
GetRp() antlr.Token
// SetInfoToken sets the infoToken token.
SetInfoToken(antlr.Token)
// SetLp sets the lp token.
SetLp(antlr.Token)
// SetRp sets the rp token.
SetRp(antlr.Token)
// IsInfoSpecContext differentiates from other interfaces.
IsInfoSpecContext()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_base_visitor.go | tools/goctl/api/parser/g4/gen/api/apiparser_base_visitor.go | package api // ApiParser
import "github.com/zeromicro/antlr"
type BaseApiParserVisitor struct {
*antlr.BaseParseTreeVisitor
}
func (v *BaseApiParserVisitor) VisitApi(ctx *ApiContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitSpec(ctx *SpecContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitSyntaxLit(ctx *SyntaxLitContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitImportSpec(ctx *ImportSpecContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitImportLit(ctx *ImportLitContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitImportBlock(ctx *ImportBlockContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitImportBlockValue(ctx *ImportBlockValueContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitImportValue(ctx *ImportValueContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitInfoSpec(ctx *InfoSpecContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeSpec(ctx *TypeSpecContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeLit(ctx *TypeLitContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeBlock(ctx *TypeBlockContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeLitBody(ctx *TypeLitBodyContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeBlockBody(ctx *TypeBlockBodyContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeStruct(ctx *TypeStructContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeAlias(ctx *TypeAliasContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeBlockStruct(ctx *TypeBlockStructContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitTypeBlockAlias(ctx *TypeBlockAliasContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitField(ctx *FieldContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitNormalField(ctx *NormalFieldContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitAnonymousFiled(ctx *AnonymousFiledContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitDataType(ctx *DataTypeContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitPointerType(ctx *PointerTypeContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitMapType(ctx *MapTypeContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitArrayType(ctx *ArrayTypeContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitServiceSpec(ctx *ServiceSpecContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitAtServer(ctx *AtServerContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitServiceApi(ctx *ServiceApiContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitServiceRoute(ctx *ServiceRouteContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitAtDoc(ctx *AtDocContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitAtHandler(ctx *AtHandlerContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitRoute(ctx *RouteContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitBody(ctx *BodyContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitReplybody(ctx *ReplybodyContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitKvLit(ctx *KvLitContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitServiceName(ctx *ServiceNameContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitPath(ctx *PathContext) any {
return v.VisitChildren(ctx)
}
func (v *BaseApiParserVisitor) VisitPathItem(ctx *PathItemContext) any {
return v.VisitChildren(ctx)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser6.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser6.go | package api
import (
"reflect"
"github.com/zeromicro/antlr"
)
// Part 6
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
type AtServerContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
lp antlr.Token
rp antlr.Token
}
func NewEmptyAtServerContext() *AtServerContext {
var p = new(AtServerContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_atServer
return p
}
func (*AtServerContext) IsAtServerContext() {}
func NewAtServerContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *AtServerContext {
var p = new(AtServerContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_atServer
return p
}
func (s *AtServerContext) GetParser() antlr.Parser { return s.parser }
func (s *AtServerContext) GetLp() antlr.Token { return s.lp }
func (s *AtServerContext) GetRp() antlr.Token { return s.rp }
func (s *AtServerContext) SetLp(v antlr.Token) { s.lp = v }
func (s *AtServerContext) SetRp(v antlr.Token) { s.rp = v }
func (s *AtServerContext) ATSERVER() antlr.TerminalNode {
return s.GetToken(ApiParserParserATSERVER, 0)
}
func (s *AtServerContext) AllKvLit() []IKvLitContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IKvLitContext)(nil)).Elem())
var tst = make([]IKvLitContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IKvLitContext)
}
}
return tst
}
func (s *AtServerContext) KvLit(i int) IKvLitContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IKvLitContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IKvLitContext)
}
func (s *AtServerContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *AtServerContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *AtServerContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitAtServer(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) AtServer() (localctx IAtServerContext) {
localctx = NewAtServerContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 52, ApiParserParserRULE_atServer)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(244)
p.Match(ApiParserParserATSERVER)
}
{
p.SetState(245)
var _m = p.Match(ApiParserParserT__1)
localctx.(*AtServerContext).lp = _m
}
p.SetState(247)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserID {
{
p.SetState(246)
p.KvLit()
}
p.SetState(249)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(251)
var _m = p.Match(ApiParserParserT__2)
localctx.(*AtServerContext).rp = _m
}
return localctx
}
// IServiceApiContext is an interface to support dynamic dispatch.
type IServiceApiContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetServiceToken returns the serviceToken token.
GetServiceToken() antlr.Token
// GetLbrace returns the lbrace token.
GetLbrace() antlr.Token
// GetRbrace returns the rbrace token.
GetRbrace() antlr.Token
// SetServiceToken sets the serviceToken token.
SetServiceToken(antlr.Token)
// SetLbrace sets the lbrace token.
SetLbrace(antlr.Token)
// SetRbrace sets the rbrace token.
SetRbrace(antlr.Token)
// IsServiceApiContext differentiates from other interfaces.
IsServiceApiContext()
}
type ServiceApiContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
serviceToken antlr.Token
lbrace antlr.Token
rbrace antlr.Token
}
func NewEmptyServiceApiContext() *ServiceApiContext {
var p = new(ServiceApiContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_serviceApi
return p
}
func (*ServiceApiContext) IsServiceApiContext() {}
func NewServiceApiContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ServiceApiContext {
var p = new(ServiceApiContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_serviceApi
return p
}
func (s *ServiceApiContext) GetParser() antlr.Parser { return s.parser }
func (s *ServiceApiContext) GetServiceToken() antlr.Token { return s.serviceToken }
func (s *ServiceApiContext) GetLbrace() antlr.Token { return s.lbrace }
func (s *ServiceApiContext) GetRbrace() antlr.Token { return s.rbrace }
func (s *ServiceApiContext) SetServiceToken(v antlr.Token) { s.serviceToken = v }
func (s *ServiceApiContext) SetLbrace(v antlr.Token) { s.lbrace = v }
func (s *ServiceApiContext) SetRbrace(v antlr.Token) { s.rbrace = v }
func (s *ServiceApiContext) ServiceName() IServiceNameContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IServiceNameContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IServiceNameContext)
}
func (s *ServiceApiContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
func (s *ServiceApiContext) AllServiceRoute() []IServiceRouteContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IServiceRouteContext)(nil)).Elem())
var tst = make([]IServiceRouteContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IServiceRouteContext)
}
}
return tst
}
func (s *ServiceApiContext) ServiceRoute(i int) IServiceRouteContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IServiceRouteContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IServiceRouteContext)
}
func (s *ServiceApiContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ServiceApiContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ServiceApiContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitServiceApi(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ServiceApi() (localctx IServiceApiContext) {
localctx = NewServiceApiContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 54, ApiParserParserRULE_serviceApi)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
match(p, "service")
{
p.SetState(254)
var _m = p.Match(ApiParserParserID)
localctx.(*ServiceApiContext).serviceToken = _m
}
{
p.SetState(255)
p.ServiceName()
}
{
p.SetState(256)
var _m = p.Match(ApiParserParserT__3)
localctx.(*ServiceApiContext).lbrace = _m
}
p.SetState(260)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ((_la)&-(0x1f+1)) == 0 && ((1<<uint(_la))&((1<<ApiParserParserATDOC)|(1<<ApiParserParserATHANDLER)|(1<<ApiParserParserATSERVER))) != 0 {
{
p.SetState(257)
p.ServiceRoute()
}
p.SetState(262)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(263)
var _m = p.Match(ApiParserParserT__4)
localctx.(*ServiceApiContext).rbrace = _m
}
return localctx
}
// IServiceRouteContext is an interface to support dynamic dispatch.
type IServiceRouteContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsServiceRouteContext differentiates from other interfaces.
IsServiceRouteContext()
}
type ServiceRouteContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyServiceRouteContext() *ServiceRouteContext {
var p = new(ServiceRouteContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_serviceRoute
return p
}
func (*ServiceRouteContext) IsServiceRouteContext() {}
func NewServiceRouteContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ServiceRouteContext {
var p = new(ServiceRouteContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_serviceRoute
return p
}
func (s *ServiceRouteContext) GetParser() antlr.Parser { return s.parser }
func (s *ServiceRouteContext) Route() IRouteContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IRouteContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IRouteContext)
}
func (s *ServiceRouteContext) AtServer() IAtServerContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IAtServerContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IAtServerContext)
}
func (s *ServiceRouteContext) AtHandler() IAtHandlerContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IAtHandlerContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IAtHandlerContext)
}
func (s *ServiceRouteContext) AtDoc() IAtDocContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IAtDocContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IAtDocContext)
}
func (s *ServiceRouteContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ServiceRouteContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ServiceRouteContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitServiceRoute(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) ServiceRoute() (localctx IServiceRouteContext) {
localctx = NewServiceRouteContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 56, ApiParserParserRULE_serviceRoute)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(266)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserATDOC {
{
p.SetState(265)
p.AtDoc()
}
}
p.SetState(270)
p.GetErrorHandler().Sync(p)
switch p.GetTokenStream().LA(1) {
case ApiParserParserATSERVER:
{
p.SetState(268)
p.AtServer()
}
case ApiParserParserATHANDLER:
{
p.SetState(269)
p.AtHandler()
}
default:
panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
}
{
p.SetState(272)
p.Route()
}
return localctx
}
// IAtDocContext is an interface to support dynamic dispatch.
type IAtDocContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetLp returns the lp token.
GetLp() antlr.Token
// GetRp returns the rp token.
GetRp() antlr.Token
// SetLp sets the lp token.
SetLp(antlr.Token)
// SetRp sets the rp token.
SetRp(antlr.Token)
// IsAtDocContext differentiates from other interfaces.
IsAtDocContext()
}
type AtDocContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
lp antlr.Token
rp antlr.Token
}
func NewEmptyAtDocContext() *AtDocContext {
var p = new(AtDocContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_atDoc
return p
}
func (*AtDocContext) IsAtDocContext() {}
func NewAtDocContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *AtDocContext {
var p = new(AtDocContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_atDoc
return p
}
func (s *AtDocContext) GetParser() antlr.Parser { return s.parser }
func (s *AtDocContext) GetLp() antlr.Token { return s.lp }
func (s *AtDocContext) GetRp() antlr.Token { return s.rp }
func (s *AtDocContext) SetLp(v antlr.Token) { s.lp = v }
func (s *AtDocContext) SetRp(v antlr.Token) { s.rp = v }
func (s *AtDocContext) ATDOC() antlr.TerminalNode {
return s.GetToken(ApiParserParserATDOC, 0)
}
func (s *AtDocContext) STRING() antlr.TerminalNode {
return s.GetToken(ApiParserParserSTRING, 0)
}
func (s *AtDocContext) AllKvLit() []IKvLitContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IKvLitContext)(nil)).Elem())
var tst = make([]IKvLitContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IKvLitContext)
}
}
return tst
}
func (s *AtDocContext) KvLit(i int) IKvLitContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IKvLitContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IKvLitContext)
}
func (s *AtDocContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *AtDocContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *AtDocContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitAtDoc(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) AtDoc() (localctx IAtDocContext) {
localctx = NewAtDocContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 58, ApiParserParserRULE_atDoc)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(274)
p.Match(ApiParserParserATDOC)
}
p.SetState(276)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__1 {
{
p.SetState(275)
var _m = p.Match(ApiParserParserT__1)
localctx.(*AtDocContext).lp = _m
}
}
p.SetState(284)
p.GetErrorHandler().Sync(p)
switch p.GetTokenStream().LA(1) {
case ApiParserParserID:
p.SetState(279)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ok := true; ok; ok = _la == ApiParserParserID {
{
p.SetState(278)
p.KvLit()
}
p.SetState(281)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
case ApiParserParserSTRING:
{
p.SetState(283)
p.Match(ApiParserParserSTRING)
}
default:
panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
}
p.SetState(287)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ApiParserParserT__2 {
{
p.SetState(286)
var _m = p.Match(ApiParserParserT__2)
localctx.(*AtDocContext).rp = _m
}
}
return localctx
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/baseparser.go | tools/goctl/api/parser/g4/gen/api/baseparser.go | package api
import (
"fmt"
"net/http"
"regexp"
"strings"
"unicode"
"github.com/zeromicro/antlr"
)
const (
versionRegex = `(?m)"v[1-9][0-9]*"`
importValueRegex = `(?m)"\/?(?:[^/]+\/)*[^/]+.api"`
tagRegex = `(?m)\x60[a-z]+:".+"\x60`
)
var (
holder = struct{}{}
kind = map[string]struct{}{
"bool": holder,
"int": holder,
"int8": holder,
"int16": holder,
"int32": holder,
"int64": holder,
"uint": holder,
"uint8": holder,
"uint16": holder,
"uint32": holder,
"uint64": holder,
"uintptr": holder,
"float32": holder,
"float64": holder,
"complex64": holder,
"complex128": holder,
"string": holder,
"byte": holder,
"rune": holder,
}
)
func match(p *ApiParserParser, text string) {
v := getCurrentTokenText(p)
if v != text {
notifyErrorListeners(p, expecting(text, v))
}
}
func checkVersion(p *ApiParserParser) {
v := getCurrentTokenText(p)
if !matchRegex(v, versionRegex) {
notifyErrorListeners(p, mismatched("version", v))
}
}
func checkImportValue(p *ApiParserParser) {
v := getCurrentTokenText(p)
if !matchRegex(v, importValueRegex) {
notifyErrorListeners(p, mismatched("import value", v))
}
}
func checkKeyValue(p *ApiParserParser) {
v := getCurrentTokenText(p)
if !strings.HasPrefix(v, ":") {
notifyErrorListeners(p, mismatched(":", v))
}
v = strings.TrimPrefix(v, ":")
v = strings.TrimFunc(v, func(r rune) bool {
return unicode.IsSpace(r)
})
setCurrentTokenText(p, v)
}
func checkHTTPMethod(p *ApiParserParser) {
method := getCurrentTokenText(p)
uppler := strings.ToUpper(method)
switch uppler {
case http.MethodPost, http.MethodGet, http.MethodHead,
http.MethodPut, http.MethodPatch, http.MethodDelete,
http.MethodConnect, http.MethodOptions, http.MethodTrace:
if method != strings.ToLower(method) {
notifyErrorListeners(p, expecting("http method lower case", method))
}
default:
notifyErrorListeners(p, expecting("http method", method))
}
}
func checkKeyword(p *ApiParserParser) {
v := getCurrentTokenText(p)
if IsGolangKeyWord(v) {
notifyErrorListeners(p, fmt.Sprintf("expecting ID, found golang keyword: '%s'", v))
}
}
func checkKey(p *ApiParserParser) {
v := getCurrentTokenText(p)
if IsGolangKeyWord(v) {
notifyErrorListeners(p, fmt.Sprintf("expecting ID, found golang keyword: '%s'", v))
}
if _, ok := kind[v]; !ok {
notifyErrorListeners(p, fmt.Sprintf("expecting golang basic type, found : '%s'", v))
}
}
// IsBasicType returns true if the input argument is basic golang type
func IsBasicType(text string) bool {
_, ok := kind[text]
return ok
}
// IsGolangKeyWord returns true if input argument is golang keyword, but it will be ignored which in excepts
func IsGolangKeyWord(text string, excepts ...string) bool {
for _, each := range excepts {
if text == each {
return false
}
}
switch text {
case "var", "const", "package", "import", "func", "return",
"defer", "go", "select", "interface", "struct", "break", "case",
"continue", "for", "fallthrough", "else", "if", "switch", "goto",
"default", "chan", "type", "map", "range":
return true
default:
return false
}
}
func isNormal(p *ApiParserParser) bool {
ct := p.GetTokenStream().(*antlr.CommonTokenStream)
line := p.GetCurrentToken().GetLine()
tokens := ct.GetAllTokens()
var list []string
for _, token := range tokens {
if token.GetLine() == line {
text := token.GetText()
if strings.HasPrefix(text, "//") {
continue
}
if strings.HasPrefix(text, "/*") {
continue
}
if text == "<EOF>" {
continue
}
if strings.TrimSpace(text) == "" {
continue
}
list = append(list, text)
}
}
if len(list) == 1 {
t := strings.TrimPrefix(list[0], "*")
if IsGolangKeyWord(t) {
notifyErrorListeners(p, fmt.Sprintf("expecting ID, found golang keyword: '%s'", t))
}
}
if len(list) > 1 {
if list[0] == "*" {
t := strings.TrimPrefix(list[1], "*")
if IsGolangKeyWord(t) {
notifyErrorListeners(p, fmt.Sprintf("expecting ID, found golang keyword: '%s'", t))
}
return false
}
}
return len(list) > 1
}
// MatchTag returns a Boolean value, which returns true if it does matched, otherwise returns false
func MatchTag(v string) bool {
return matchRegex(v, tagRegex)
}
func isInterface(p *ApiParserParser) {
v := getCurrentTokenText(p)
if IsGolangKeyWord(v) {
notifyErrorListeners(p, fmt.Sprintf("expecting ID, found golang keyword: '%s'", v))
}
}
func getCurrentTokenText(p *ApiParserParser) string {
token := p.GetCurrentToken()
if token == nil {
return ""
}
return token.GetText()
}
func setCurrentTokenText(p *ApiParserParser, text string) {
token := p.GetCurrentToken()
if token == nil {
return
}
token.SetText(text)
}
func notifyErrorListeners(p *ApiParserParser, msg string) {
p.NotifyErrorListeners(msg, nil, nil)
}
func matchRegex(text, str string) bool {
re := regexp.MustCompile(str)
v := re.FindString(text)
text = strings.TrimFunc(text, func(r rune) bool {
return unicode.IsSpace(r)
})
return v == text
}
func expecting(expecting, found string) string {
return fmt.Sprintf(`expecting '%s', found input '%s'`, expecting, found)
}
func mismatched(expecting, found string) string {
return fmt.Sprintf(`mismatched '%s', found input '%s'`, expecting, found)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/file_splitor_test.go | tools/goctl/api/parser/g4/gen/api/file_splitor_test.go | // DO NOT EDIT.
// Tool: split apiparser_parser.go
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
package api
import (
"bufio"
"bytes"
"fmt"
"go/format"
"log"
"os"
"path/filepath"
"testing"
)
func TestFileSplitor(t *testing.T) {
t.Skip("skip this test because it is used to split the apiparser_parser.go file by developer.")
dir := "."
data, err := os.ReadFile(filepath.Join(dir, "apiparser_parser.go"))
if err != nil {
log.Fatalln(err)
}
r := bytes.NewReader(data)
reader := bufio.NewReader(r)
var lines, files int
buffer := bytes.NewBuffer(nil)
for {
fn, part := "apiparser_parser0.go", "main"
if files > 0 {
fn = fmt.Sprintf("apiparser_parser%d.go", files)
part = fmt.Sprintf("%d", files)
}
fp := filepath.Join(dir, fn)
buffer.Reset()
if files > 0 {
buffer.WriteString(fmt.Sprintf(`package api
import "github.com/zeromicro/antlr"
// Part %s
// The apiparser_parser.go file was split into multiple files because it
// was too large and caused a possible memory overflow during goctl installation.
`, part))
}
var exit bool
for {
line, _, err := reader.ReadLine()
buffer.Write(line)
buffer.WriteRune('\n')
if err != nil {
fmt.Printf("%+v\n", err)
exit = true
break
}
lines += 1
if string(line) == "}" && lines >= 650 {
break
}
}
src, err := format.Source(buffer.Bytes())
if err != nil {
fmt.Printf("%+v\n", err)
break
}
err = os.WriteFile(fp, src, os.ModePerm)
if err != nil {
fmt.Printf("%+v\n", err)
}
if exit {
break
}
lines = 0
files += 1
}
err = os.Rename(filepath.Join(dir, "apiparser_parser0.go"), filepath.Join(dir, "apiparser_parser.go"))
if err != nil {
log.Fatalln(err)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_parser.go | tools/goctl/api/parser/g4/gen/api/apiparser_parser.go | package api // ApiParser
import (
"fmt"
"reflect"
"strconv"
"github.com/zeromicro/antlr"
)
// Suppress unused import errors
var _ = fmt.Printf
var _ = reflect.Copy
var _ = strconv.Itoa
var parserATN = []uint16{
3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 3, 27, 356,
4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7,
4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13,
9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4, 18, 9,
18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 4, 23, 9, 23,
4, 24, 9, 24, 4, 25, 9, 25, 4, 26, 9, 26, 4, 27, 9, 27, 4, 28, 9, 28, 4,
29, 9, 29, 4, 30, 9, 30, 4, 31, 9, 31, 4, 32, 9, 32, 4, 33, 9, 33, 4, 34,
9, 34, 4, 35, 9, 35, 4, 36, 9, 36, 4, 37, 9, 37, 4, 38, 9, 38, 4, 39, 9,
39, 3, 2, 7, 2, 80, 10, 2, 12, 2, 14, 2, 83, 11, 2, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 5, 3, 90, 10, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 5, 3,
5, 5, 5, 100, 10, 5, 3, 6, 3, 6, 3, 6, 3, 6, 3, 7, 3, 7, 3, 7, 3, 7, 6,
7, 110, 10, 7, 13, 7, 14, 7, 111, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3,
9, 3, 10, 3, 10, 3, 10, 3, 10, 6, 10, 125, 10, 10, 13, 10, 14, 10, 126,
3, 10, 3, 10, 3, 11, 3, 11, 5, 11, 133, 10, 11, 3, 12, 3, 12, 3, 12, 3,
12, 3, 13, 3, 13, 3, 13, 3, 13, 7, 13, 143, 10, 13, 12, 13, 14, 13, 146,
11, 13, 3, 13, 3, 13, 3, 14, 3, 14, 5, 14, 152, 10, 14, 3, 15, 3, 15, 5,
15, 156, 10, 15, 3, 16, 3, 16, 3, 16, 5, 16, 161, 10, 16, 3, 16, 3, 16,
7, 16, 165, 10, 16, 12, 16, 14, 16, 168, 11, 16, 3, 16, 3, 16, 3, 17, 3,
17, 3, 17, 5, 17, 175, 10, 17, 3, 17, 3, 17, 3, 18, 3, 18, 3, 18, 5, 18,
182, 10, 18, 3, 18, 3, 18, 7, 18, 186, 10, 18, 12, 18, 14, 18, 189, 11,
18, 3, 18, 3, 18, 3, 19, 3, 19, 3, 19, 5, 19, 196, 10, 19, 3, 19, 3, 19,
3, 20, 3, 20, 3, 20, 5, 20, 203, 10, 20, 3, 21, 3, 21, 3, 21, 3, 21, 5,
21, 209, 10, 21, 3, 22, 5, 22, 212, 10, 22, 3, 22, 3, 22, 3, 23, 3, 23,
3, 23, 3, 23, 3, 23, 3, 23, 3, 23, 3, 23, 5, 23, 224, 10, 23, 3, 24, 3,
24, 3, 24, 3, 24, 3, 25, 3, 25, 3, 25, 3, 25, 3, 25, 3, 25, 3, 25, 3, 25,
3, 26, 3, 26, 3, 26, 3, 26, 3, 27, 5, 27, 243, 10, 27, 3, 27, 3, 27, 3,
28, 3, 28, 3, 28, 6, 28, 250, 10, 28, 13, 28, 14, 28, 251, 3, 28, 3, 28,
3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 7, 29, 261, 10, 29, 12, 29, 14, 29,
264, 11, 29, 3, 29, 3, 29, 3, 30, 5, 30, 269, 10, 30, 3, 30, 3, 30, 5,
30, 273, 10, 30, 3, 30, 3, 30, 3, 31, 3, 31, 5, 31, 279, 10, 31, 3, 31,
6, 31, 282, 10, 31, 13, 31, 14, 31, 283, 3, 31, 5, 31, 287, 10, 31, 3,
31, 5, 31, 290, 10, 31, 3, 32, 3, 32, 3, 32, 3, 33, 3, 33, 3, 33, 3, 33,
5, 33, 299, 10, 33, 3, 33, 5, 33, 302, 10, 33, 3, 34, 3, 34, 5, 34, 306,
10, 34, 3, 34, 3, 34, 3, 35, 3, 35, 3, 35, 5, 35, 313, 10, 35, 3, 35, 3,
35, 3, 36, 3, 36, 3, 36, 3, 36, 3, 37, 3, 37, 5, 37, 323, 10, 37, 6, 37,
325, 10, 37, 13, 37, 14, 37, 326, 3, 38, 3, 38, 3, 38, 3, 38, 7, 38, 333,
10, 38, 12, 38, 14, 38, 336, 11, 38, 3, 38, 3, 38, 3, 38, 3, 38, 5, 38,
342, 10, 38, 6, 38, 344, 10, 38, 13, 38, 14, 38, 345, 3, 38, 5, 38, 349,
10, 38, 3, 39, 6, 39, 352, 10, 39, 13, 39, 14, 39, 353, 3, 39, 2, 2, 40,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38,
40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74,
76, 2, 3, 3, 2, 26, 27, 2, 365, 2, 81, 3, 2, 2, 2, 4, 89, 3, 2, 2, 2, 6,
91, 3, 2, 2, 2, 8, 99, 3, 2, 2, 2, 10, 101, 3, 2, 2, 2, 12, 105, 3, 2,
2, 2, 14, 115, 3, 2, 2, 2, 16, 117, 3, 2, 2, 2, 18, 120, 3, 2, 2, 2, 20,
132, 3, 2, 2, 2, 22, 134, 3, 2, 2, 2, 24, 138, 3, 2, 2, 2, 26, 151, 3,
2, 2, 2, 28, 155, 3, 2, 2, 2, 30, 157, 3, 2, 2, 2, 32, 171, 3, 2, 2, 2,
34, 178, 3, 2, 2, 2, 36, 192, 3, 2, 2, 2, 38, 202, 3, 2, 2, 2, 40, 204,
3, 2, 2, 2, 42, 211, 3, 2, 2, 2, 44, 223, 3, 2, 2, 2, 46, 225, 3, 2, 2,
2, 48, 229, 3, 2, 2, 2, 50, 237, 3, 2, 2, 2, 52, 242, 3, 2, 2, 2, 54, 246,
3, 2, 2, 2, 56, 255, 3, 2, 2, 2, 58, 268, 3, 2, 2, 2, 60, 276, 3, 2, 2,
2, 62, 291, 3, 2, 2, 2, 64, 294, 3, 2, 2, 2, 66, 303, 3, 2, 2, 2, 68, 309,
3, 2, 2, 2, 70, 316, 3, 2, 2, 2, 72, 324, 3, 2, 2, 2, 74, 348, 3, 2, 2,
2, 76, 351, 3, 2, 2, 2, 78, 80, 5, 4, 3, 2, 79, 78, 3, 2, 2, 2, 80, 83,
3, 2, 2, 2, 81, 79, 3, 2, 2, 2, 81, 82, 3, 2, 2, 2, 82, 3, 3, 2, 2, 2,
83, 81, 3, 2, 2, 2, 84, 90, 5, 6, 4, 2, 85, 90, 5, 8, 5, 2, 86, 90, 5,
18, 10, 2, 87, 90, 5, 20, 11, 2, 88, 90, 5, 52, 27, 2, 89, 84, 3, 2, 2,
2, 89, 85, 3, 2, 2, 2, 89, 86, 3, 2, 2, 2, 89, 87, 3, 2, 2, 2, 89, 88,
3, 2, 2, 2, 90, 5, 3, 2, 2, 2, 91, 92, 8, 4, 1, 2, 92, 93, 7, 26, 2, 2,
93, 94, 7, 3, 2, 2, 94, 95, 8, 4, 1, 2, 95, 96, 7, 23, 2, 2, 96, 7, 3,
2, 2, 2, 97, 100, 5, 10, 6, 2, 98, 100, 5, 12, 7, 2, 99, 97, 3, 2, 2, 2,
99, 98, 3, 2, 2, 2, 100, 9, 3, 2, 2, 2, 101, 102, 8, 6, 1, 2, 102, 103,
7, 26, 2, 2, 103, 104, 5, 16, 9, 2, 104, 11, 3, 2, 2, 2, 105, 106, 8, 7,
1, 2, 106, 107, 7, 26, 2, 2, 107, 109, 7, 4, 2, 2, 108, 110, 5, 14, 8,
2, 109, 108, 3, 2, 2, 2, 110, 111, 3, 2, 2, 2, 111, 109, 3, 2, 2, 2, 111,
112, 3, 2, 2, 2, 112, 113, 3, 2, 2, 2, 113, 114, 7, 5, 2, 2, 114, 13, 3,
2, 2, 2, 115, 116, 5, 16, 9, 2, 116, 15, 3, 2, 2, 2, 117, 118, 8, 9, 1,
2, 118, 119, 7, 23, 2, 2, 119, 17, 3, 2, 2, 2, 120, 121, 8, 10, 1, 2, 121,
122, 7, 26, 2, 2, 122, 124, 7, 4, 2, 2, 123, 125, 5, 70, 36, 2, 124, 123,
3, 2, 2, 2, 125, 126, 3, 2, 2, 2, 126, 124, 3, 2, 2, 2, 126, 127, 3, 2,
2, 2, 127, 128, 3, 2, 2, 2, 128, 129, 7, 5, 2, 2, 129, 19, 3, 2, 2, 2,
130, 133, 5, 22, 12, 2, 131, 133, 5, 24, 13, 2, 132, 130, 3, 2, 2, 2, 132,
131, 3, 2, 2, 2, 133, 21, 3, 2, 2, 2, 134, 135, 8, 12, 1, 2, 135, 136,
7, 26, 2, 2, 136, 137, 5, 26, 14, 2, 137, 23, 3, 2, 2, 2, 138, 139, 8,
13, 1, 2, 139, 140, 7, 26, 2, 2, 140, 144, 7, 4, 2, 2, 141, 143, 5, 28,
15, 2, 142, 141, 3, 2, 2, 2, 143, 146, 3, 2, 2, 2, 144, 142, 3, 2, 2, 2,
144, 145, 3, 2, 2, 2, 145, 147, 3, 2, 2, 2, 146, 144, 3, 2, 2, 2, 147,
148, 7, 5, 2, 2, 148, 25, 3, 2, 2, 2, 149, 152, 5, 30, 16, 2, 150, 152,
5, 32, 17, 2, 151, 149, 3, 2, 2, 2, 151, 150, 3, 2, 2, 2, 152, 27, 3, 2,
2, 2, 153, 156, 5, 34, 18, 2, 154, 156, 5, 36, 19, 2, 155, 153, 3, 2, 2,
2, 155, 154, 3, 2, 2, 2, 156, 29, 3, 2, 2, 2, 157, 158, 8, 16, 1, 2, 158,
160, 7, 26, 2, 2, 159, 161, 7, 26, 2, 2, 160, 159, 3, 2, 2, 2, 160, 161,
3, 2, 2, 2, 161, 162, 3, 2, 2, 2, 162, 166, 7, 6, 2, 2, 163, 165, 5, 38,
20, 2, 164, 163, 3, 2, 2, 2, 165, 168, 3, 2, 2, 2, 166, 164, 3, 2, 2, 2,
166, 167, 3, 2, 2, 2, 167, 169, 3, 2, 2, 2, 168, 166, 3, 2, 2, 2, 169,
170, 7, 7, 2, 2, 170, 31, 3, 2, 2, 2, 171, 172, 8, 17, 1, 2, 172, 174,
7, 26, 2, 2, 173, 175, 7, 3, 2, 2, 174, 173, 3, 2, 2, 2, 174, 175, 3, 2,
2, 2, 175, 176, 3, 2, 2, 2, 176, 177, 5, 44, 23, 2, 177, 33, 3, 2, 2, 2,
178, 179, 8, 18, 1, 2, 179, 181, 7, 26, 2, 2, 180, 182, 7, 26, 2, 2, 181,
180, 3, 2, 2, 2, 181, 182, 3, 2, 2, 2, 182, 183, 3, 2, 2, 2, 183, 187,
7, 6, 2, 2, 184, 186, 5, 38, 20, 2, 185, 184, 3, 2, 2, 2, 186, 189, 3,
2, 2, 2, 187, 185, 3, 2, 2, 2, 187, 188, 3, 2, 2, 2, 188, 190, 3, 2, 2,
2, 189, 187, 3, 2, 2, 2, 190, 191, 7, 7, 2, 2, 191, 35, 3, 2, 2, 2, 192,
193, 8, 19, 1, 2, 193, 195, 7, 26, 2, 2, 194, 196, 7, 3, 2, 2, 195, 194,
3, 2, 2, 2, 195, 196, 3, 2, 2, 2, 196, 197, 3, 2, 2, 2, 197, 198, 5, 44,
23, 2, 198, 37, 3, 2, 2, 2, 199, 200, 6, 20, 2, 2, 200, 203, 5, 40, 21,
2, 201, 203, 5, 42, 22, 2, 202, 199, 3, 2, 2, 2, 202, 201, 3, 2, 2, 2,
203, 39, 3, 2, 2, 2, 204, 205, 8, 21, 1, 2, 205, 206, 7, 26, 2, 2, 206,
208, 5, 44, 23, 2, 207, 209, 7, 24, 2, 2, 208, 207, 3, 2, 2, 2, 208, 209,
3, 2, 2, 2, 209, 41, 3, 2, 2, 2, 210, 212, 7, 8, 2, 2, 211, 210, 3, 2,
2, 2, 211, 212, 3, 2, 2, 2, 212, 213, 3, 2, 2, 2, 213, 214, 7, 26, 2, 2,
214, 43, 3, 2, 2, 2, 215, 216, 8, 23, 1, 2, 216, 224, 7, 26, 2, 2, 217,
224, 5, 48, 25, 2, 218, 224, 5, 50, 26, 2, 219, 224, 7, 18, 2, 2, 220,
224, 7, 9, 2, 2, 221, 224, 5, 46, 24, 2, 222, 224, 5, 30, 16, 2, 223, 215,
3, 2, 2, 2, 223, 217, 3, 2, 2, 2, 223, 218, 3, 2, 2, 2, 223, 219, 3, 2,
2, 2, 223, 220, 3, 2, 2, 2, 223, 221, 3, 2, 2, 2, 223, 222, 3, 2, 2, 2,
224, 45, 3, 2, 2, 2, 225, 226, 7, 8, 2, 2, 226, 227, 8, 24, 1, 2, 227,
228, 7, 26, 2, 2, 228, 47, 3, 2, 2, 2, 229, 230, 8, 25, 1, 2, 230, 231,
7, 26, 2, 2, 231, 232, 7, 10, 2, 2, 232, 233, 8, 25, 1, 2, 233, 234, 7,
26, 2, 2, 234, 235, 7, 11, 2, 2, 235, 236, 5, 44, 23, 2, 236, 49, 3, 2,
2, 2, 237, 238, 7, 10, 2, 2, 238, 239, 7, 11, 2, 2, 239, 240, 5, 44, 23,
2, 240, 51, 3, 2, 2, 2, 241, 243, 5, 54, 28, 2, 242, 241, 3, 2, 2, 2, 242,
243, 3, 2, 2, 2, 243, 244, 3, 2, 2, 2, 244, 245, 5, 56, 29, 2, 245, 53,
3, 2, 2, 2, 246, 247, 7, 19, 2, 2, 247, 249, 7, 4, 2, 2, 248, 250, 5, 70,
36, 2, 249, 248, 3, 2, 2, 2, 250, 251, 3, 2, 2, 2, 251, 249, 3, 2, 2, 2,
251, 252, 3, 2, 2, 2, 252, 253, 3, 2, 2, 2, 253, 254, 7, 5, 2, 2, 254,
55, 3, 2, 2, 2, 255, 256, 8, 29, 1, 2, 256, 257, 7, 26, 2, 2, 257, 258,
5, 72, 37, 2, 258, 262, 7, 6, 2, 2, 259, 261, 5, 58, 30, 2, 260, 259, 3,
2, 2, 2, 261, 264, 3, 2, 2, 2, 262, 260, 3, 2, 2, 2, 262, 263, 3, 2, 2,
2, 263, 265, 3, 2, 2, 2, 264, 262, 3, 2, 2, 2, 265, 266, 7, 7, 2, 2, 266,
57, 3, 2, 2, 2, 267, 269, 5, 60, 31, 2, 268, 267, 3, 2, 2, 2, 268, 269,
3, 2, 2, 2, 269, 272, 3, 2, 2, 2, 270, 273, 5, 54, 28, 2, 271, 273, 5,
62, 32, 2, 272, 270, 3, 2, 2, 2, 272, 271, 3, 2, 2, 2, 273, 274, 3, 2,
2, 2, 274, 275, 5, 64, 33, 2, 275, 59, 3, 2, 2, 2, 276, 278, 7, 16, 2,
2, 277, 279, 7, 4, 2, 2, 278, 277, 3, 2, 2, 2, 278, 279, 3, 2, 2, 2, 279,
286, 3, 2, 2, 2, 280, 282, 5, 70, 36, 2, 281, 280, 3, 2, 2, 2, 282, 283,
3, 2, 2, 2, 283, 281, 3, 2, 2, 2, 283, 284, 3, 2, 2, 2, 284, 287, 3, 2,
2, 2, 285, 287, 7, 23, 2, 2, 286, 281, 3, 2, 2, 2, 286, 285, 3, 2, 2, 2,
287, 289, 3, 2, 2, 2, 288, 290, 7, 5, 2, 2, 289, 288, 3, 2, 2, 2, 289,
290, 3, 2, 2, 2, 290, 61, 3, 2, 2, 2, 291, 292, 7, 17, 2, 2, 292, 293,
7, 26, 2, 2, 293, 63, 3, 2, 2, 2, 294, 295, 8, 33, 1, 2, 295, 296, 7, 26,
2, 2, 296, 298, 5, 74, 38, 2, 297, 299, 5, 66, 34, 2, 298, 297, 3, 2, 2,
2, 298, 299, 3, 2, 2, 2, 299, 301, 3, 2, 2, 2, 300, 302, 5, 68, 35, 2,
301, 300, 3, 2, 2, 2, 301, 302, 3, 2, 2, 2, 302, 65, 3, 2, 2, 2, 303, 305,
7, 4, 2, 2, 304, 306, 7, 26, 2, 2, 305, 304, 3, 2, 2, 2, 305, 306, 3, 2,
2, 2, 306, 307, 3, 2, 2, 2, 307, 308, 7, 5, 2, 2, 308, 67, 3, 2, 2, 2,
309, 310, 7, 12, 2, 2, 310, 312, 7, 4, 2, 2, 311, 313, 5, 44, 23, 2, 312,
311, 3, 2, 2, 2, 312, 313, 3, 2, 2, 2, 313, 314, 3, 2, 2, 2, 314, 315,
7, 5, 2, 2, 315, 69, 3, 2, 2, 2, 316, 317, 7, 26, 2, 2, 317, 318, 8, 36,
1, 2, 318, 319, 7, 25, 2, 2, 319, 71, 3, 2, 2, 2, 320, 322, 7, 26, 2, 2,
321, 323, 7, 13, 2, 2, 322, 321, 3, 2, 2, 2, 322, 323, 3, 2, 2, 2, 323,
325, 3, 2, 2, 2, 324, 320, 3, 2, 2, 2, 325, 326, 3, 2, 2, 2, 326, 324,
3, 2, 2, 2, 326, 327, 3, 2, 2, 2, 327, 73, 3, 2, 2, 2, 328, 329, 7, 14,
2, 2, 329, 334, 5, 76, 39, 2, 330, 331, 7, 13, 2, 2, 331, 333, 5, 76, 39,
2, 332, 330, 3, 2, 2, 2, 333, 336, 3, 2, 2, 2, 334, 332, 3, 2, 2, 2, 334,
335, 3, 2, 2, 2, 335, 344, 3, 2, 2, 2, 336, 334, 3, 2, 2, 2, 337, 338,
7, 15, 2, 2, 338, 341, 5, 76, 39, 2, 339, 340, 7, 13, 2, 2, 340, 342, 5,
76, 39, 2, 341, 339, 3, 2, 2, 2, 341, 342, 3, 2, 2, 2, 342, 344, 3, 2,
2, 2, 343, 328, 3, 2, 2, 2, 343, 337, 3, 2, 2, 2, 344, 345, 3, 2, 2, 2,
345, 343, 3, 2, 2, 2, 345, 346, 3, 2, 2, 2, 346, 349, 3, 2, 2, 2, 347,
349, 7, 14, 2, 2, 348, 343, 3, 2, 2, 2, 348, 347, 3, 2, 2, 2, 349, 75,
3, 2, 2, 2, 350, 352, 9, 2, 2, 2, 351, 350, 3, 2, 2, 2, 352, 353, 3, 2,
2, 2, 353, 351, 3, 2, 2, 2, 353, 354, 3, 2, 2, 2, 354, 77, 3, 2, 2, 2,
42, 81, 89, 99, 111, 126, 132, 144, 151, 155, 160, 166, 174, 181, 187,
195, 202, 208, 211, 223, 242, 251, 262, 268, 272, 278, 283, 286, 289, 298,
301, 305, 312, 322, 326, 334, 341, 343, 345, 348, 353,
}
var literalNames = []string{
"", "'='", "'('", "')'", "'{'", "'}'", "'*'", "'time.Time'", "'['", "']'",
"'returns'", "'-'", "'/'", "'/:'", "'@doc'", "'@handler'", "'interface{}'",
"'@server'",
}
var symbolicNames = []string{
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "ATDOC", "ATHANDLER",
"INTERFACE", "ATSERVER", "WS", "COMMENT", "LINE_COMMENT", "STRING", "RAW_STRING",
"LINE_VALUE", "ID", "LetterOrDigit",
}
var ruleNames = []string{
"api", "spec", "syntaxLit", "importSpec", "importLit", "importBlock", "importBlockValue",
"importValue", "infoSpec", "typeSpec", "typeLit", "typeBlock", "typeLitBody",
"typeBlockBody", "typeStruct", "typeAlias", "typeBlockStruct", "typeBlockAlias",
"field", "normalField", "anonymousFiled", "dataType", "pointerType", "mapType",
"arrayType", "serviceSpec", "atServer", "serviceApi", "serviceRoute", "atDoc",
"atHandler", "route", "body", "replybody", "kvLit", "serviceName", "path",
"pathItem",
}
type ApiParserParser struct {
*antlr.BaseParser
}
// NewApiParserParser produces a new parser instance for the optional input antlr.TokenStream.
//
// The *ApiParserParser instance produced may be reused by calling the SetInputStream method.
// The initial parser configuration is expensive to construct, and the object is not thread-safe;
// however, if used within a Golang sync.Pool, the construction cost amortizes well and the
// objects can be used in a thread-safe manner.
func NewApiParserParser(input antlr.TokenStream) *ApiParserParser {
this := new(ApiParserParser)
deserializer := antlr.NewATNDeserializer(nil)
deserializedATN := deserializer.DeserializeFromUInt16(parserATN)
decisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState))
for index, ds := range deserializedATN.DecisionToState {
decisionToDFA[index] = antlr.NewDFA(ds, index)
}
this.BaseParser = antlr.NewBaseParser(input)
this.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())
this.RuleNames = ruleNames
this.LiteralNames = literalNames
this.SymbolicNames = symbolicNames
this.GrammarFileName = "ApiParser.g4"
return this
}
// ApiParserParser tokens.
const (
ApiParserParserEOF = antlr.TokenEOF
ApiParserParserT__0 = 1
ApiParserParserT__1 = 2
ApiParserParserT__2 = 3
ApiParserParserT__3 = 4
ApiParserParserT__4 = 5
ApiParserParserT__5 = 6
ApiParserParserT__6 = 7
ApiParserParserT__7 = 8
ApiParserParserT__8 = 9
ApiParserParserT__9 = 10
ApiParserParserT__10 = 11
ApiParserParserT__11 = 12
ApiParserParserT__12 = 13
ApiParserParserATDOC = 14
ApiParserParserATHANDLER = 15
ApiParserParserINTERFACE = 16
ApiParserParserATSERVER = 17
ApiParserParserWS = 18
ApiParserParserCOMMENT = 19
ApiParserParserLINE_COMMENT = 20
ApiParserParserSTRING = 21
ApiParserParserRAW_STRING = 22
ApiParserParserLINE_VALUE = 23
ApiParserParserID = 24
ApiParserParserLetterOrDigit = 25
)
// ApiParserParser rules.
const (
ApiParserParserRULE_api = 0
ApiParserParserRULE_spec = 1
ApiParserParserRULE_syntaxLit = 2
ApiParserParserRULE_importSpec = 3
ApiParserParserRULE_importLit = 4
ApiParserParserRULE_importBlock = 5
ApiParserParserRULE_importBlockValue = 6
ApiParserParserRULE_importValue = 7
ApiParserParserRULE_infoSpec = 8
ApiParserParserRULE_typeSpec = 9
ApiParserParserRULE_typeLit = 10
ApiParserParserRULE_typeBlock = 11
ApiParserParserRULE_typeLitBody = 12
ApiParserParserRULE_typeBlockBody = 13
ApiParserParserRULE_typeStruct = 14
ApiParserParserRULE_typeAlias = 15
ApiParserParserRULE_typeBlockStruct = 16
ApiParserParserRULE_typeBlockAlias = 17
ApiParserParserRULE_field = 18
ApiParserParserRULE_normalField = 19
ApiParserParserRULE_anonymousFiled = 20
ApiParserParserRULE_dataType = 21
ApiParserParserRULE_pointerType = 22
ApiParserParserRULE_mapType = 23
ApiParserParserRULE_arrayType = 24
ApiParserParserRULE_serviceSpec = 25
ApiParserParserRULE_atServer = 26
ApiParserParserRULE_serviceApi = 27
ApiParserParserRULE_serviceRoute = 28
ApiParserParserRULE_atDoc = 29
ApiParserParserRULE_atHandler = 30
ApiParserParserRULE_route = 31
ApiParserParserRULE_body = 32
ApiParserParserRULE_replybody = 33
ApiParserParserRULE_kvLit = 34
ApiParserParserRULE_serviceName = 35
ApiParserParserRULE_path = 36
ApiParserParserRULE_pathItem = 37
)
// IApiContext is an interface to support dynamic dispatch.
type IApiContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsApiContext differentiates from other interfaces.
IsApiContext()
}
type ApiContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyApiContext() *ApiContext {
var p = new(ApiContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_api
return p
}
func (*ApiContext) IsApiContext() {}
func NewApiContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ApiContext {
var p = new(ApiContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_api
return p
}
func (s *ApiContext) GetParser() antlr.Parser { return s.parser }
func (s *ApiContext) AllSpec() []ISpecContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*ISpecContext)(nil)).Elem())
var tst = make([]ISpecContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(ISpecContext)
}
}
return tst
}
func (s *ApiContext) Spec(i int) ISpecContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ISpecContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(ISpecContext)
}
func (s *ApiContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ApiContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ApiContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitApi(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Api() (localctx IApiContext) {
localctx = NewApiContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 0, ApiParserParserRULE_api)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(79)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ApiParserParserATSERVER || _la == ApiParserParserID {
{
p.SetState(76)
p.Spec()
}
p.SetState(81)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
return localctx
}
// ISpecContext is an interface to support dynamic dispatch.
type ISpecContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsSpecContext differentiates from other interfaces.
IsSpecContext()
}
type SpecContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptySpecContext() *SpecContext {
var p = new(SpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_spec
return p
}
func (*SpecContext) IsSpecContext() {}
func NewSpecContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SpecContext {
var p = new(SpecContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_spec
return p
}
func (s *SpecContext) GetParser() antlr.Parser { return s.parser }
func (s *SpecContext) SyntaxLit() ISyntaxLitContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ISyntaxLitContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ISyntaxLitContext)
}
func (s *SpecContext) ImportSpec() IImportSpecContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportSpecContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IImportSpecContext)
}
func (s *SpecContext) InfoSpec() IInfoSpecContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IInfoSpecContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IInfoSpecContext)
}
func (s *SpecContext) TypeSpec() ITypeSpecContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITypeSpecContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITypeSpecContext)
}
func (s *SpecContext) ServiceSpec() IServiceSpecContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IServiceSpecContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IServiceSpecContext)
}
func (s *SpecContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *SpecContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *SpecContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) {
case ApiParserVisitor:
return t.VisitSpec(s)
default:
return t.VisitChildren(s)
}
}
func (p *ApiParserParser) Spec() (localctx ISpecContext) {
localctx = NewSpecContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 2, ApiParserParserRULE_spec)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(87)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 1, p.GetParserRuleContext()) {
case 1:
p.EnterOuterAlt(localctx, 1)
{
p.SetState(82)
p.SyntaxLit()
}
case 2:
p.EnterOuterAlt(localctx, 2)
{
p.SetState(83)
p.ImportSpec()
}
case 3:
p.EnterOuterAlt(localctx, 3)
{
p.SetState(84)
p.InfoSpec()
}
case 4:
p.EnterOuterAlt(localctx, 4)
{
p.SetState(85)
p.TypeSpec()
}
case 5:
p.EnterOuterAlt(localctx, 5)
{
p.SetState(86)
p.ServiceSpec()
}
}
return localctx
}
// ISyntaxLitContext is an interface to support dynamic dispatch.
type ISyntaxLitContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// GetSyntaxToken returns the syntaxToken token.
GetSyntaxToken() antlr.Token
// GetAssign returns the assign token.
GetAssign() antlr.Token
// GetVersion returns the version token.
GetVersion() antlr.Token
// SetSyntaxToken sets the syntaxToken token.
SetSyntaxToken(antlr.Token)
// SetAssign sets the assign token.
SetAssign(antlr.Token)
// SetVersion sets the version token.
SetVersion(antlr.Token)
// IsSyntaxLitContext differentiates from other interfaces.
IsSyntaxLitContext()
}
type SyntaxLitContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
syntaxToken antlr.Token
assign antlr.Token
version antlr.Token
}
func NewEmptySyntaxLitContext() *SyntaxLitContext {
var p = new(SyntaxLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ApiParserParserRULE_syntaxLit
return p
}
func (*SyntaxLitContext) IsSyntaxLitContext() {}
func NewSyntaxLitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SyntaxLitContext {
var p = new(SyntaxLitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ApiParserParserRULE_syntaxLit
return p
}
func (s *SyntaxLitContext) GetParser() antlr.Parser { return s.parser }
func (s *SyntaxLitContext) GetSyntaxToken() antlr.Token { return s.syntaxToken }
func (s *SyntaxLitContext) GetAssign() antlr.Token { return s.assign }
func (s *SyntaxLitContext) GetVersion() antlr.Token { return s.version }
func (s *SyntaxLitContext) SetSyntaxToken(v antlr.Token) { s.syntaxToken = v }
func (s *SyntaxLitContext) SetAssign(v antlr.Token) { s.assign = v }
func (s *SyntaxLitContext) SetVersion(v antlr.Token) { s.version = v }
func (s *SyntaxLitContext) ID() antlr.TerminalNode {
return s.GetToken(ApiParserParserID, 0)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/gen/api/apiparser_visitor.go | tools/goctl/api/parser/g4/gen/api/apiparser_visitor.go | // Code generated from C:/Users/keson/GolandProjects/go-zero/tools/goctl/api/parser/g4\ApiParser.g4 by ANTLR 4.9. DO NOT EDIT.
package api // ApiParser
import "github.com/zeromicro/antlr"
// A complete Visitor for a parse tree produced by ApiParserParser.
type ApiParserVisitor interface {
antlr.ParseTreeVisitor
// Visit a parse tree produced by ApiParserParser#api.
VisitApi(ctx *ApiContext) any
// Visit a parse tree produced by ApiParserParser#spec.
VisitSpec(ctx *SpecContext) any
// Visit a parse tree produced by ApiParserParser#syntaxLit.
VisitSyntaxLit(ctx *SyntaxLitContext) any
// Visit a parse tree produced by ApiParserParser#importSpec.
VisitImportSpec(ctx *ImportSpecContext) any
// Visit a parse tree produced by ApiParserParser#importLit.
VisitImportLit(ctx *ImportLitContext) any
// Visit a parse tree produced by ApiParserParser#importBlock.
VisitImportBlock(ctx *ImportBlockContext) any
// Visit a parse tree produced by ApiParserParser#importBlockValue.
VisitImportBlockValue(ctx *ImportBlockValueContext) any
// Visit a parse tree produced by ApiParserParser#importValue.
VisitImportValue(ctx *ImportValueContext) any
// Visit a parse tree produced by ApiParserParser#infoSpec.
VisitInfoSpec(ctx *InfoSpecContext) any
// Visit a parse tree produced by ApiParserParser#typeSpec.
VisitTypeSpec(ctx *TypeSpecContext) any
// Visit a parse tree produced by ApiParserParser#typeLit.
VisitTypeLit(ctx *TypeLitContext) any
// Visit a parse tree produced by ApiParserParser#typeBlock.
VisitTypeBlock(ctx *TypeBlockContext) any
// Visit a parse tree produced by ApiParserParser#typeLitBody.
VisitTypeLitBody(ctx *TypeLitBodyContext) any
// Visit a parse tree produced by ApiParserParser#typeBlockBody.
VisitTypeBlockBody(ctx *TypeBlockBodyContext) any
// Visit a parse tree produced by ApiParserParser#typeStruct.
VisitTypeStruct(ctx *TypeStructContext) any
// Visit a parse tree produced by ApiParserParser#typeAlias.
VisitTypeAlias(ctx *TypeAliasContext) any
// Visit a parse tree produced by ApiParserParser#typeBlockStruct.
VisitTypeBlockStruct(ctx *TypeBlockStructContext) any
// Visit a parse tree produced by ApiParserParser#typeBlockAlias.
VisitTypeBlockAlias(ctx *TypeBlockAliasContext) any
// Visit a parse tree produced by ApiParserParser#field.
VisitField(ctx *FieldContext) any
// Visit a parse tree produced by ApiParserParser#normalField.
VisitNormalField(ctx *NormalFieldContext) any
// Visit a parse tree produced by ApiParserParser#anonymousFiled.
VisitAnonymousFiled(ctx *AnonymousFiledContext) any
// Visit a parse tree produced by ApiParserParser#dataType.
VisitDataType(ctx *DataTypeContext) any
// Visit a parse tree produced by ApiParserParser#pointerType.
VisitPointerType(ctx *PointerTypeContext) any
// Visit a parse tree produced by ApiParserParser#mapType.
VisitMapType(ctx *MapTypeContext) any
// Visit a parse tree produced by ApiParserParser#arrayType.
VisitArrayType(ctx *ArrayTypeContext) any
// Visit a parse tree produced by ApiParserParser#serviceSpec.
VisitServiceSpec(ctx *ServiceSpecContext) any
// Visit a parse tree produced by ApiParserParser#atServer.
VisitAtServer(ctx *AtServerContext) any
// Visit a parse tree produced by ApiParserParser#serviceApi.
VisitServiceApi(ctx *ServiceApiContext) any
// Visit a parse tree produced by ApiParserParser#serviceRoute.
VisitServiceRoute(ctx *ServiceRouteContext) any
// Visit a parse tree produced by ApiParserParser#atDoc.
VisitAtDoc(ctx *AtDocContext) any
// Visit a parse tree produced by ApiParserParser#atHandler.
VisitAtHandler(ctx *AtHandlerContext) any
// Visit a parse tree produced by ApiParserParser#route.
VisitRoute(ctx *RouteContext) any
// Visit a parse tree produced by ApiParserParser#body.
VisitBody(ctx *BodyContext) any
// Visit a parse tree produced by ApiParserParser#replybody.
VisitReplybody(ctx *ReplybodyContext) any
// Visit a parse tree produced by ApiParserParser#kvLit.
VisitKvLit(ctx *KvLitContext) any
// Visit a parse tree produced by ApiParserParser#serviceName.
VisitServiceName(ctx *ServiceNameContext) any
// Visit a parse tree produced by ApiParserParser#path.
VisitPath(ctx *PathContext) any
// Visit a parse tree produced by ApiParserParser#pathItem.
VisitPathItem(ctx *PathItemContext) any
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/ast_test.go | tools/goctl/api/parser/g4/test/ast_test.go | package test
import (
_ "embed"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
//go:embed apis/test.api
var testApi string
var parser = ast.NewParser(ast.WithParserPrefix("test.api"), ast.WithParserDebug())
func TestApi(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.Api().Accept(visitor)
}
v, err := parser.Accept(fn, testApi)
assert.Nil(t, err)
api := v.(*ast.Api)
body := &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("FooBar")},
}
returns := ast.NewTextExpr("returns")
assert.True(t, api.Equal(&ast.Api{
Syntax: &ast.SyntaxExpr{
Syntax: ast.NewTextExpr("syntax"),
Assign: ast.NewTextExpr("="),
Version: ast.NewTextExpr(`"v1"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// syntax doc"),
},
CommentExpr: ast.NewTextExpr("// syntax comment"),
},
Import: []*ast.ImportExpr{
{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"foo.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// import doc"),
},
CommentExpr: ast.NewTextExpr("// import comment"),
},
{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"bar.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// import group doc"),
},
CommentExpr: ast.NewTextExpr("// import group comment"),
},
},
Info: &ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("author"),
Value: ast.NewTextExpr(`"songmeizi"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// author doc"),
},
CommentExpr: ast.NewTextExpr("// author comment"),
},
{
Key: ast.NewTextExpr("date"),
Value: ast.NewTextExpr(`2020-01-04`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// date doc"),
},
CommentExpr: ast.NewTextExpr("// date comment"),
},
{
Key: ast.NewTextExpr("desc"),
Value: ast.NewTextExpr(`"break line
desc"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// desc doc"),
},
CommentExpr: ast.NewTextExpr("// desc comment"),
},
},
},
Type: []ast.TypeExpr{
&ast.TypeStruct{
Name: ast.NewTextExpr("FooBar"),
Struct: ast.NewTextExpr("struct"),
LBrace: ast.NewTextExpr("{"),
RBrace: ast.NewTextExpr("}"),
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("Foo"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
},
},
},
&ast.TypeStruct{
Name: ast.NewTextExpr("Bar"),
LBrace: ast.NewTextExpr("{"),
RBrace: ast.NewTextExpr("}"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// remove struct"),
},
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("VString"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("string")},
Tag: ast.NewTextExpr("`json:\"vString\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vString"),
},
},
{
Name: ast.NewTextExpr("VBool"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("bool")},
Tag: ast.NewTextExpr("`json:\"vBool\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vBool"),
},
},
{
Name: ast.NewTextExpr("VInt8"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int8")},
Tag: ast.NewTextExpr("`json:\"vInt8\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vInt8"),
},
},
{
Name: ast.NewTextExpr("VInt16"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int16")},
Tag: ast.NewTextExpr("`json:\"vInt16\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vInt16"),
},
},
{
Name: ast.NewTextExpr("VInt32"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int32")},
Tag: ast.NewTextExpr("`json:\"vInt32\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vInt32"),
},
},
{
Name: ast.NewTextExpr("VInt64"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int64")},
Tag: ast.NewTextExpr("`json:\"vInt64\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vInt64"),
},
},
{
Name: ast.NewTextExpr("VInt"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
Tag: ast.NewTextExpr("`json:\"vInt\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vInt"),
},
},
{
Name: ast.NewTextExpr("VUInt8"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("uint8")},
Tag: ast.NewTextExpr("`json:\"vUInt8\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vUInt8"),
},
},
{
Name: ast.NewTextExpr("VUInt16"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("uint16")},
Tag: ast.NewTextExpr("`json:\"vUInt16\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vUInt16"),
},
},
{
Name: ast.NewTextExpr("VUInt32"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("uint32")},
Tag: ast.NewTextExpr("`json:\"vUInt32\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vUInt32"),
},
},
{
Name: ast.NewTextExpr("VUInt64"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("uint64")},
Tag: ast.NewTextExpr("`json:\"vUInt64\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vUInt64"),
},
},
{
Name: ast.NewTextExpr("VFloat32"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("float32")},
Tag: ast.NewTextExpr("`json:\"vFloat32\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vFloat32"),
},
},
{
Name: ast.NewTextExpr("VFloat64"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("float64")},
Tag: ast.NewTextExpr("`json:\"vFloat64\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vFloat64"),
},
},
{
Name: ast.NewTextExpr("VByte"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("byte")},
Tag: ast.NewTextExpr("`json:\"vByte\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vByte"),
},
},
{
Name: ast.NewTextExpr("VRune"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("rune")},
Tag: ast.NewTextExpr("`json:\"vRune\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vRune"),
},
},
{
Name: ast.NewTextExpr("VMap"),
DataType: &ast.Map{
MapExpr: ast.NewTextExpr("map[string]int"),
Map: ast.NewTextExpr("map"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Key: ast.NewTextExpr("string"),
Value: &ast.Literal{Literal: ast.NewTextExpr("int")},
},
Tag: ast.NewTextExpr("`json:\"vMap\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vMap"),
},
},
{
Name: ast.NewTextExpr("VArray"),
DataType: &ast.Array{
ArrayExpr: ast.NewTextExpr("[]int"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Literal{Literal: ast.NewTextExpr("int")},
},
Tag: ast.NewTextExpr("`json:\"vArray\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vArray"),
},
},
{
Name: ast.NewTextExpr("VStruct"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("FooBar")},
Tag: ast.NewTextExpr("`json:\"vStruct\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vStruct"),
},
},
{
Name: ast.NewTextExpr("VStructPointer"),
DataType: &ast.Pointer{
PointerExpr: ast.NewTextExpr("*FooBar"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("FooBar"),
},
Tag: ast.NewTextExpr("`json:\"vStructPointer\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vStructPointer"),
},
},
{
Name: ast.NewTextExpr("VInterface"),
DataType: &ast.Interface{Literal: ast.NewTextExpr("interface{}")},
Tag: ast.NewTextExpr("`json:\"vInterface\"`"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// vInterface"),
},
},
{
IsAnonymous: true,
DataType: &ast.Literal{Literal: ast.NewTextExpr("FooBar")},
DocExpr: []ast.Expr{
ast.NewTextExpr("// inline"),
},
},
},
},
},
Service: []*ast.Service{
{
AtServer: &ast.AtServer{
AtServerToken: ast.NewTextExpr("@server"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("host"),
Value: ast.NewTextExpr("0.0.0.0"),
},
{
Key: ast.NewTextExpr("port"),
Value: ast.NewTextExpr("8080"),
},
{
Key: ast.NewTextExpr("annotation"),
Value: ast.NewTextExpr(`"break line
desc"`),
},
},
},
ServiceApi: &ast.ServiceApi{
ServiceToken: ast.NewTextExpr("service"),
Name: ast.NewTextExpr("foo-api"),
Lbrace: ast.NewTextExpr("{"),
Rbrace: ast.NewTextExpr("}"),
ServiceRoute: []*ast.ServiceRoute{
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("postFoo"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo"),
Req: body,
ReturnToken: returns,
Reply: body,
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
},
},
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("summary"),
Value: ast.NewTextExpr("bar"),
},
},
},
AtServer: &ast.AtServer{
AtServerToken: ast.NewTextExpr("@server"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("handler"),
Value: ast.NewTextExpr("postBar"),
},
},
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/bar"),
Req: body,
},
},
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foobar"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("postFooBar"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/bar"),
ReturnToken: returns,
Reply: body,
DocExpr: []ast.Expr{
ast.NewTextExpr(`/**
* httpmethod: post
* path: /foo/bar
* reply: FooBar
*/`),
},
},
},
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"barfoo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("postBarFoo"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/bar/foo"),
ReturnToken: returns,
Reply: body,
CommentExpr: ast.NewTextExpr("// post:/bar/foo"),
},
},
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"barfoo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("getBarFoo"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("get"),
Path: ast.NewTextExpr("/bar/foo"),
ReturnToken: returns,
Reply: body,
},
},
},
},
},
},
}))
}
func TestApiSyntax(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.Api().Accept(visitor)
}
parser.Accept(fn, `
// doc 1
// doc 2
syntax = "v1" // comment 1
// comment 2
import "foo.api"
`)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/grammar_test.go | tools/goctl/api/parser/g4/test/grammar_test.go | package test
import (
"testing"
"github.com/stretchr/testify/assert"
)
var files = []string{
"example",
"empty",
"syntax",
"info",
"types",
"service",
}
func TestGrammar(t *testing.T) {
for _, file := range files {
t.Run(file, func(t *testing.T) {
_, err := parser.Parse("./apis/" + file + ".api")
assert.Nil(t, err)
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/type_test.go | tools/goctl/api/parser/g4/test/type_test.go | package test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
var fieldAccept = func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.Field().Accept(visitor)
}
func TestField(t *testing.T) {
t.Run("anonymous", func(t *testing.T) {
v, err := parser.Accept(fieldAccept, `User`)
assert.Nil(t, err)
f := v.(*ast.TypeField)
assert.True(t, f.Equal(&ast.TypeField{
IsAnonymous: true,
DataType: &ast.Literal{Literal: ast.NewTextExpr("User")},
}))
v, err = parser.Accept(fieldAccept, `*User`)
assert.Nil(t, err)
f = v.(*ast.TypeField)
assert.True(t, f.Equal(&ast.TypeField{
IsAnonymous: true,
DataType: &ast.Pointer{
PointerExpr: ast.NewTextExpr("*User"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("User"),
},
}))
v, err = parser.Accept(fieldAccept, `
// anonymous user
*User // pointer type`)
assert.Nil(t, err)
f = v.(*ast.TypeField)
assert.True(t, f.Equal(&ast.TypeField{
IsAnonymous: true,
DataType: &ast.Pointer{
PointerExpr: ast.NewTextExpr("*User"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("User"),
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// anonymous user"),
},
CommentExpr: ast.NewTextExpr("// pointer type"),
}))
_, err = parser.Accept(fieldAccept, `interface`)
assert.Error(t, err)
_, err = parser.Accept(fieldAccept, `map`)
assert.Error(t, err)
})
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fieldAccept, `User int`)
assert.Nil(t, err)
f := v.(*ast.TypeField)
assert.True(t, f.Equal(&ast.TypeField{
Name: ast.NewTextExpr("User"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
}))
v, err = parser.Accept(fieldAccept, `Foo Bar`)
assert.Nil(t, err)
f = v.(*ast.TypeField)
assert.True(t, f.Equal(&ast.TypeField{
Name: ast.NewTextExpr("Foo"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
}))
v, err = parser.Accept(fieldAccept, `Foo map[int]Bar`)
assert.Nil(t, err)
f = v.(*ast.TypeField)
assert.True(t, f.Equal(&ast.TypeField{
Name: ast.NewTextExpr("Foo"),
DataType: &ast.Map{
MapExpr: ast.NewTextExpr("map[int]Bar"),
Map: ast.NewTextExpr("map"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Key: ast.NewTextExpr("int"),
Value: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
}))
})
}
func TestDataType_ID(t *testing.T) {
dt := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.DataType().Accept(visitor)
}
t.Run("Struct", func(t *testing.T) {
v, err := parser.Accept(dt, `Foo`)
assert.Nil(t, err)
id := v.(ast.DataType)
assert.True(t, id.Equal(&ast.Literal{Literal: ast.NewTextExpr("Foo")}))
})
t.Run("basic", func(t *testing.T) {
v, err := parser.Accept(dt, `int`)
assert.Nil(t, err)
id := v.(ast.DataType)
assert.True(t, id.Equal(&ast.Literal{Literal: ast.NewTextExpr("int")}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(dt, `map`)
assert.Error(t, err)
})
}
func TestDataType_Map(t *testing.T) {
dt := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.MapType().Accept(visitor)
}
t.Run("basicKey", func(t *testing.T) {
v, err := parser.Accept(dt, `map[int]Bar`)
assert.Nil(t, err)
m := v.(ast.DataType)
assert.True(t, m.Equal(&ast.Map{
MapExpr: ast.NewTextExpr("map[int]Bar"),
Map: ast.NewTextExpr("map"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Key: ast.NewTextExpr("int"),
Value: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(dt, `map[var]Bar`)
assert.Error(t, err)
_, err = parser.Accept(dt, `map[*User]Bar`)
assert.Error(t, err)
_, err = parser.Accept(dt, `map[User]Bar`)
assert.Error(t, err)
})
}
func TestDataType_Array(t *testing.T) {
dt := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.ArrayType().Accept(visitor)
}
t.Run("basic", func(t *testing.T) {
v, err := parser.Accept(dt, `[]int`)
assert.Nil(t, err)
array := v.(ast.DataType)
assert.True(t, array.Equal(&ast.Array{
ArrayExpr: ast.NewTextExpr("[]int"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Literal{Literal: ast.NewTextExpr("int")},
}))
})
t.Run("pointer", func(t *testing.T) {
v, err := parser.Accept(dt, `[]*User`)
assert.Nil(t, err)
array := v.(ast.DataType)
assert.True(t, array.Equal(&ast.Array{
ArrayExpr: ast.NewTextExpr("[]*User"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Pointer{
PointerExpr: ast.NewTextExpr("*User"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("User"),
},
}))
})
t.Run("interface{}", func(t *testing.T) {
v, err := parser.Accept(dt, `[]interface{}`)
assert.Nil(t, err)
array := v.(ast.DataType)
assert.True(t, array.Equal(&ast.Array{
ArrayExpr: ast.NewTextExpr("[]interface{}"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Interface{Literal: ast.NewTextExpr("interface{}")},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(dt, `[]var`)
assert.Error(t, err)
_, err = parser.Accept(dt, `[]interface`)
assert.Error(t, err)
})
}
func TestDataType_Interface(t *testing.T) {
dt := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.DataType().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(dt, `interface{}`)
assert.Nil(t, err)
inter := v.(ast.DataType)
assert.True(t, inter.Equal(&ast.Interface{Literal: ast.NewTextExpr("interface{}")}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(dt, `interface`)
assert.Error(t, err)
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(dt, `interface{`)
assert.Error(t, err)
})
}
func TestDataType_Time(t *testing.T) {
dt := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.DataType().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
_, err := parser.Accept(dt, `time.Time`)
assert.Error(t, err)
})
}
func TestDataType_Pointer(t *testing.T) {
dt := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.PointerType().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(dt, `*int`)
assert.Nil(t, err)
assert.True(t, v.(ast.DataType).Equal(&ast.Pointer{
PointerExpr: ast.NewTextExpr("*int"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("int"),
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(dt, `int`)
assert.Error(t, err)
})
}
func TestAlias(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.TypeAlias().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
_, err := parser.Accept(fn, `Foo int`)
assert.Error(t, err)
_, err = parser.Accept(fn, `Foo=int`)
assert.Error(t, err)
_, err = parser.Accept(fn, `
Foo int // comment`)
assert.Error(t, err)
_, err = parser.Accept(fn, `
Foo int /**comment*/`)
assert.Error(t, err)
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `Foo var`)
assert.Error(t, err)
_, err = parser.Accept(fn, `Foo 2`)
assert.Error(t, err)
})
}
func TestTypeStruct(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.TypeStruct().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, "Foo {\n\t\t\tFoo string\n\t\t\tBar int `json:\"bar\"``\n\t\t}")
assert.Nil(t, err)
s := v.(*ast.TypeStruct)
assert.True(t, s.Equal(&ast.TypeStruct{
Name: ast.NewTextExpr("Foo"),
LBrace: ast.NewTextExpr("{"),
RBrace: ast.NewTextExpr("}"),
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("Foo"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("string")},
},
{
Name: ast.NewTextExpr("Bar"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
Tag: ast.NewTextExpr("`json:\"bar\"`"),
},
},
}))
v, err = parser.Accept(fn, "Foo struct{\n\t\t\tFoo string\n\t\t\tBar int `json:\"bar\"``\n\t\t}")
assert.Nil(t, err)
s = v.(*ast.TypeStruct)
assert.True(t, s.Equal(&ast.TypeStruct{
Name: ast.NewTextExpr("Foo"),
LBrace: ast.NewTextExpr("{"),
RBrace: ast.NewTextExpr("}"),
Struct: ast.NewTextExpr("struct"),
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("Foo"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("string")},
},
{
Name: ast.NewTextExpr("Bar"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
Tag: ast.NewTextExpr("`json:\"bar\"`"),
},
},
}))
})
}
func TestTypeBlock(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.TypeBlock().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
_, err := parser.Accept(fn, `type(
// doc
Foo int
)`)
assert.Error(t, err)
v, err := parser.Accept(fn, `type (
// doc
Foo {
Bar int
}
)`)
assert.Nil(t, err)
st := v.([]ast.TypeExpr)
assert.True(t, st[0].Equal(&ast.TypeStruct{
Name: ast.NewTextExpr("Foo"),
LBrace: ast.NewTextExpr("{"),
RBrace: ast.NewTextExpr("}"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// doc"),
},
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("Bar"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
},
},
}))
})
}
func TestTypeLit(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.TypeLit().Accept(visitor)
}
t.Run("normal", func(t *testing.T) {
_, err := parser.Accept(fn, `type Foo int`)
assert.Error(t, err)
_, err = parser.Accept(fn, `type Foo = int`)
assert.Error(t, err)
_, err = parser.Accept(fn, `
// doc
type Foo = int // comment`)
assert.Error(t, err)
v, err := parser.Accept(fn, `
// doc
type Foo {// comment
Bar int
}`)
assert.Nil(t, err)
st := v.(*ast.TypeStruct)
assert.True(t, st.Equal(&ast.TypeStruct{
Name: ast.NewTextExpr("Foo"),
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("Bar"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
DocExpr: []ast.Expr{
ast.NewTextExpr("// comment"),
},
},
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// doc"),
},
}))
v, err = parser.Accept(fn, `
// doc
type Foo {// comment
Bar
}`)
assert.Nil(t, err)
st = v.(*ast.TypeStruct)
assert.True(t, st.Equal(&ast.TypeStruct{
Name: ast.NewTextExpr("Foo"),
Fields: []*ast.TypeField{
{
IsAnonymous: true,
DataType: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
DocExpr: []ast.Expr{
ast.NewTextExpr("// comment"),
},
},
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// doc"),
},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `type Foo`)
assert.Error(t, err)
})
}
func TestTypeUnExported(t *testing.T) {
fn := func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.TypeSpec().Accept(visitor)
}
t.Run("type", func(t *testing.T) {
_, err := parser.Accept(fn, `type foo {}`)
assert.Nil(t, err)
})
t.Run("field", func(t *testing.T) {
_, err := parser.Accept(fn, `type Foo {
name int
}`)
assert.Nil(t, err)
_, err = parser.Accept(fn, `type Foo {
Name int
}`)
assert.Nil(t, err)
})
t.Run("filedDataType", func(t *testing.T) {
_, err := parser.Accept(fn, `type Foo {
Foo *foo
Bar []bar
FooBar map[int]fooBar
}`)
assert.Nil(t, err)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/service_test.go | tools/goctl/api/parser/g4/test/service_test.go | package test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
func TestBody(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.Body().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `(Foo)`)
assert.Nil(t, err)
body := v.(*ast.Body)
assert.True(t, body.Equal(&ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `(var)`)
assert.Error(t, err)
_, err = parser.Accept(fn, `()`)
assert.Nil(t, err)
})
}
func TestRoute(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.Route().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `post /foo/foo-bar/:bar (Foo) returns (Bar)`)
assert.Nil(t, err)
route := v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
Req: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
},
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
}))
v, err = parser.Accept(fn, `post /foo/foo-bar/:bar (Foo)`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
Req: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
},
}))
v, err = parser.Accept(fn, `post /foo/foo-bar/:bar returns (Bar)`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
}))
v, err = parser.Accept(fn, `post /foo/foo-bar/:bar returns ([]Bar)`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Array{
ArrayExpr: ast.NewTextExpr("[]Bar"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
},
}))
v, err = parser.Accept(fn, `post /foo/foo-bar/:bar returns ([]*Bar)`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Array{
ArrayExpr: ast.NewTextExpr("[]*Bar"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Pointer{
PointerExpr: ast.NewTextExpr("*Bar"),
Star: ast.NewTextExpr("*"),
Name: ast.NewTextExpr("Bar"),
},
},
},
}))
v, err = parser.Accept(fn, `post /1/2a/3b/4`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/1/2a/3b/4"),
}))
v, err = parser.Accept(fn, `post /foo/foo-bar/:bar`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
}))
v, err = parser.Accept(fn, `
// foo
post /foo/foo-bar/:bar // bar`)
assert.Nil(t, err)
route = v.(*ast.Route)
assert.True(t, route.Equal(&ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo/foo-bar/:bar"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `posts /foo`)
assert.Error(t, err)
_, err = parser.Accept(fn, `gets /foo`)
assert.Error(t, err)
_, err = parser.Accept(fn, `post /foo/:`)
assert.Error(t, err)
_, err = parser.Accept(fn, `post /foo/`)
assert.Error(t, err)
_, err = parser.Accept(fn, `post foo/bar`)
assert.Error(t, err)
_, err = parser.Accept(fn, `post /foo/bar returns (Bar)`)
assert.Nil(t, err)
_, err = parser.Accept(fn, ` /foo/bar returns (Bar)`)
assert.Error(t, err)
_, err = parser.Accept(fn, ` post returns (Bar)`)
assert.Error(t, err)
_, err = parser.Accept(fn, ` post /foo/bar returns (int)`)
assert.Nil(t, err)
_, err = parser.Accept(fn, ` post /foo/bar returns (*int)`)
assert.Error(t, err)
_, err = parser.Accept(fn, ` post /foo/bar returns ([]var)`)
assert.Error(t, err)
_, err = parser.Accept(fn, ` post /foo/bar returns (const)`)
assert.Error(t, err)
})
}
func TestAtHandler(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.AtHandler().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `@handler foo`)
assert.Nil(t, err)
atHandler := v.(*ast.AtHandler)
assert.True(t, atHandler.Equal(&ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
}))
v, err = parser.Accept(fn, `
// foo
@handler foo // bar`)
assert.Nil(t, err)
atHandler = v.(*ast.AtHandler)
assert.True(t, atHandler.Equal(&ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, ``)
assert.Error(t, err)
_, err = parser.Accept(fn, `@handler`)
assert.Error(t, err)
_, err = parser.Accept(fn, `@handler "foo"`)
assert.Error(t, err)
})
}
func TestAtDoc(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.AtDoc().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `@doc "foo"`)
assert.Nil(t, err)
atDoc := v.(*ast.AtDoc)
assert.True(t, atDoc.Equal(&ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
LineDoc: ast.NewTextExpr(`"foo"`),
}))
v, err = parser.Accept(fn, `@doc("foo")`)
assert.Nil(t, err)
atDoc = v.(*ast.AtDoc)
assert.True(t, atDoc.Equal(&ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
}))
v, err = parser.Accept(fn, `@doc(
foo: bar
)`)
assert.Nil(t, err)
atDoc = v.(*ast.AtDoc)
assert.True(t, atDoc.Equal(&ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo"),
Value: ast.NewTextExpr("bar"),
},
},
}))
v, err = parser.Accept(fn, `@doc(
// foo
foo: bar // bar
)`)
assert.Nil(t, err)
atDoc = v.(*ast.AtDoc)
assert.True(t, atDoc.Equal(&ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo"),
Value: ast.NewTextExpr("bar"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `@doc("foo"`)
assert.Error(t, err)
_, err = parser.Accept(fn, `@doc "foo")`)
assert.Error(t, err)
})
}
func TestServiceRoute(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.ServiceRoute().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `
@doc("foo")
// foo/bar
// foo
@handler foo // bar
// foo/bar
// foo
post /foo (Foo) returns (Bar) // bar
`)
assert.Nil(t, err)
sr := v.(*ast.ServiceRoute)
assert.True(t, sr.Equal(&ast.ServiceRoute{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo"),
Req: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
},
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `post /foo (Foo) returns (Bar) // bar`)
assert.Error(t, err)
_, err = parser.Accept(fn, `@handler foo`)
assert.Error(t, err)
})
}
func TestServiceApi(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.ServiceApi().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `
service foo-api{
@doc("foo")
// foo/bar
// foo
@handler foo // bar
// foo/bar
// foo
post /foo (Foo) returns (Bar) // bar
}
`)
assert.Nil(t, err)
api := v.(*ast.ServiceApi)
assert.True(t, api.Equal(&ast.ServiceApi{
ServiceToken: ast.NewTextExpr("service"),
Name: ast.NewTextExpr("foo-api"),
Lbrace: ast.NewTextExpr("{"),
Rbrace: ast.NewTextExpr("}"),
ServiceRoute: []*ast.ServiceRoute{
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo"),
Req: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
},
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
},
},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `services foo-api{}`)
assert.Error(t, err)
_, err = parser.Accept(fn, `service foo-api{`)
assert.Error(t, err)
_, err = parser.Accept(fn, `service foo-api{
post /foo
}`)
assert.Error(t, err)
_, err = parser.Accept(fn, `service foo-api{
@handler foo
}`)
assert.Error(t, err)
})
}
func TestAtServer(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.AtServer().Accept(v)
}
t.Run("normal", func(t *testing.T) {
v, err := parser.Accept(fn, `
@server(
// foo
foo1: bar1 // bar
// foo
foo2: "bar2" // bar
/**foo*/
foo3: "foo
bar" /**bar*/
)
`)
assert.Nil(t, err)
as := v.(*ast.AtServer)
assert.True(t, as.Equal(&ast.AtServer{
AtServerToken: ast.NewTextExpr("@server"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo1"),
Value: ast.NewTextExpr("bar1"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
{
Key: ast.NewTextExpr("foo2"),
Value: ast.NewTextExpr(`"bar2"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
{
Key: ast.NewTextExpr("foo3"),
Value: ast.NewTextExpr(`"foo
bar"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**foo*/"),
},
CommentExpr: ast.NewTextExpr("/**bar*/"),
},
},
}))
})
t.Run("wrong", func(t *testing.T) {
_, err := parser.Accept(fn, `server (
foo:bar
)`)
assert.Error(t, err)
_, err = parser.Accept(fn, `@server ()`)
assert.Error(t, err)
_, err = parser.Accept(fn, `@server (
foo: bar
`)
assert.Error(t, err)
})
}
func TestServiceSpec(t *testing.T) {
fn := func(p *api.ApiParserParser, v *ast.ApiVisitor) any {
return p.ServiceSpec().Accept(v)
}
t.Run("normal", func(t *testing.T) {
_, err := parser.Accept(fn, `
service foo-api{
@handler foo
post /foo returns ([]int)
}
`)
assert.Nil(t, err)
v, err := parser.Accept(fn, `
@server(
// foo
foo1: bar1 // bar
// foo
foo2: "bar2" // bar
/**foo*/
foo3: "foo
bar" /**bar*/
)
service foo-api{
@doc("foo")
// foo/bar
// foo
@handler foo // bar
// foo/bar
// foo
post /foo (Foo) returns (Bar) // bar
}
`)
assert.Nil(t, err)
service := v.(*ast.Service)
assert.True(t, service.Equal(&ast.Service{
AtServer: &ast.AtServer{
AtServerToken: ast.NewTextExpr("@server"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo1"),
Value: ast.NewTextExpr("bar1"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
{
Key: ast.NewTextExpr("foo2"),
Value: ast.NewTextExpr(`"bar2"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
{
Key: ast.NewTextExpr("foo3"),
Value: ast.NewTextExpr(`"foo
bar"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**foo*/"),
},
CommentExpr: ast.NewTextExpr("/**bar*/"),
},
},
},
ServiceApi: &ast.ServiceApi{
ServiceToken: ast.NewTextExpr("service"),
Name: ast.NewTextExpr("foo-api"),
Lbrace: ast.NewTextExpr("{"),
Rbrace: ast.NewTextExpr("}"),
ServiceRoute: []*ast.ServiceRoute{
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo"),
Req: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
},
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
},
},
},
}))
v, err = parser.Accept(fn, `
service foo-api{
@doc("foo")
// foo/bar
// foo
@handler foo // bar
// foo/bar
// foo
post /foo (Foo) returns (Bar) // bar
}
`)
assert.Nil(t, err)
service = v.(*ast.Service)
assert.True(t, service.Equal(&ast.Service{
ServiceApi: &ast.ServiceApi{
ServiceToken: ast.NewTextExpr("service"),
Name: ast.NewTextExpr("foo-api"),
Lbrace: ast.NewTextExpr("{"),
Rbrace: ast.NewTextExpr("}"),
ServiceRoute: []*ast.ServiceRoute{
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo"),
Req: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
},
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Bar")},
},
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
},
},
},
}))
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/apiparser_test.go | tools/goctl/api/parser/g4/test/apiparser_test.go | package test
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
normalAPI = `
syntax="v1"
info (
foo: bar
)
type Foo {
Bar int
}
@server(
foo: bar
)
service foo-api{
@doc("foo")
@handler foo
post /foo (Foo) returns ([]int)
}
`
missDeclarationAPI = `
@server(
foo: bar
)
service foo-api{
@doc("foo")
@handler foo
post /foo (Foo) returns (Foo)
}
`
missDeclarationInArrayAPI = `
@server(
foo: bar
)
service foo-api{
@doc("foo")
@handler foo
post /foo returns ([]Foo)
}
`
missDeclarationInArrayAPI2 = `
@server(
foo: bar
)
service foo-api{
@doc("foo")
@handler foo
post /foo returns ([]*Foo)
}
`
nestedAPIImport = `
import "foo.api"
`
ambiguousSyntax = `
syntax = "v2"
`
ambiguousService = `
service bar-api{
@handler foo
post /foo
}
`
duplicateHandler = `
service bar-api{
@handler foo
post /foo
}
`
duplicateRoute = `
service bar-api{
@handler bar
post /foo
}
`
duplicateType = `
type Foo int
`
)
func TestApiParser(t *testing.T) {
t.Run("missDeclarationAPI", func(t *testing.T) {
_, err := parser.ParseContent(missDeclarationAPI)
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("missDeclarationAPI", func(t *testing.T) {
_, err := parser.ParseContent(missDeclarationInArrayAPI)
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("missDeclarationAPI", func(t *testing.T) {
_, err := parser.ParseContent(missDeclarationInArrayAPI2)
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("nestedImport", func(t *testing.T) {
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err := os.WriteFile(file, []byte(nestedAPIImport), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`import "%s"`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("duplicateImport", func(t *testing.T) {
_, err := parser.ParseContent(`
import "foo.api"
import "foo.api"
`)
assert.Error(t, err)
})
t.Run("duplicateKey", func(t *testing.T) {
_, err := parser.ParseContent(`
info (
foo: bar
foo: bar
)
`)
assert.Error(t, err)
})
t.Run("ambiguousSyntax", func(t *testing.T) {
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err := os.WriteFile(file, []byte(ambiguousSyntax), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`
syntax = "v1"
import "%s"`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("ambiguousSyntax", func(t *testing.T) {
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err := os.WriteFile(file, []byte(ambiguousSyntax), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`
syntax = "v1"
import "%s"`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("ambiguousService", func(t *testing.T) {
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err := os.WriteFile(file, []byte(ambiguousService), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`
import "%s"
service foo-api{
@handler foo
post /foo
}
`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("duplicateHandler", func(t *testing.T) {
_, err := parser.ParseContent(`
service foo-api{
@handler foo
post /foo
@handler foo
post /bar
}
`)
assert.Error(t, err)
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err = os.WriteFile(file, []byte(duplicateHandler), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`
import "%s"
service bar-api{
@handler foo
post /foo
}
`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("duplicateRoute", func(t *testing.T) {
_, err := parser.ParseContent(`
service foo-api{
@handler foo
post /foo
@handler bar
post /foo
}
`)
assert.Error(t, err)
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err = os.WriteFile(file, []byte(duplicateRoute), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`
import "%s"
service bar-api{
@handler foo
post /foo
}
`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("duplicateType", func(t *testing.T) {
_, err := parser.ParseContent(`
type Foo int
type Foo bool
`)
assert.Error(t, err)
file := filepath.Join(pathx.MustTempDir(), "foo.api")
err = os.WriteFile(file, []byte(duplicateType), os.ModePerm)
if err != nil {
return
}
_, err = parser.ParseContent(fmt.Sprintf(`
import "%s"
type Foo bool
`, file))
assert.Error(t, err)
fmt.Printf("%+v\n", err)
})
t.Run("normal", func(t *testing.T) {
v, err := parser.ParseContent(normalAPI)
assert.Nil(t, err)
body := &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Literal{Literal: ast.NewTextExpr("Foo")},
}
assert.True(t, v.Equal(&ast.Api{
Syntax: &ast.SyntaxExpr{
Syntax: ast.NewTextExpr("syntax"),
Assign: ast.NewTextExpr("="),
Version: ast.NewTextExpr(`"v1"`),
},
Info: &ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo"),
Value: ast.NewTextExpr("bar"),
},
},
},
Type: []ast.TypeExpr{
&ast.TypeStruct{
Name: ast.NewTextExpr("Foo"),
LBrace: ast.NewTextExpr("{"),
RBrace: ast.NewTextExpr("}"),
Fields: []*ast.TypeField{
{
Name: ast.NewTextExpr("Bar"),
DataType: &ast.Literal{Literal: ast.NewTextExpr("int")},
},
},
},
},
Service: []*ast.Service{
{
AtServer: &ast.AtServer{
AtServerToken: ast.NewTextExpr("@server"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Kv: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo"),
Value: ast.NewTextExpr("bar"),
},
},
},
ServiceApi: &ast.ServiceApi{
ServiceToken: ast.NewTextExpr("service"),
Name: ast.NewTextExpr("foo-api"),
Lbrace: ast.NewTextExpr("{"),
Rbrace: ast.NewTextExpr("}"),
ServiceRoute: []*ast.ServiceRoute{
{
AtDoc: &ast.AtDoc{
AtDocToken: ast.NewTextExpr("@doc"),
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
LineDoc: ast.NewTextExpr(`"foo"`),
},
AtHandler: &ast.AtHandler{
AtHandlerToken: ast.NewTextExpr("@handler"),
Name: ast.NewTextExpr("foo"),
},
Route: &ast.Route{
Method: ast.NewTextExpr("post"),
Path: ast.NewTextExpr("/foo"),
Req: body,
ReturnToken: ast.NewTextExpr("returns"),
Reply: &ast.Body{
Lp: ast.NewTextExpr("("),
Rp: ast.NewTextExpr(")"),
Name: &ast.Array{
ArrayExpr: ast.NewTextExpr("[]int"),
LBrack: ast.NewTextExpr("["),
RBrack: ast.NewTextExpr("]"),
Literal: &ast.Literal{Literal: ast.NewTextExpr("int")},
},
},
},
},
},
},
},
},
}))
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/info_test.go | tools/goctl/api/parser/g4/test/info_test.go | package test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
var infoAccept = func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.InfoSpec().Accept(visitor)
}
func TestInfo(t *testing.T) {
t.Run("matched", func(t *testing.T) {
v, err := parser.Accept(infoAccept, `
info(
title: foo
)
`)
assert.Nil(t, err)
info := v.(*ast.InfoExpr)
assert.True(t, info.Equal(&ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("title"),
Value: ast.NewTextExpr("foo"),
},
},
}))
v, err = parser.Accept(infoAccept, `
info(
title: 中文(bar)
)
`)
assert.Nil(t, err)
info = v.(*ast.InfoExpr)
assert.True(t, info.Equal(&ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("title"),
Value: ast.NewTextExpr("中文(bar)"),
},
},
}))
v, err = parser.Accept(infoAccept, `
info(
foo: "new
line"
)
`)
assert.Nil(t, err)
info = v.(*ast.InfoExpr)
assert.True(t, info.Equal(&ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("foo"),
Value: ast.NewTextExpr(`"new
line"`),
},
},
}))
})
t.Run("matched doc", func(t *testing.T) {
v, err := parser.Accept(infoAccept, `
// doc
info( // comment
// foo
title: foo // bar
)
`)
assert.Nil(t, err)
info := v.(*ast.InfoExpr)
assert.True(t, info.Equal(&ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("title"),
Value: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// foo"),
},
CommentExpr: ast.NewTextExpr("// bar"),
},
},
}))
v, err = parser.Accept(infoAccept, `
/**doc block*/
info( /**line block*/
/**foo*/
title: foo /*bar**/
)
`)
assert.Nil(t, err)
info = v.(*ast.InfoExpr)
assert.True(t, info.Equal(&ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("title"),
Value: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**foo*/"),
},
CommentExpr: ast.NewTextExpr("/*bar**/"),
},
},
}))
v, err = parser.Accept(infoAccept, `
info(
// doc
title: foo
// doc
author: bar
)
`)
assert.Nil(t, err)
info = v.(*ast.InfoExpr)
assert.True(t, info.Equal(&ast.InfoExpr{
Info: ast.NewTextExpr("info"),
Kvs: []*ast.KvExpr{
{
Key: ast.NewTextExpr("title"),
Value: ast.NewTextExpr("foo"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// doc"),
},
},
{
Key: ast.NewTextExpr("author"),
Value: ast.NewTextExpr("bar"),
DocExpr: []ast.Expr{
ast.NewTextExpr("// doc"),
},
},
},
}))
})
t.Run("mismatched", func(t *testing.T) {
_, err := parser.Accept(infoAccept, `
info(
title
)
`)
assert.Error(t, err)
_, err = parser.Accept(infoAccept, `
info(
:title
)
`)
assert.Error(t, err)
_, err = parser.Accept(infoAccept, `
info(
foo bar
)
`)
assert.Error(t, err)
_, err = parser.Accept(infoAccept, `
info(
foo : new
line
)
`)
assert.Error(t, err)
_, err = parser.Accept(infoAccept, `
info()
`)
assert.Error(t, err)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/import_test.go | tools/goctl/api/parser/g4/test/import_test.go | package test
import (
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
var importAccept = func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.ImportSpec().Accept(visitor)
}
func TestImport(t *testing.T) {
t.Run("matched", func(t *testing.T) {
v, err := parser.Accept(importAccept, `import "foo.api"`)
assert.Nil(t, err)
list := v.([]*ast.ImportExpr)
for _, each := range list {
assert.True(t, each.Equal(&ast.ImportExpr{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"foo.api"`),
}))
}
})
t.Run("matched block", func(t *testing.T) {
v, err := parser.Accept(importAccept, `
import (
/**foo*/
"foo.api"
/**bar*/
"bar.api"
/**foobar*/
"foo/bar.api"/**foobar*/
)
`)
assert.Nil(t, err)
list := v.([]*ast.ImportExpr)
expected := []*ast.ImportExpr{
{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"foo.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**foo*/"),
},
},
{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"bar.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**bar*/"),
},
},
{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"foo/bar.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**foobar*/"),
},
CommentExpr: ast.NewTextExpr("/**foobar*/"),
},
}
sort.Slice(list, func(i, j int) bool {
return list[i].Value.Line() < list[j].Value.Line()
})
sort.Slice(expected, func(i, j int) bool {
return expected[i].Value.Line() < expected[j].Value.Line()
})
assert.True(t, len(list) == len(expected))
for index, each := range list {
assert.True(t, each.Equal(expected[index]))
}
})
t.Run("matched doc", func(t *testing.T) {
v, err := parser.Accept(importAccept, `
/**doc*/
import "foo.api" /**line doc*/`)
assert.Nil(t, err)
list := v.([]*ast.ImportExpr)
for _, each := range list {
assert.True(t, each.Equal(&ast.ImportExpr{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"foo.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("/**doc*/"),
},
CommentExpr: ast.NewTextExpr("/**line doc*/"),
}))
}
})
t.Run("matched comment", func(t *testing.T) {
v, err := parser.Accept(importAccept, `
// comment block
import "foo.api" // line comment`)
assert.Nil(t, err)
list := v.([]*ast.ImportExpr)
for _, each := range list {
assert.True(t, each.Equal(&ast.ImportExpr{
Import: ast.NewTextExpr("import"),
Value: ast.NewTextExpr(`"foo.api"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// comment block"),
},
CommentExpr: ast.NewTextExpr("// line comment"),
}))
}
})
t.Run("mismatched import", func(t *testing.T) {
_, err := parser.Accept(importAccept, `
"foo.api"`)
assert.Error(t, err)
_, err = parser.Accept(importAccept, `
impor "foo.api"`)
assert.Error(t, err)
})
t.Run("mismatched value", func(t *testing.T) {
_, err := parser.Accept(importAccept, `
import "foo"`)
assert.Error(t, err)
_, err = parser.Accept(importAccept, `
import ""`)
assert.Error(t, err)
_, err = parser.Accept(importAccept, `
import `)
assert.Error(t, err)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/test/syntax_test.go | tools/goctl/api/parser/g4/test/syntax_test.go | package test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/ast"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
var syntaxAccept = func(p *api.ApiParserParser, visitor *ast.ApiVisitor) any {
return p.SyntaxLit().Accept(visitor)
}
func TestSyntax(t *testing.T) {
t.Run("matched", func(t *testing.T) {
v, err := parser.Accept(syntaxAccept, `syntax = "v1"`)
assert.Nil(t, err)
syntax := v.(*ast.SyntaxExpr)
assert.True(t, syntax.Equal(&ast.SyntaxExpr{
Syntax: ast.NewTextExpr("syntax"),
Assign: ast.NewTextExpr("="),
Version: ast.NewTextExpr(`"v1"`),
}))
})
t.Run("expecting syntax", func(t *testing.T) {
_, err := parser.Accept(syntaxAccept, `= "v1"`)
assert.Error(t, err)
_, err = parser.Accept(syntaxAccept, `syn = "v1"`)
assert.Error(t, err)
})
t.Run("missing assign", func(t *testing.T) {
_, err := parser.Accept(syntaxAccept, `syntax "v1"`)
assert.Error(t, err)
_, err = parser.Accept(syntaxAccept, `syntax + "v1"`)
assert.Error(t, err)
})
t.Run("mismatched version", func(t *testing.T) {
_, err := parser.Accept(syntaxAccept, `syntax="v0"`)
assert.Error(t, err)
_, err = parser.Accept(syntaxAccept, `syntax = "v1a"`)
assert.Error(t, err)
_, err = parser.Accept(syntaxAccept, `syntax = "vv1"`)
assert.Error(t, err)
_, err = parser.Accept(syntaxAccept, `syntax = "1"`)
assert.Error(t, err)
})
t.Run("with comment", func(t *testing.T) {
v, err := parser.Accept(syntaxAccept, `
// doc
syntax="v1" // line comment`)
assert.Nil(t, err)
syntax := v.(*ast.SyntaxExpr)
assert.True(t, syntax.Equal(&ast.SyntaxExpr{
Syntax: ast.NewTextExpr("syntax"),
Assign: ast.NewTextExpr("="),
Version: ast.NewTextExpr(`"v1"`),
DocExpr: []ast.Expr{
ast.NewTextExpr("// doc"),
},
CommentExpr: ast.NewTextExpr("// line comment"),
}))
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/kv.go | tools/goctl/api/parser/g4/ast/kv.go | package ast
import (
"strings"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
// KvExpr describes key-value for api
type KvExpr struct {
Key Expr
Value Expr
DocExpr []Expr
CommentExpr Expr
}
// VisitKvLit implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitKvLit(ctx *api.KvLitContext) any {
var kvExpr KvExpr
kvExpr.Key = v.newExprWithToken(ctx.GetKey())
commentExpr := v.getComment(ctx)
if ctx.GetValue() != nil {
valueText := ctx.GetValue().GetText()
valueExpr := v.newExprWithToken(ctx.GetValue())
if strings.Contains(valueText, "//") {
if commentExpr == nil {
commentExpr = v.newExprWithToken(ctx.GetValue())
commentExpr.SetText("")
}
index := strings.Index(valueText, "//")
commentExpr.SetText(valueText[index:])
valueExpr.SetText(strings.TrimSpace(valueText[:index]))
} else if strings.Contains(valueText, "/*") {
if commentExpr == nil {
commentExpr = v.newExprWithToken(ctx.GetValue())
commentExpr.SetText("")
}
index := strings.Index(valueText, "/*")
commentExpr.SetText(valueText[index:])
valueExpr.SetText(strings.TrimSpace(valueText[:index]))
}
kvExpr.Value = valueExpr
}
kvExpr.DocExpr = v.getDoc(ctx)
kvExpr.CommentExpr = commentExpr
return &kvExpr
}
// Format provides a formatter for api command, now nothing to do
func (k *KvExpr) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two KvExpr are equal
func (k *KvExpr) Equal(v any) bool {
if v == nil {
return false
}
kv, ok := v.(*KvExpr)
if !ok {
return false
}
if !EqualDoc(k, kv) {
return false
}
return k.Key.Equal(kv.Key) && k.Value.Equal(kv.Value)
}
// Doc returns the document of KvExpr, like // some text
func (k *KvExpr) Doc() []Expr {
return k.DocExpr
}
// Comment returns the comment of KvExpr, like // some text
func (k *KvExpr) Comment() Expr {
return k.CommentExpr
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/syntax.go | tools/goctl/api/parser/g4/ast/syntax.go | package ast
import "github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
// SyntaxExpr describes syntax for api
type SyntaxExpr struct {
Syntax Expr
Assign Expr
Version Expr
DocExpr []Expr
CommentExpr Expr
}
// VisitSyntaxLit implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitSyntaxLit(ctx *api.SyntaxLitContext) any {
syntax := v.newExprWithToken(ctx.GetSyntaxToken())
assign := v.newExprWithToken(ctx.GetAssign())
version := v.newExprWithToken(ctx.GetVersion())
return &SyntaxExpr{
Syntax: syntax,
Assign: assign,
Version: version,
DocExpr: v.getDoc(ctx),
CommentExpr: v.getComment(ctx),
}
}
// Format provides a formatter for api command, now nothing to do
func (s *SyntaxExpr) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two SyntaxExpr are equal
func (s *SyntaxExpr) Equal(v any) bool {
if v == nil {
return false
}
syntax, ok := v.(*SyntaxExpr)
if !ok {
return false
}
if !EqualDoc(s, syntax) {
return false
}
return s.Syntax.Equal(syntax.Syntax) &&
s.Assign.Equal(syntax.Assign) &&
s.Version.Equal(syntax.Version)
}
// Doc returns the document of SyntaxExpr, like // some text
func (s *SyntaxExpr) Doc() []Expr {
return s.DocExpr
}
// Comment returns the comment of SyntaxExpr, like // some text
func (s *SyntaxExpr) Comment() Expr {
return s.CommentExpr
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/api.go | tools/goctl/api/parser/g4/ast/api.go | package ast
import (
"fmt"
"path"
"sort"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
const (
prefixKey = "prefix"
groupKey = "group"
)
// Api describes syntax for api
type Api struct {
LinePrefix string
Syntax *SyntaxExpr
Import []*ImportExpr
importM map[string]PlaceHolder
Info *InfoExpr
Type []TypeExpr
typeM map[string]PlaceHolder
Service []*Service
serviceM map[string]PlaceHolder
handlerM map[string]PlaceHolder
routeM map[string]PlaceHolder
}
// VisitApi implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitApi(ctx *api.ApiContext) any {
var final Api
final.importM = map[string]PlaceHolder{}
final.typeM = map[string]PlaceHolder{}
final.serviceM = map[string]PlaceHolder{}
final.handlerM = map[string]PlaceHolder{}
final.routeM = map[string]PlaceHolder{}
for _, each := range ctx.AllSpec() {
root := each.Accept(v).(*Api)
v.acceptSyntax(root, &final)
v.acceptImport(root, &final)
v.acceptInfo(root, &final)
v.acceptType(root, &final)
v.acceptService(root, &final)
}
return &final
}
func (v *ApiVisitor) acceptService(root, final *Api) {
for _, service := range root.Service {
if _, ok := final.serviceM[service.ServiceApi.Name.Text()]; !ok && len(final.serviceM) > 0 {
v.panic(service.ServiceApi.Name, "multiple service declaration")
}
v.duplicateServerItemCheck(service)
var prefix, group string
if service.AtServer != nil {
p := service.AtServer.Kv.Get(prefixKey)
if p != nil {
prefix = p.Text()
}
g := service.AtServer.Kv.Get(groupKey)
if g != nil {
group = g.Text()
}
}
for _, route := range service.ServiceApi.ServiceRoute {
uniqueRoute := fmt.Sprintf("%s %s", route.Route.Method.Text(), path.Join(prefix, route.Route.Path.Text()))
if _, ok := final.routeM[uniqueRoute]; ok {
v.panic(route.Route.Method, fmt.Sprintf("duplicate route '%s'", uniqueRoute))
}
final.routeM[uniqueRoute] = Holder
var handlerExpr Expr
if route.AtServer != nil {
atServerM := map[string]PlaceHolder{}
for _, kv := range route.AtServer.Kv {
if _, ok := atServerM[kv.Key.Text()]; ok {
v.panic(kv.Key, fmt.Sprintf("duplicate key '%s'", kv.Key.Text()))
}
atServerM[kv.Key.Text()] = Holder
if kv.Key.Text() == "handler" {
handlerExpr = kv.Value
}
}
}
if route.AtHandler != nil {
handlerExpr = route.AtHandler.Name
}
if handlerExpr == nil {
v.panic(route.Route.Method, "mismatched handler")
}
if handlerExpr.Text() == "" {
v.panic(handlerExpr, "mismatched handler")
}
handlerKey := handlerExpr.Text()
if len(group) > 0 {
handlerKey = fmt.Sprintf("%s/%s", group, handlerExpr.Text())
}
if _, ok := final.handlerM[handlerKey]; ok {
v.panic(handlerExpr, fmt.Sprintf("duplicate handler '%s'", handlerExpr.Text()))
}
final.handlerM[handlerKey] = Holder
}
final.Service = append(final.Service, service)
}
}
func (v *ApiVisitor) duplicateServerItemCheck(service *Service) {
if service.AtServer != nil {
atServerM := map[string]PlaceHolder{}
for _, kv := range service.AtServer.Kv {
if _, ok := atServerM[kv.Key.Text()]; ok {
v.panic(kv.Key, fmt.Sprintf("duplicate key '%s'", kv.Key.Text()))
}
atServerM[kv.Key.Text()] = Holder
}
}
}
func (v *ApiVisitor) acceptType(root, final *Api) {
for _, tp := range root.Type {
if _, ok := final.typeM[tp.NameExpr().Text()]; ok {
v.panic(tp.NameExpr(), fmt.Sprintf("duplicate type '%s'", tp.NameExpr().Text()))
}
final.typeM[tp.NameExpr().Text()] = Holder
final.Type = append(final.Type, tp)
}
}
func (v *ApiVisitor) acceptInfo(root, final *Api) {
if root.Info != nil {
infoM := map[string]PlaceHolder{}
if final.Info != nil {
v.panic(root.Info.Info, "multiple info declaration")
}
for _, value := range root.Info.Kvs {
if _, ok := infoM[value.Key.Text()]; ok {
v.panic(value.Key, fmt.Sprintf("duplicate key '%s'", value.Key.Text()))
}
infoM[value.Key.Text()] = Holder
}
final.Info = root.Info
}
}
func (v *ApiVisitor) acceptImport(root, final *Api) {
for _, imp := range root.Import {
if _, ok := final.importM[imp.Value.Text()]; ok {
v.panic(imp.Import, fmt.Sprintf("duplicate import '%s'", imp.Value.Text()))
}
final.importM[imp.Value.Text()] = Holder
final.Import = append(final.Import, imp)
}
}
func (v *ApiVisitor) acceptSyntax(root, final *Api) {
if root.Syntax != nil {
if final.Syntax != nil {
v.panic(root.Syntax.Syntax, "multiple syntax declaration")
}
final.Syntax = root.Syntax
}
}
// VisitSpec implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitSpec(ctx *api.SpecContext) any {
var root Api
if ctx.SyntaxLit() != nil {
root.Syntax = ctx.SyntaxLit().Accept(v).(*SyntaxExpr)
}
if ctx.ImportSpec() != nil {
root.Import = ctx.ImportSpec().Accept(v).([]*ImportExpr)
}
if ctx.InfoSpec() != nil {
root.Info = ctx.InfoSpec().Accept(v).(*InfoExpr)
}
if ctx.TypeSpec() != nil {
tp := ctx.TypeSpec().Accept(v)
root.Type = tp.([]TypeExpr)
}
if ctx.ServiceSpec() != nil {
root.Service = []*Service{ctx.ServiceSpec().Accept(v).(*Service)}
}
return &root
}
// Format provides a formatter for api command, now nothing to do
func (a *Api) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Api are equal
func (a *Api) Equal(v any) bool {
if v == nil || a == nil {
return false
}
root, ok := v.(*Api)
if !ok {
return false
}
if !a.Syntax.Equal(root.Syntax) {
return false
}
if len(a.Import) != len(root.Import) {
return false
}
var expectingImport, actualImport []*ImportExpr
expectingImport = append(expectingImport, a.Import...)
actualImport = append(actualImport, root.Import...)
sort.Slice(expectingImport, func(i, j int) bool {
return expectingImport[i].Value.Text() < expectingImport[j].Value.Text()
})
sort.Slice(actualImport, func(i, j int) bool {
return actualImport[i].Value.Text() < actualImport[j].Value.Text()
})
for index, each := range expectingImport {
ac := actualImport[index]
if !each.Equal(ac) {
return false
}
}
if !a.Info.Equal(root.Info) {
return false
}
if len(a.Type) != len(root.Type) {
return false
}
var expectingType, actualType []TypeExpr
expectingType = append(expectingType, a.Type...)
actualType = append(actualType, root.Type...)
sort.Slice(expectingType, func(i, j int) bool {
return expectingType[i].NameExpr().Text() < expectingType[j].NameExpr().Text()
})
sort.Slice(actualType, func(i, j int) bool {
return actualType[i].NameExpr().Text() < actualType[j].NameExpr().Text()
})
for index, each := range expectingType {
ac := actualType[index]
if !each.Equal(ac) {
return false
}
}
if len(a.Service) != len(root.Service) {
return false
}
var expectingService, actualService []*Service
expectingService = append(expectingService, a.Service...)
actualService = append(actualService, root.Service...)
for index, each := range expectingService {
ac := actualService[index]
if !each.Equal(ac) {
return false
}
}
return true
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/service.go | tools/goctl/api/parser/g4/ast/service.go | package ast
import (
"fmt"
"sort"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
// Service describes service for api syntax
type Service struct {
AtServer *AtServer
ServiceApi *ServiceApi
}
// KV defines a slice for KvExpr
type KV []*KvExpr
// AtServer describes server metadata for api syntax
type AtServer struct {
AtServerToken Expr
Lp Expr
Rp Expr
Kv KV
}
// ServiceApi describes service ast for api syntax
type ServiceApi struct {
ServiceToken Expr
Name Expr
Lbrace Expr
Rbrace Expr
ServiceRoute []*ServiceRoute
}
// ServiceRoute describes service route ast for api syntax
type ServiceRoute struct {
AtDoc *AtDoc
AtServer *AtServer
AtHandler *AtHandler
Route *Route
}
// AtDoc describes service comments ast for api syntax
type AtDoc struct {
AtDocToken Expr
Lp Expr
Rp Expr
LineDoc Expr
Kv []*KvExpr
}
// AtHandler describes service handler ast for api syntax
type AtHandler struct {
AtHandlerToken Expr
Name Expr
DocExpr []Expr
CommentExpr Expr
}
// Route describes route ast for api syntax
type Route struct {
Method Expr
Path Expr
Req *Body
ReturnToken Expr
Reply *Body
DocExpr []Expr
CommentExpr Expr
}
// Body describes request,response body ast for api syntax
type Body struct {
ReturnExpr Expr
Lp Expr
Rp Expr
Name DataType
}
// VisitServiceSpec implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitServiceSpec(ctx *api.ServiceSpecContext) any {
var serviceSpec Service
if ctx.AtServer() != nil {
serviceSpec.AtServer = ctx.AtServer().Accept(v).(*AtServer)
}
serviceSpec.ServiceApi = ctx.ServiceApi().Accept(v).(*ServiceApi)
return &serviceSpec
}
// VisitAtServer implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitAtServer(ctx *api.AtServerContext) any {
var atServer AtServer
atServer.AtServerToken = v.newExprWithTerminalNode(ctx.ATSERVER())
atServer.Lp = v.newExprWithToken(ctx.GetLp())
atServer.Rp = v.newExprWithToken(ctx.GetRp())
for _, each := range ctx.AllKvLit() {
atServer.Kv = append(atServer.Kv, each.Accept(v).(*KvExpr))
}
return &atServer
}
// VisitServiceApi implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitServiceApi(ctx *api.ServiceApiContext) any {
var serviceApi ServiceApi
serviceApi.ServiceToken = v.newExprWithToken(ctx.GetServiceToken())
serviceName := ctx.ServiceName()
serviceApi.Name = v.newExprWithText(serviceName.GetText(), serviceName.GetStart().GetLine(), serviceName.GetStart().GetColumn(), serviceName.GetStart().GetStart(), serviceName.GetStop().GetStop())
serviceApi.Lbrace = v.newExprWithToken(ctx.GetLbrace())
serviceApi.Rbrace = v.newExprWithToken(ctx.GetRbrace())
for _, each := range ctx.AllServiceRoute() {
serviceApi.ServiceRoute = append(serviceApi.ServiceRoute, each.Accept(v).(*ServiceRoute))
}
return &serviceApi
}
// VisitServiceRoute implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitServiceRoute(ctx *api.ServiceRouteContext) any {
var serviceRoute ServiceRoute
if ctx.AtDoc() != nil {
serviceRoute.AtDoc = ctx.AtDoc().Accept(v).(*AtDoc)
}
if ctx.AtServer() != nil {
serviceRoute.AtServer = ctx.AtServer().Accept(v).(*AtServer)
} else if ctx.AtHandler() != nil {
serviceRoute.AtHandler = ctx.AtHandler().Accept(v).(*AtHandler)
}
serviceRoute.Route = ctx.Route().Accept(v).(*Route)
return &serviceRoute
}
// VisitAtDoc implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitAtDoc(ctx *api.AtDocContext) any {
var atDoc AtDoc
atDoc.AtDocToken = v.newExprWithTerminalNode(ctx.ATDOC())
if ctx.STRING() != nil {
atDoc.LineDoc = v.newExprWithTerminalNode(ctx.STRING())
} else {
for _, each := range ctx.AllKvLit() {
atDoc.Kv = append(atDoc.Kv, each.Accept(v).(*KvExpr))
}
}
atDoc.Lp = v.newExprWithToken(ctx.GetLp())
atDoc.Rp = v.newExprWithToken(ctx.GetRp())
if ctx.GetLp() != nil {
if ctx.GetRp() == nil {
v.panic(atDoc.Lp, "mismatched ')'")
}
}
if ctx.GetRp() != nil {
if ctx.GetLp() == nil {
v.panic(atDoc.Rp, "mismatched '('")
}
}
return &atDoc
}
// VisitAtHandler implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitAtHandler(ctx *api.AtHandlerContext) any {
var atHandler AtHandler
astHandlerExpr := v.newExprWithTerminalNode(ctx.ATHANDLER())
atHandler.AtHandlerToken = astHandlerExpr
atHandler.Name = v.newExprWithTerminalNode(ctx.ID())
atHandler.DocExpr = v.getDoc(ctx)
atHandler.CommentExpr = v.getComment(ctx)
return &atHandler
}
// VisitRoute implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitRoute(ctx *api.RouteContext) any {
var route Route
path := ctx.Path()
methodExpr := v.newExprWithToken(ctx.GetHttpMethod())
route.Method = methodExpr
route.Path = v.newExprWithText(path.GetText(), path.GetStart().GetLine(), path.GetStart().GetColumn(), path.GetStart().GetStart(), path.GetStop().GetStop())
if ctx.GetRequest() != nil {
req := ctx.GetRequest().Accept(v)
if req != nil {
route.Req = req.(*Body)
}
}
if ctx.GetResponse() != nil {
reply := ctx.GetResponse().Accept(v)
if reply != nil {
resp := reply.(*Body)
route.ReturnToken = resp.ReturnExpr
resp.ReturnExpr = nil
route.Reply = resp
}
}
route.DocExpr = v.getDoc(ctx)
route.CommentExpr = v.getComment(ctx)
return &route
}
// VisitBody implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitBody(ctx *api.BodyContext) any {
if ctx.ID() == nil {
if v.debug {
msg := fmt.Sprintf(
`%s line %d: expr "()" is deprecated, if there has no request body, please omit it`,
v.prefix,
ctx.GetStart().GetLine(),
)
v.log.Warning(msg)
}
return nil
}
idExpr := v.newExprWithTerminalNode(ctx.ID())
if api.IsGolangKeyWord(idExpr.Text()) {
v.panic(idExpr, fmt.Sprintf("expecting 'ID', but found golang keyword '%s'", idExpr.Text()))
}
return &Body{
Lp: v.newExprWithToken(ctx.GetLp()),
Rp: v.newExprWithToken(ctx.GetRp()),
Name: &Literal{Literal: idExpr},
}
}
// VisitReplybody implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitReplybody(ctx *api.ReplybodyContext) any {
if ctx.DataType() == nil {
if v.debug {
msg := fmt.Sprintf(
`%s line %d: expr "returns ()" or "()" is deprecated, if there has no response body, please omit it`,
v.prefix,
ctx.GetStart().GetLine(),
)
v.log.Warning(msg)
}
return nil
}
var returnExpr Expr
if ctx.GetReturnToken() != nil {
returnExpr = v.newExprWithToken(ctx.GetReturnToken())
if ctx.GetReturnToken().GetText() != "returns" {
v.panic(returnExpr, fmt.Sprintf("expecting returns, found input '%s'", ctx.GetReturnToken().GetText()))
}
}
dt := ctx.DataType().Accept(v).(DataType)
if dt == nil {
return nil
}
switch dataType := dt.(type) {
case *Array:
lit := dataType.Literal
switch lit.(type) {
case *Literal, *Pointer:
if api.IsGolangKeyWord(lit.Expr().Text()) {
v.panic(lit.Expr(), fmt.Sprintf("expecting 'ID', but found golang keyword '%s'", lit.Expr().Text()))
}
default:
v.panic(dt.Expr(), fmt.Sprintf("unsupported %s", dt.Expr().Text()))
}
case *Literal:
lit := dataType.Literal.Text()
if api.IsGolangKeyWord(lit) {
v.panic(dataType.Literal, fmt.Sprintf("expecting 'ID', but found golang keyword '%s'", lit))
}
default:
v.panic(dt.Expr(), fmt.Sprintf("unsupported %s", dt.Expr().Text()))
}
return &Body{
ReturnExpr: returnExpr,
Lp: v.newExprWithToken(ctx.GetLp()),
Rp: v.newExprWithToken(ctx.GetRp()),
Name: dt,
}
}
// Format provides a formatter for api command, now nothing to do
func (b *Body) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Body are equal
func (b *Body) Equal(v any) bool {
if v == nil {
return false
}
body, ok := v.(*Body)
if !ok {
return false
}
if !b.Lp.Equal(body.Lp) {
return false
}
if !b.Rp.Equal(body.Rp) {
return false
}
return b.Name.Equal(body.Name)
}
// Format provides a formatter for api command, now nothing to do
func (r *Route) Format() error {
// todo
return nil
}
// Doc returns the document of Route, like // some text
func (r *Route) Doc() []Expr {
return r.DocExpr
}
// Comment returns the comment of Route, like // some text
func (r *Route) Comment() Expr {
return r.CommentExpr
}
// Equal compares whether the element literals in two Route are equal
func (r *Route) Equal(v any) bool {
if v == nil {
return false
}
route, ok := v.(*Route)
if !ok {
return false
}
if !r.Method.Equal(route.Method) {
return false
}
if !r.Path.Equal(route.Path) {
return false
}
if r.Req != nil {
if !r.Req.Equal(route.Req) {
return false
}
}
if r.ReturnToken != nil {
if !r.ReturnToken.Equal(route.ReturnToken) {
return false
}
}
if r.Reply != nil {
if !r.Reply.Equal(route.Reply) {
return false
}
}
return EqualDoc(r, route)
}
// Doc returns the document of AtHandler, like // some text
func (a *AtHandler) Doc() []Expr {
return a.DocExpr
}
// Comment returns the comment of AtHandler, like // some text
func (a *AtHandler) Comment() Expr {
return a.CommentExpr
}
// Format provides a formatter for api command, now nothing to do
func (a *AtHandler) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two AtHandler are equal
func (a *AtHandler) Equal(v any) bool {
if v == nil {
return false
}
atHandler, ok := v.(*AtHandler)
if !ok {
return false
}
if !a.AtHandlerToken.Equal(atHandler.AtHandlerToken) {
return false
}
if !a.Name.Equal(atHandler.Name) {
return false
}
return EqualDoc(a, atHandler)
}
// Format provides a formatter for api command, now nothing to do
func (a *AtDoc) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two AtDoc are equal
func (a *AtDoc) Equal(v any) bool {
if v == nil {
return false
}
atDoc, ok := v.(*AtDoc)
if !ok {
return false
}
if !a.AtDocToken.Equal(atDoc.AtDocToken) {
return false
}
if a.Lp.IsNotNil() {
if !a.Lp.Equal(atDoc.Lp) {
return false
}
}
if a.Rp.IsNotNil() {
if !a.Rp.Equal(atDoc.Rp) {
return false
}
}
if a.LineDoc != nil {
if !a.LineDoc.Equal(atDoc.LineDoc) {
return false
}
}
var expecting, actual []*KvExpr
expecting = append(expecting, a.Kv...)
actual = append(actual, atDoc.Kv...)
if len(expecting) != len(actual) {
return false
}
for index, each := range expecting {
ac := actual[index]
if !each.Equal(ac) {
return false
}
}
return true
}
// Format provides a formatter for api command, now nothing to do
func (a *AtServer) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two AtServer are equal
func (a *AtServer) Equal(v any) bool {
if v == nil {
return false
}
atServer, ok := v.(*AtServer)
if !ok {
return false
}
if !a.AtServerToken.Equal(atServer.AtServerToken) {
return false
}
if !a.Lp.Equal(atServer.Lp) {
return false
}
if !a.Rp.Equal(atServer.Rp) {
return false
}
var expecting, actual []*KvExpr
expecting = append(expecting, a.Kv...)
actual = append(actual, atServer.Kv...)
if len(expecting) != len(actual) {
return false
}
sort.Slice(expecting, func(i, j int) bool {
return expecting[i].Key.Text() < expecting[j].Key.Text()
})
sort.Slice(actual, func(i, j int) bool {
return actual[i].Key.Text() < actual[j].Key.Text()
})
for index, each := range expecting {
ac := actual[index]
if !each.Equal(ac) {
return false
}
}
return true
}
// Equal compares whether the element literals in two ServiceRoute are equal
func (s *ServiceRoute) Equal(v any) bool {
if v == nil {
return false
}
sr, ok := v.(*ServiceRoute)
if !ok {
return false
}
if !s.AtDoc.Equal(sr.AtDoc) {
return false
}
if s.AtServer != nil {
if !s.AtServer.Equal(sr.AtServer) {
return false
}
}
if s.AtHandler != nil {
if !s.AtHandler.Equal(sr.AtHandler) {
return false
}
}
return s.Route.Equal(sr.Route)
}
// Format provides a formatter for api command, now nothing to do
func (s *ServiceRoute) Format() error {
// todo
return nil
}
// GetHandler returns handler name of api route
func (s *ServiceRoute) GetHandler() Expr {
if s.AtHandler != nil {
return s.AtHandler.Name
}
return s.AtServer.Kv.Get("handler")
}
// Format provides a formatter for api command, now nothing to do
func (a *ServiceApi) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two ServiceApi are equal
func (a *ServiceApi) Equal(v any) bool {
if v == nil {
return false
}
api, ok := v.(*ServiceApi)
if !ok {
return false
}
if !a.ServiceToken.Equal(api.ServiceToken) {
return false
}
if !a.Name.Equal(api.Name) {
return false
}
if !a.Lbrace.Equal(api.Lbrace) {
return false
}
if !a.Rbrace.Equal(api.Rbrace) {
return false
}
var expecting, acutal []*ServiceRoute
expecting = append(expecting, a.ServiceRoute...)
acutal = append(acutal, api.ServiceRoute...)
if len(expecting) != len(acutal) {
return false
}
sort.Slice(expecting, func(i, j int) bool {
return expecting[i].Route.Path.Text() < expecting[j].Route.Path.Text()
})
sort.Slice(acutal, func(i, j int) bool {
return acutal[i].Route.Path.Text() < acutal[j].Route.Path.Text()
})
for index, each := range expecting {
ac := acutal[index]
if !each.Equal(ac) {
return false
}
}
return true
}
// Format provides a formatter for api command, now nothing to do
func (s *Service) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Service are equal
func (s *Service) Equal(v any) bool {
if v == nil {
return false
}
service, ok := v.(*Service)
if !ok {
return false
}
if s.AtServer != nil {
if !s.AtServer.Equal(service.AtServer) {
return false
}
}
return s.ServiceApi.Equal(service.ServiceApi)
}
// Get returns the target KV by specified key
func (kv KV) Get(key string) Expr {
for _, each := range kv {
if each.Key.Text() == key {
return each.Value
}
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/placeholder.go | tools/goctl/api/parser/g4/ast/placeholder.go | package ast
// Holder defines a default instance for PlaceHolder
var Holder PlaceHolder
// PlaceHolder defines an empty struct
type PlaceHolder struct{}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/apiparser.go | tools/goctl/api/parser/g4/ast/apiparser.go | package ast
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/zeromicro/antlr"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
)
type (
// Parser provides api parsing capabilities
Parser struct {
antlr.DefaultErrorListener
linePrefix string
debug bool
log console.Console
skipCheckTypeDeclaration bool
handlerMap map[string]PlaceHolder
routeMap map[string]PlaceHolder
typeMap map[string]PlaceHolder
fileMap map[string]PlaceHolder
importStatck importStack
syntax *SyntaxExpr
}
// ParserOption defines a function with argument Parser
ParserOption func(p *Parser)
)
// NewParser creates an instance for Parser
func NewParser(options ...ParserOption) *Parser {
p := &Parser{
log: console.NewColorConsole(),
}
for _, opt := range options {
opt(p)
}
p.handlerMap = make(map[string]PlaceHolder)
p.routeMap = make(map[string]PlaceHolder)
p.typeMap = make(map[string]PlaceHolder)
p.fileMap = make(map[string]PlaceHolder)
return p
}
// Accept can parse any terminalNode of api tree by fn.
// -- for debug
func (p *Parser) Accept(fn func(p *api.ApiParserParser, visitor *ApiVisitor) any, content string) (v any, err error) {
defer func() {
p := recover()
if p != nil {
switch e := p.(type) {
case error:
err = e
default:
err = fmt.Errorf("%+v", p)
}
}
}()
inputStream := antlr.NewInputStream(content)
lexer := api.NewApiParserLexer(inputStream)
lexer.RemoveErrorListeners()
tokens := antlr.NewCommonTokenStream(lexer, antlr.LexerDefaultTokenChannel)
apiParser := api.NewApiParserParser(tokens)
apiParser.RemoveErrorListeners()
apiParser.AddErrorListener(p)
var visitorOptions []VisitorOption
visitorOptions = append(visitorOptions, WithVisitorPrefix(p.linePrefix))
if p.debug {
visitorOptions = append(visitorOptions, WithVisitorDebug())
}
visitor := NewApiVisitor(visitorOptions...)
v = fn(apiParser, visitor)
return
}
// Parse is used to parse the api from the specified file name
func (p *Parser) Parse(filename string) (*Api, error) {
abs, err := filepath.Abs(filename)
if err != nil {
return nil, err
}
data, err := p.readContent(filename)
if err != nil {
return nil, err
}
p.importStatck.push(abs)
return p.parse(filename, data)
}
// ParseContent is used to parse the api from the specified content
func (p *Parser) ParseContent(content string, filename ...string) (*Api, error) {
var f, abs string
if len(filename) > 0 {
f = filename[0]
a, err := filepath.Abs(f)
if err != nil {
return nil, err
}
abs = a
}
p.importStatck.push(abs)
return p.parse(f, content)
}
// parse is used to parse api from the content
// filename is only used to mark the file where the error is located
func (p *Parser) parse(filename, content string) (*Api, error) {
root, err := p.invoke(filename, content)
if err != nil {
return nil, err
}
var apiAstList []*Api
apiAstList = append(apiAstList, root)
p.storeVerificationInfo(root)
p.syntax = root.Syntax
impApiAstList, err := p.invokeImportedApi(filename, root.Import)
if err != nil {
return nil, err
}
apiAstList = append(apiAstList, impApiAstList...)
if !p.skipCheckTypeDeclaration {
err = p.checkTypeDeclaration(apiAstList)
if err != nil {
return nil, err
}
}
allApi := p.memberFill(apiAstList)
return allApi, nil
}
func (p *Parser) invokeImportedApi(filename string, imports []*ImportExpr) ([]*Api, error) {
var apiAstList []*Api
for _, imp := range imports {
dir := filepath.Dir(filename)
impPath := strings.ReplaceAll(imp.Value.Text(), "\"", "")
if !filepath.IsAbs(impPath) {
impPath = filepath.Join(dir, impPath)
}
// import cycle check
if err := p.importStatck.push(impPath); err != nil {
return nil, err
}
// ignore already imported file
if p.alreadyImported(impPath) {
p.importStatck.pop()
continue
}
p.fileMap[impPath] = PlaceHolder{}
data, err := p.readContent(impPath)
if err != nil {
return nil, err
}
nestedApi, err := p.invoke(impPath, data)
if err != nil {
return nil, err
}
err = p.valid(nestedApi)
if err != nil {
return nil, err
}
p.storeVerificationInfo(nestedApi)
apiAstList = append(apiAstList, nestedApi)
list, err := p.invokeImportedApi(impPath, nestedApi.Import)
p.importStatck.pop()
apiAstList = append(apiAstList, list...)
if err != nil {
return nil, err
}
}
return apiAstList, nil
}
func (p *Parser) alreadyImported(filename string) bool {
_, ok := p.fileMap[filename]
return ok
}
func (p *Parser) invoke(linePrefix, content string) (v *Api, err error) {
defer func() {
p := recover()
if p != nil {
switch e := p.(type) {
case error:
err = e
default:
err = fmt.Errorf("%+v", p)
}
}
}()
if linePrefix != "" {
p.linePrefix = linePrefix
}
inputStream := antlr.NewInputStream(content)
lexer := api.NewApiParserLexer(inputStream)
lexer.RemoveErrorListeners()
tokens := antlr.NewCommonTokenStream(lexer, antlr.LexerDefaultTokenChannel)
apiParser := api.NewApiParserParser(tokens)
apiParser.RemoveErrorListeners()
apiParser.AddErrorListener(p)
var visitorOptions []VisitorOption
visitorOptions = append(visitorOptions, WithVisitorPrefix(p.linePrefix))
if p.debug {
visitorOptions = append(visitorOptions, WithVisitorDebug())
}
visitor := NewApiVisitor(visitorOptions...)
v = apiParser.Api().Accept(visitor).(*Api)
v.LinePrefix = p.linePrefix
return
}
// storeVerificationInfo stores information for verification
func (p *Parser) storeVerificationInfo(api *Api) {
routeMap := func(list []*ServiceRoute, prefix string) {
for _, g := range list {
handler := g.GetHandler()
if handler.IsNotNil() {
handlerName := handler.Text()
p.handlerMap[handlerName] = Holder
route := fmt.Sprintf("%s://%s", g.Route.Method.Text(), path.Join(prefix, g.Route.Path.Text()))
p.routeMap[route] = Holder
}
}
}
for _, each := range api.Service {
var prefix string
if each.AtServer != nil {
pExp := each.AtServer.Kv.Get(prefixKey)
if pExp != nil {
prefix = pExp.Text()
}
}
routeMap(each.ServiceApi.ServiceRoute, prefix)
}
for _, each := range api.Type {
p.typeMap[each.NameExpr().Text()] = Holder
}
}
func (p *Parser) valid(nestedApi *Api) error {
if p.syntax != nil && nestedApi.Syntax != nil {
if p.syntax.Version.Text() != nestedApi.Syntax.Version.Text() {
syntaxToken := nestedApi.Syntax.Syntax
return fmt.Errorf("%s line %d:%d multiple syntax declaration, expecting syntax '%s', but found '%s'",
nestedApi.LinePrefix, syntaxToken.Line(), syntaxToken.Column(), p.syntax.Version.Text(), nestedApi.Syntax.Version.Text())
}
}
// duplicate route check
err := p.duplicateRouteCheck(nestedApi)
if err != nil {
return err
}
// duplicate type check
for _, each := range nestedApi.Type {
if _, ok := p.typeMap[each.NameExpr().Text()]; ok {
return fmt.Errorf("%s line %d:%d duplicate type declaration '%s'",
nestedApi.LinePrefix, each.NameExpr().Line(), each.NameExpr().Column(), each.NameExpr().Text())
}
}
return nil
}
func (p *Parser) duplicateRouteCheck(nestedApi *Api) error {
for _, each := range nestedApi.Service {
var prefix, group string
if each.AtServer != nil {
p := each.AtServer.Kv.Get(prefixKey)
if p != nil {
prefix = p.Text()
}
g := each.AtServer.Kv.Get(groupKey)
if g != nil {
group = g.Text()
}
}
for _, r := range each.ServiceApi.ServiceRoute {
handler := r.GetHandler()
if !handler.IsNotNil() {
return fmt.Errorf("%s handler not exist near line %d", nestedApi.LinePrefix, r.Route.Method.Line())
}
handlerKey := handler.Text()
if len(group) > 0 {
handlerKey = fmt.Sprintf("%s/%s", group, handler.Text())
}
if _, ok := p.handlerMap[handlerKey]; ok {
return fmt.Errorf("%s line %d:%d duplicate handler '%s'",
nestedApi.LinePrefix, handler.Line(), handler.Column(), handlerKey)
}
routeKey := fmt.Sprintf("%s://%s", r.Route.Method.Text(), path.Join(prefix, r.Route.Path.Text()))
if _, ok := p.routeMap[routeKey]; ok {
return fmt.Errorf("%s line %d:%d duplicate route '%s'",
nestedApi.LinePrefix, r.Route.Method.Line(), r.Route.Method.Column(), r.Route.Method.Text()+" "+r.Route.Path.Text())
}
}
}
return nil
}
func (p *Parser) nestedApiCheck(mainApi, nestedApi *Api) error {
if len(nestedApi.Import) > 0 {
importToken := nestedApi.Import[0].Import
return fmt.Errorf("%s line %d:%d the nested api does not support import",
nestedApi.LinePrefix, importToken.Line(), importToken.Column())
}
if mainApi.Syntax != nil && nestedApi.Syntax != nil {
if mainApi.Syntax.Version.Text() != nestedApi.Syntax.Version.Text() {
syntaxToken := nestedApi.Syntax.Syntax
return fmt.Errorf("%s line %d:%d multiple syntax declaration, expecting syntax '%s', but found '%s'",
nestedApi.LinePrefix, syntaxToken.Line(), syntaxToken.Column(), mainApi.Syntax.Version.Text(), nestedApi.Syntax.Version.Text())
}
}
if len(mainApi.Service) > 0 {
mainService := mainApi.Service[0]
for _, service := range nestedApi.Service {
if mainService.ServiceApi.Name.Text() != service.ServiceApi.Name.Text() {
return fmt.Errorf("%s multiple service name declaration, expecting service name '%s', but found '%s'",
nestedApi.LinePrefix, mainService.ServiceApi.Name.Text(), service.ServiceApi.Name.Text())
}
}
}
return nil
}
func (p *Parser) memberFill(apiList []*Api) *Api {
var root Api
for index, each := range apiList {
if index == 0 {
root.Syntax = each.Syntax
root.Info = each.Info
root.Import = each.Import
}
root.Type = append(root.Type, each.Type...)
root.Service = append(root.Service, each.Service...)
}
return &root
}
// checkTypeDeclaration checks whether a struct type has been declared in context
func (p *Parser) checkTypeDeclaration(apiList []*Api) error {
types := make(map[string]TypeExpr)
for _, root := range apiList {
for _, each := range root.Type {
types[each.NameExpr().Text()] = each
}
}
for _, apiItem := range apiList {
linePrefix := apiItem.LinePrefix
err := p.checkTypes(apiItem, linePrefix, types)
if err != nil {
return err
}
err = p.checkServices(apiItem, types, linePrefix)
if err != nil {
return err
}
}
return nil
}
func (p *Parser) checkServices(apiItem *Api, types map[string]TypeExpr, linePrefix string) error {
for _, service := range apiItem.Service {
for _, each := range service.ServiceApi.ServiceRoute {
route := each.Route
err := p.checkRequestBody(route, types, linePrefix)
if err != nil {
return err
}
if route.Reply != nil && route.Reply.Name.IsNotNil() && route.Reply.Name.Expr().IsNotNil() {
reply := route.Reply.Name
var structName string
switch tp := reply.(type) {
case *Literal:
structName = tp.Literal.Text()
case *Array:
switch innerTp := tp.Literal.(type) {
case *Literal:
structName = innerTp.Literal.Text()
case *Pointer:
structName = innerTp.Name.Text()
}
}
if api.IsBasicType(structName) {
continue
}
_, ok := types[structName]
if !ok {
return fmt.Errorf("%s line %d:%d can not find declaration '%s' in context",
linePrefix, route.Reply.Name.Expr().Line(), route.Reply.Name.Expr().Column(), structName)
}
}
}
}
return nil
}
func (p *Parser) checkRequestBody(route *Route, types map[string]TypeExpr, linePrefix string) error {
if route.Req != nil && route.Req.Name.IsNotNil() && route.Req.Name.Expr().IsNotNil() {
_, ok := types[route.Req.Name.Expr().Text()]
if !ok {
return fmt.Errorf("%s line %d:%d can not find declaration '%s' in context",
linePrefix, route.Req.Name.Expr().Line(), route.Req.Name.Expr().Column(), route.Req.Name.Expr().Text())
}
}
return nil
}
func (p *Parser) checkTypes(apiItem *Api, linePrefix string, types map[string]TypeExpr) error {
for _, each := range apiItem.Type {
tp, ok := each.(*TypeStruct)
if !ok {
continue
}
for _, member := range tp.Fields {
err := p.checkType(linePrefix, types, member.DataType)
if err != nil {
return err
}
}
}
return nil
}
func (p *Parser) checkType(linePrefix string, types map[string]TypeExpr, expr DataType) error {
if expr == nil {
return nil
}
switch v := expr.(type) {
case *Literal:
name := v.Literal.Text()
if api.IsBasicType(name) {
return nil
}
_, ok := types[name]
if !ok {
return fmt.Errorf("%s line %d:%d can not find declaration '%s' in context",
linePrefix, v.Literal.Line(), v.Literal.Column(), name)
}
case *Pointer:
name := v.Name.Text()
if api.IsBasicType(name) {
return nil
}
_, ok := types[name]
if !ok {
return fmt.Errorf("%s line %d:%d can not find declaration '%s' in context",
linePrefix, v.Name.Line(), v.Name.Column(), name)
}
case *Map:
return p.checkType(linePrefix, types, v.Value)
case *Array:
return p.checkType(linePrefix, types, v.Literal)
default:
return nil
}
return nil
}
func (p *Parser) readContent(filename string) (string, error) {
filename = strings.ReplaceAll(filename, `"`, "")
data, err := os.ReadFile(filename)
if err != nil {
return "", err
}
return string(data), nil
}
// SyntaxError accepts errors and panic it
func (p *Parser) SyntaxError(_ antlr.Recognizer, _ any, line, column int, msg string, _ antlr.RecognitionException) {
str := fmt.Sprintf(`%s line %d:%d %s`, p.linePrefix, line, column, msg)
if p.debug {
p.log.Error(str)
}
panic(str)
}
// WithParserDebug returns a debug ParserOption
func WithParserDebug() ParserOption {
return func(p *Parser) {
p.debug = true
}
}
// WithParserPrefix returns a prefix ParserOption
func WithParserPrefix(prefix string) ParserOption {
return func(p *Parser) {
p.linePrefix = prefix
}
}
func WithParserSkipCheckTypeDeclaration() ParserOption {
return func(p *Parser) {
p.skipCheckTypeDeclaration = true
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/importstack.go | tools/goctl/api/parser/g4/ast/importstack.go | package ast
import "errors"
// ErrImportCycleNotAllowed defines an error for circular importing
var ErrImportCycleNotAllowed = errors.New("import cycle not allowed")
// importStack a stack of import paths
type importStack []string
func (s *importStack) push(p string) error {
for _, x := range *s {
if x == p {
return ErrImportCycleNotAllowed
}
}
*s = append(*s, p)
return nil
}
func (s *importStack) pop() {
*s = (*s)[0 : len(*s)-1]
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/type.go | tools/goctl/api/parser/g4/ast/type.go | package ast
import (
"fmt"
"sort"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
)
type (
// TypeExpr describes an expression for TypeAlias and TypeStruct
TypeExpr interface {
Doc() []Expr
Format() error
Equal(v any) bool
NameExpr() Expr
}
// TypeAlias describes alias ast for api syntax
TypeAlias struct {
Name Expr
Assign Expr
DataType DataType
DocExpr []Expr
CommentExpr Expr
}
// TypeStruct describes structure ast for api syntax
TypeStruct struct {
Name Expr
Struct Expr
LBrace Expr
RBrace Expr
DocExpr []Expr
Fields []*TypeField
}
// TypeField describes field ast for api syntax
TypeField struct {
IsAnonymous bool
// Name is nil if IsAnonymous
Name Expr
DataType DataType
Tag Expr
DocExpr []Expr
CommentExpr Expr
}
// DataType describes datatype for api syntax, the default implementation expressions are
// Literal, Interface, Map, Array, Time, Pointer
DataType interface {
Expr() Expr
Equal(dt DataType) bool
Format() error
IsNotNil() bool
}
// Literal describes the basic types of golang, non-reference types,
// such as int, bool, Foo,...
Literal struct {
Literal Expr
}
// Interface describes the interface type of golang,Its fixed value is interface{}
Interface struct {
Literal Expr
}
// Map describes the map ast for api syntax
Map struct {
MapExpr Expr
Map Expr
LBrack Expr
RBrack Expr
Key Expr
Value DataType
}
// Array describes the slice ast for api syntax
Array struct {
ArrayExpr Expr
LBrack Expr
RBrack Expr
Literal DataType
}
// Time describes the time ast for api syntax
Time struct {
Literal Expr
}
// Pointer describes the pointer ast for api syntax
Pointer struct {
PointerExpr Expr
Star Expr
Name Expr
}
)
// VisitTypeSpec implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeSpec(ctx *api.TypeSpecContext) any {
if ctx.TypeLit() != nil {
return []TypeExpr{ctx.TypeLit().Accept(v).(TypeExpr)}
}
return ctx.TypeBlock().Accept(v)
}
// VisitTypeLit implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeLit(ctx *api.TypeLitContext) any {
typeLit := ctx.TypeLitBody().Accept(v)
alias, ok := typeLit.(*TypeAlias)
if ok {
return alias
}
doc := v.getDoc(ctx)
st, ok := typeLit.(*TypeStruct)
if ok {
st.DocExpr = doc
return st
}
return typeLit
}
// VisitTypeBlock implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeBlock(ctx *api.TypeBlockContext) any {
list := ctx.AllTypeBlockBody()
types := make([]TypeExpr, 0, len(list))
for _, each := range list {
types = append(types, each.Accept(v).(TypeExpr))
}
return types
}
// VisitTypeLitBody implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeLitBody(ctx *api.TypeLitBodyContext) any {
if ctx.TypeAlias() != nil {
return ctx.TypeAlias().Accept(v)
}
return ctx.TypeStruct().Accept(v)
}
// VisitTypeBlockBody implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeBlockBody(ctx *api.TypeBlockBodyContext) any {
if ctx.TypeBlockAlias() != nil {
return ctx.TypeBlockAlias().Accept(v).(*TypeAlias)
}
return ctx.TypeBlockStruct().Accept(v).(*TypeStruct)
}
// VisitTypeStruct implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeStruct(ctx *api.TypeStructContext) any {
var st TypeStruct
st.Name = v.newExprWithToken(ctx.GetStructName())
if ctx.GetStructToken() != nil {
structExpr := v.newExprWithToken(ctx.GetStructToken())
structTokenText := ctx.GetStructToken().GetText()
if structTokenText != "struct" {
v.panic(structExpr, fmt.Sprintf("expecting 'struct', found input '%s'", structTokenText))
}
if api.IsGolangKeyWord(structTokenText, "struct") {
v.panic(structExpr, fmt.Sprintf("expecting 'struct', but found golang keyword '%s'", structTokenText))
}
st.Struct = structExpr
}
st.LBrace = v.newExprWithToken(ctx.GetLbrace())
st.RBrace = v.newExprWithToken(ctx.GetRbrace())
fields := ctx.AllField()
for _, each := range fields {
f := each.Accept(v)
if f == nil {
continue
}
st.Fields = append(st.Fields, f.(*TypeField))
}
return &st
}
// VisitTypeBlockStruct implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeBlockStruct(ctx *api.TypeBlockStructContext) any {
var st TypeStruct
st.Name = v.newExprWithToken(ctx.GetStructName())
if ctx.GetStructToken() != nil {
structExpr := v.newExprWithToken(ctx.GetStructToken())
structTokenText := ctx.GetStructToken().GetText()
if structTokenText != "struct" {
v.panic(structExpr, fmt.Sprintf("expecting 'struct', found input '%s'", structTokenText))
}
if api.IsGolangKeyWord(structTokenText, "struct") {
v.panic(structExpr, fmt.Sprintf("expecting 'struct', but found golang keyword '%s'", structTokenText))
}
st.Struct = structExpr
}
st.DocExpr = v.getDoc(ctx)
st.LBrace = v.newExprWithToken(ctx.GetLbrace())
st.RBrace = v.newExprWithToken(ctx.GetRbrace())
fields := ctx.AllField()
for _, each := range fields {
f := each.Accept(v)
if f == nil {
continue
}
st.Fields = append(st.Fields, f.(*TypeField))
}
return &st
}
// VisitTypeBlockAlias implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeBlockAlias(ctx *api.TypeBlockAliasContext) any {
var alias TypeAlias
alias.Name = v.newExprWithToken(ctx.GetAlias())
alias.Assign = v.newExprWithToken(ctx.GetAssign())
alias.DataType = ctx.DataType().Accept(v).(DataType)
alias.DocExpr = v.getDoc(ctx)
alias.CommentExpr = v.getComment(ctx)
// todo: reopen if necessary
v.panic(alias.Name, "unsupported alias")
return &alias
}
// VisitTypeAlias implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitTypeAlias(ctx *api.TypeAliasContext) any {
var alias TypeAlias
alias.Name = v.newExprWithToken(ctx.GetAlias())
alias.Assign = v.newExprWithToken(ctx.GetAssign())
alias.DataType = ctx.DataType().Accept(v).(DataType)
alias.DocExpr = v.getDoc(ctx)
alias.CommentExpr = v.getComment(ctx)
// todo: reopen if necessary
v.panic(alias.Name, "unsupported alias")
return &alias
}
// VisitField implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitField(ctx *api.FieldContext) any {
iAnonymousFiled := ctx.AnonymousFiled()
iNormalFieldContext := ctx.NormalField()
if iAnonymousFiled != nil {
return iAnonymousFiled.Accept(v).(*TypeField)
}
if iNormalFieldContext != nil {
return iNormalFieldContext.Accept(v).(*TypeField)
}
return nil
}
// VisitNormalField implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitNormalField(ctx *api.NormalFieldContext) any {
var field TypeField
field.Name = v.newExprWithToken(ctx.GetFieldName())
iDataTypeContext := ctx.DataType()
if iDataTypeContext != nil {
field.DataType = iDataTypeContext.Accept(v).(DataType)
field.CommentExpr = v.getComment(ctx)
}
if ctx.GetTag() != nil {
tagText := ctx.GetTag().GetText()
tagExpr := v.newExprWithToken(ctx.GetTag())
if !api.MatchTag(tagText) {
v.panic(tagExpr, fmt.Sprintf("mismatched tag, found input '%s'", tagText))
}
field.Tag = tagExpr
field.CommentExpr = v.getComment(ctx)
}
field.DocExpr = v.getDoc(ctx)
return &field
}
// VisitAnonymousFiled implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitAnonymousFiled(ctx *api.AnonymousFiledContext) any {
start := ctx.GetStart()
stop := ctx.GetStop()
var field TypeField
field.IsAnonymous = true
if ctx.GetStar() != nil {
nameExpr := v.newExprWithTerminalNode(ctx.ID())
field.DataType = &Pointer{
PointerExpr: v.newExprWithText(ctx.GetStar().GetText()+ctx.ID().GetText(), start.GetLine(), start.GetColumn(), start.GetStart(), stop.GetStop()),
Star: v.newExprWithToken(ctx.GetStar()),
Name: nameExpr,
}
} else {
nameExpr := v.newExprWithTerminalNode(ctx.ID())
field.DataType = &Literal{Literal: nameExpr}
}
field.DocExpr = v.getDoc(ctx)
field.CommentExpr = v.getComment(ctx)
return &field
}
// VisitDataType implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitDataType(ctx *api.DataTypeContext) any {
if ctx.ID() != nil {
idExpr := v.newExprWithTerminalNode(ctx.ID())
return &Literal{Literal: idExpr}
}
if ctx.MapType() != nil {
t := ctx.MapType().Accept(v)
return t
}
if ctx.ArrayType() != nil {
return ctx.ArrayType().Accept(v)
}
if ctx.GetInter() != nil {
return &Interface{Literal: v.newExprWithToken(ctx.GetInter())}
}
if ctx.GetTime() != nil {
// todo: reopen if it is necessary
timeExpr := v.newExprWithToken(ctx.GetTime())
v.panic(timeExpr, "unsupported time.Time")
return &Time{Literal: timeExpr}
}
if ctx.PointerType() != nil {
return ctx.PointerType().Accept(v)
}
return ctx.TypeStruct().Accept(v)
}
// VisitPointerType implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitPointerType(ctx *api.PointerTypeContext) any {
nameExpr := v.newExprWithTerminalNode(ctx.ID())
return &Pointer{
PointerExpr: v.newExprWithText(ctx.GetText(), ctx.GetStar().GetLine(), ctx.GetStar().GetColumn(), ctx.GetStar().GetStart(), ctx.ID().GetSymbol().GetStop()),
Star: v.newExprWithToken(ctx.GetStar()),
Name: nameExpr,
}
}
// VisitMapType implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitMapType(ctx *api.MapTypeContext) any {
return &Map{
MapExpr: v.newExprWithText(ctx.GetText(), ctx.GetMapToken().GetLine(), ctx.GetMapToken().GetColumn(),
ctx.GetMapToken().GetStart(), ctx.GetValue().GetStop().GetStop()),
Map: v.newExprWithToken(ctx.GetMapToken()),
LBrack: v.newExprWithToken(ctx.GetLbrack()),
RBrack: v.newExprWithToken(ctx.GetRbrack()),
Key: v.newExprWithToken(ctx.GetKey()),
Value: ctx.GetValue().Accept(v).(DataType),
}
}
// VisitArrayType implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitArrayType(ctx *api.ArrayTypeContext) any {
return &Array{
ArrayExpr: v.newExprWithText(ctx.GetText(), ctx.GetLbrack().GetLine(), ctx.GetLbrack().GetColumn(), ctx.GetLbrack().GetStart(), ctx.DataType().GetStop().GetStop()),
LBrack: v.newExprWithToken(ctx.GetLbrack()),
RBrack: v.newExprWithToken(ctx.GetRbrack()),
Literal: ctx.DataType().Accept(v).(DataType),
}
}
// NameExpr returns the expression string of TypeAlias
func (a *TypeAlias) NameExpr() Expr {
return a.Name
}
// Doc returns the document of TypeAlias, like // some text
func (a *TypeAlias) Doc() []Expr {
return a.DocExpr
}
// Comment returns the comment of TypeAlias, like // some text
func (a *TypeAlias) Comment() Expr {
return a.CommentExpr
}
// Format provides a formatter for api command, now nothing to do
func (a *TypeAlias) Format() error {
return nil
}
// Equal compares whether the element literals in two TypeAlias are equal
func (a *TypeAlias) Equal(v any) bool {
if v == nil {
return false
}
alias := v.(*TypeAlias)
if !a.Name.Equal(alias.Name) {
return false
}
if !a.Assign.Equal(alias.Assign) {
return false
}
if !a.DataType.Equal(alias.DataType) {
return false
}
return EqualDoc(a, alias)
}
// Expr returns the expression string of Literal
func (l *Literal) Expr() Expr {
return l.Literal
}
// Format provides a formatter for api command, now nothing to do
func (l *Literal) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Literal are equal
func (l *Literal) Equal(dt DataType) bool {
if dt == nil {
return false
}
v, ok := dt.(*Literal)
if !ok {
return false
}
return l.Literal.Equal(v.Literal)
}
// IsNotNil returns whether the instance is nil or not
func (l *Literal) IsNotNil() bool {
return l != nil
}
// Expr returns the expression string of Interface
func (i *Interface) Expr() Expr {
return i.Literal
}
// Format provides a formatter for api command, now nothing to do
func (i *Interface) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Interface are equal
func (i *Interface) Equal(dt DataType) bool {
if dt == nil {
return false
}
v, ok := dt.(*Interface)
if !ok {
return false
}
return i.Literal.Equal(v.Literal)
}
// IsNotNil returns whether the instance is nil or not
func (i *Interface) IsNotNil() bool {
return i != nil
}
// Expr returns the expression string of Map
func (m *Map) Expr() Expr {
return m.MapExpr
}
// Format provides a formatter for api command, now nothing to do
func (m *Map) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Map are equal
func (m *Map) Equal(dt DataType) bool {
if dt == nil {
return false
}
v, ok := dt.(*Map)
if !ok {
return false
}
if !m.Key.Equal(v.Key) {
return false
}
if !m.Value.Equal(v.Value) {
return false
}
if !m.MapExpr.Equal(v.MapExpr) {
return false
}
return m.Map.Equal(v.Map)
}
// IsNotNil returns whether the instance is nil or not
func (m *Map) IsNotNil() bool {
return m != nil
}
// Expr returns the expression string of Array
func (a *Array) Expr() Expr {
return a.ArrayExpr
}
// Format provides a formatter for api command, now nothing to do
func (a *Array) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Array are equal
func (a *Array) Equal(dt DataType) bool {
if dt == nil {
return false
}
v, ok := dt.(*Array)
if !ok {
return false
}
if !a.ArrayExpr.Equal(v.ArrayExpr) {
return false
}
return a.Literal.Equal(v.Literal)
}
// IsNotNil returns whether the instance is nil or not
func (a *Array) IsNotNil() bool {
return a != nil
}
// Expr returns the expression string of Time
func (t *Time) Expr() Expr {
return t.Literal
}
// Format provides a formatter for api command, now nothing to do
func (t *Time) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two Time are equal
func (t *Time) Equal(dt DataType) bool {
if dt == nil {
return false
}
v, ok := dt.(*Time)
if !ok {
return false
}
return t.Literal.Equal(v.Literal)
}
// IsNotNil returns whether the instance is nil or not
func (t *Time) IsNotNil() bool {
return t != nil
}
// Expr returns the expression string of Pointer
func (p *Pointer) Expr() Expr {
return p.PointerExpr
}
// Format provides a formatter for api command, now nothing to do
func (p *Pointer) Format() error {
return nil
}
// Equal compares whether the element literals in two Pointer are equal
func (p *Pointer) Equal(dt DataType) bool {
if dt == nil {
return false
}
v, ok := dt.(*Pointer)
if !ok {
return false
}
if !p.PointerExpr.Equal(v.PointerExpr) {
return false
}
if !p.Star.Equal(v.Star) {
return false
}
return p.Name.Equal(v.Name)
}
// IsNotNil returns whether the instance is nil or not
func (p *Pointer) IsNotNil() bool {
return p != nil
}
// NameExpr returns the expression string of TypeStruct
func (s *TypeStruct) NameExpr() Expr {
return s.Name
}
// Equal compares whether the element literals in two TypeStruct are equal
func (s *TypeStruct) Equal(dt any) bool {
if dt == nil {
return false
}
v, ok := dt.(*TypeStruct)
if !ok {
return false
}
if !s.Name.Equal(v.Name) {
return false
}
var expectDoc, actualDoc []Expr
expectDoc = append(expectDoc, s.DocExpr...)
actualDoc = append(actualDoc, v.DocExpr...)
sort.Slice(expectDoc, func(i, j int) bool {
return expectDoc[i].Line() < expectDoc[j].Line()
})
for index, each := range actualDoc {
if !each.Equal(actualDoc[index]) {
return false
}
}
if s.Struct != nil {
if s.Struct != nil {
if !s.Struct.Equal(v.Struct) {
return false
}
}
}
if len(s.Fields) != len(v.Fields) {
return false
}
var expected, actual []*TypeField
expected = append(expected, s.Fields...)
actual = append(actual, v.Fields...)
sort.Slice(expected, func(i, j int) bool {
return expected[i].DataType.Expr().Line() < expected[j].DataType.Expr().Line()
})
sort.Slice(actual, func(i, j int) bool {
return actual[i].DataType.Expr().Line() < actual[j].DataType.Expr().Line()
})
for index, each := range expected {
ac := actual[index]
if !each.Equal(ac) {
return false
}
}
return true
}
// Doc returns the document of TypeStruct, like // some text
func (s *TypeStruct) Doc() []Expr {
return s.DocExpr
}
// Format provides a formatter for api command, now nothing to do
func (s *TypeStruct) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two TypeField are equal
func (t *TypeField) Equal(v any) bool {
if v == nil {
return false
}
f, ok := v.(*TypeField)
if !ok {
return false
}
if t.IsAnonymous != f.IsAnonymous {
return false
}
if !t.DataType.Equal(f.DataType) {
return false
}
if !t.IsAnonymous {
if !t.Name.Equal(f.Name) {
return false
}
if t.Tag != nil {
if !t.Tag.Equal(f.Tag) {
return false
}
}
}
return EqualDoc(t, f)
}
// Doc returns the document of TypeField, like // some text
func (t *TypeField) Doc() []Expr {
return t.DocExpr
}
// Comment returns the comment of TypeField, like // some text
func (t *TypeField) Comment() Expr {
return t.CommentExpr
}
// Format provides a formatter for api command, now nothing to do
func (t *TypeField) Format() error {
// todo
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/apiparser_test.go | tools/goctl/api/parser/g4/ast/apiparser_test.go | package ast
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
func Test_ImportCycle(t *testing.T) {
const (
mainFilename = "main.api"
subAFilename = "a.api"
subBFilename = "b.api"
mainSrc = `import "./a.api"`
subASrc = `import "./b.api"`
subBSrc = `import "./a.api"`
)
var err error
dir := pathx.MustTempDir()
defer os.RemoveAll(dir)
mainPath := filepath.Join(dir, mainFilename)
err = os.WriteFile(mainPath, []byte(mainSrc), 0o777)
require.NoError(t, err)
subAPath := filepath.Join(dir, subAFilename)
err = os.WriteFile(subAPath, []byte(subASrc), 0o777)
require.NoError(t, err)
subBPath := filepath.Join(dir, subBFilename)
err = os.WriteFile(subBPath, []byte(subBSrc), 0o777)
require.NoError(t, err)
_, err = NewParser().Parse(mainPath)
assert.ErrorIs(t, err, ErrImportCycleNotAllowed)
}
func Test_MultiImportedShouldAllowed(t *testing.T) {
const (
mainFilename = "main.api"
subAFilename = "a.api"
subBFilename = "b.api"
mainSrc = "import \"./b.api\"\n" +
"import \"./a.api\"\n" +
"type Main { b B `json:\"b\"`}"
subASrc = "import \"./b.api\"\n" +
"type A { b B `json:\"b\"`}\n"
subBSrc = `type B{}`
)
var err error
dir := pathx.MustTempDir()
defer os.RemoveAll(dir)
mainPath := filepath.Join(dir, mainFilename)
err = os.WriteFile(mainPath, []byte(mainSrc), 0o777)
require.NoError(t, err)
subAPath := filepath.Join(dir, subAFilename)
err = os.WriteFile(subAPath, []byte(subASrc), 0o777)
require.NoError(t, err)
subBPath := filepath.Join(dir, subBFilename)
err = os.WriteFile(subBPath, []byte(subBSrc), 0o777)
require.NoError(t, err)
_, err = NewParser().Parse(mainPath)
assert.NoError(t, err)
}
func Test_RedundantDeclarationShouldNotBeAllowed(t *testing.T) {
const (
mainFilename = "main.api"
subAFilename = "a.api"
subBFilename = "b.api"
mainSrc = "import \"./a.api\"\n" +
"import \"./b.api\"\n"
subASrc = `import "./b.api"
type A{}`
subBSrc = `type A{}`
)
var err error
dir := pathx.MustTempDir()
defer os.RemoveAll(dir)
mainPath := filepath.Join(dir, mainFilename)
err = os.WriteFile(mainPath, []byte(mainSrc), 0o777)
require.NoError(t, err)
subAPath := filepath.Join(dir, subAFilename)
err = os.WriteFile(subAPath, []byte(subASrc), 0o777)
require.NoError(t, err)
subBPath := filepath.Join(dir, subBFilename)
err = os.WriteFile(subBPath, []byte(subBSrc), 0o777)
require.NoError(t, err)
_, err = NewParser().Parse(mainPath)
assert.Error(t, err)
assert.Contains(t, err.Error(), "duplicate type declaration")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/ast.go | tools/goctl/api/parser/g4/ast/ast.go | package ast
import (
"fmt"
"sort"
"strings"
"github.com/zeromicro/antlr"
"github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
)
type (
// TokenStream defines a token
TokenStream interface {
GetStart() antlr.Token
GetStop() antlr.Token
GetParser() antlr.Parser
}
// ApiVisitor wraps api.BaseApiParserVisitor to call methods which has prefix Visit to
// visit node from the api syntax
ApiVisitor struct {
*api.BaseApiParserVisitor
debug bool
log console.Console
prefix string
infoFlag bool
}
// VisitorOption defines a function with argument ApiVisitor
VisitorOption func(v *ApiVisitor)
// Spec describes api spec
Spec interface {
Doc() []Expr
Comment() Expr
Format() error
Equal(v any) bool
}
// Expr describes ast expression
Expr interface {
Prefix() string
Line() int
Column() int
Text() string
SetText(text string)
Start() int
Stop() int
Equal(expr Expr) bool
IsNotNil() bool
}
)
// NewApiVisitor creates an instance for ApiVisitor
func NewApiVisitor(options ...VisitorOption) *ApiVisitor {
v := &ApiVisitor{
log: console.NewColorConsole(),
}
for _, opt := range options {
opt(v)
}
return v
}
func (v *ApiVisitor) panic(expr Expr, msg string) {
errString := fmt.Sprintf("%s line %d:%d %s", v.prefix, expr.Line(), expr.Column(), msg)
if v.debug {
fmt.Println(errString)
}
panic(errString)
}
// WithVisitorPrefix returns a VisitorOption wrap with specified prefix
func WithVisitorPrefix(prefix string) VisitorOption {
return func(v *ApiVisitor) {
v.prefix = prefix
}
}
// WithVisitorDebug returns a debug VisitorOption
func WithVisitorDebug() VisitorOption {
return func(v *ApiVisitor) {
v.debug = true
}
}
type defaultExpr struct {
prefix, v string
line, column int
start, stop int
}
// NewTextExpr creates a default instance for Expr
func NewTextExpr(v string) *defaultExpr {
return &defaultExpr{
v: v,
}
}
func (v *ApiVisitor) newExprWithTerminalNode(node antlr.TerminalNode) *defaultExpr {
if node == nil {
return nil
}
token := node.GetSymbol()
return v.newExprWithToken(token)
}
func (v *ApiVisitor) newExprWithToken(token antlr.Token) *defaultExpr {
if token == nil {
return nil
}
instance := &defaultExpr{}
instance.prefix = v.prefix
instance.v = token.GetText()
instance.line = token.GetLine()
instance.column = token.GetColumn()
instance.start = token.GetStart()
instance.stop = token.GetStop()
return instance
}
func (v *ApiVisitor) newExprWithText(text string, line, column, start, stop int) *defaultExpr {
instance := &defaultExpr{}
instance.prefix = v.prefix
instance.v = text
instance.line = line
instance.column = column
instance.start = start
instance.stop = stop
return instance
}
func (e *defaultExpr) Prefix() string {
if e == nil {
return ""
}
return e.prefix
}
func (e *defaultExpr) Line() int {
if e == nil {
return 0
}
return e.line
}
func (e *defaultExpr) Column() int {
if e == nil {
return 0
}
return e.column
}
func (e *defaultExpr) Text() string {
if e == nil {
return ""
}
return e.v
}
func (e *defaultExpr) SetText(text string) {
if e == nil {
return
}
e.v = text
}
func (e *defaultExpr) Start() int {
if e == nil {
return 0
}
return e.start
}
func (e *defaultExpr) Stop() int {
if e == nil {
return 0
}
return e.stop
}
func (e *defaultExpr) Equal(expr Expr) bool {
if e == nil {
return expr == nil
}
if expr == nil {
return false
}
return e.v == expr.Text()
}
func (e *defaultExpr) IsNotNil() bool {
return e != nil
}
// EqualDoc compares whether the element literals in two Spec are equal
func EqualDoc(spec1, spec2 Spec) bool {
if spec1 == nil {
return spec2 == nil
}
if spec2 == nil {
return false
}
var expectDoc, actualDoc []Expr
expectDoc = append(expectDoc, spec2.Doc()...)
actualDoc = append(actualDoc, spec1.Doc()...)
sort.Slice(expectDoc, func(i, j int) bool {
return expectDoc[i].Line() < expectDoc[j].Line()
})
for index, each := range actualDoc {
if !each.Equal(actualDoc[index]) {
return false
}
}
if spec1.Comment() != nil {
if spec2.Comment() == nil {
return false
}
if !spec1.Comment().Equal(spec2.Comment()) {
return false
}
} else {
if spec2.Comment() != nil {
return false
}
}
return true
}
func (v *ApiVisitor) getDoc(t TokenStream) []Expr {
return v.getHiddenTokensToLeft(t, api.COMMENTS, false)
}
func (v *ApiVisitor) getComment(t TokenStream) Expr {
list := v.getHiddenTokensToRight(t, api.COMMENTS)
if len(list) == 0 {
return nil
}
commentExpr := list[0]
stop := t.GetStop()
text := stop.GetText()
nlCount := strings.Count(text, "\n")
if commentExpr.Line() != stop.GetLine()+nlCount {
return nil
}
return commentExpr
}
func (v *ApiVisitor) getHiddenTokensToLeft(t TokenStream, channel int, containsCommentOfDefaultChannel bool) []Expr {
ct := t.GetParser().GetTokenStream().(*antlr.CommonTokenStream)
tokens := ct.GetHiddenTokensToLeft(t.GetStart().GetTokenIndex(), channel)
var list []Expr
for _, each := range tokens {
if !containsCommentOfDefaultChannel {
index := each.GetTokenIndex() - 1
if index > 0 {
allTokens := ct.GetAllTokens()
flag := false
for i := index; i >= 0; i-- {
tk := allTokens[i]
if tk.GetChannel() == antlr.LexerDefaultTokenChannel {
if tk.GetLine() == each.GetLine() {
flag = true
break
}
}
}
if flag {
continue
}
}
}
list = append(list, v.newExprWithToken(each))
}
return list
}
func (v *ApiVisitor) getHiddenTokensToRight(t TokenStream, channel int) []Expr {
ct := t.GetParser().GetTokenStream().(*antlr.CommonTokenStream)
tokens := ct.GetHiddenTokensToRight(t.GetStop().GetTokenIndex(), channel)
var list []Expr
for _, each := range tokens {
list = append(list, v.newExprWithToken(each))
}
return list
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/info.go | tools/goctl/api/parser/g4/ast/info.go | package ast
import "github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
// InfoExpr defines info syntax for api
type InfoExpr struct {
Info Expr
Lp Expr
Rp Expr
Kvs []*KvExpr
}
// VisitInfoSpec implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitInfoSpec(ctx *api.InfoSpecContext) any {
var expr InfoExpr
expr.Info = v.newExprWithToken(ctx.GetInfoToken())
expr.Lp = v.newExprWithToken(ctx.GetLp())
expr.Rp = v.newExprWithToken(ctx.GetRp())
list := ctx.AllKvLit()
for _, each := range list {
kvExpr := each.Accept(v).(*KvExpr)
expr.Kvs = append(expr.Kvs, kvExpr)
}
if v.infoFlag {
v.panic(expr.Info, "duplicate declaration 'info'")
}
return &expr
}
// Format provides a formatter for api command, now nothing to do
func (i *InfoExpr) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two InfoExpr are equal
func (i *InfoExpr) Equal(v any) bool {
if v == nil {
return false
}
info, ok := v.(*InfoExpr)
if !ok {
return false
}
if !i.Info.Equal(info.Info) {
return false
}
var expected, actual []*KvExpr
expected = append(expected, i.Kvs...)
actual = append(actual, info.Kvs...)
if len(expected) != len(actual) {
return false
}
for index, each := range expected {
ac := actual[index]
if !each.Equal(ac) {
return false
}
}
return true
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/parser/g4/ast/import.go | tools/goctl/api/parser/g4/ast/import.go | package ast
import "github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
// ImportExpr defines import syntax for api
type ImportExpr struct {
Import Expr
Value Expr
DocExpr []Expr
CommentExpr Expr
}
// VisitImportSpec implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitImportSpec(ctx *api.ImportSpecContext) any {
var list []*ImportExpr
if ctx.ImportLit() != nil {
lits := ctx.ImportLit().Accept(v).([]*ImportExpr)
list = append(list, lits...)
}
if ctx.ImportBlock() != nil {
blocks := ctx.ImportBlock().Accept(v).([]*ImportExpr)
list = append(list, blocks...)
}
return list
}
// VisitImportLit implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitImportLit(ctx *api.ImportLitContext) any {
importToken := v.newExprWithToken(ctx.GetImportToken())
valueExpr := ctx.ImportValue().Accept(v).(Expr)
return []*ImportExpr{
{
Import: importToken,
Value: valueExpr,
DocExpr: v.getDoc(ctx),
CommentExpr: v.getComment(ctx),
},
}
}
// VisitImportBlock implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitImportBlock(ctx *api.ImportBlockContext) any {
importToken := v.newExprWithToken(ctx.GetImportToken())
values := ctx.AllImportBlockValue()
var list []*ImportExpr
for _, value := range values {
importExpr := value.Accept(v).(*ImportExpr)
importExpr.Import = importToken
list = append(list, importExpr)
}
return list
}
// VisitImportBlockValue implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitImportBlockValue(ctx *api.ImportBlockValueContext) any {
value := ctx.ImportValue().Accept(v).(Expr)
return &ImportExpr{
Value: value,
DocExpr: v.getDoc(ctx),
CommentExpr: v.getComment(ctx),
}
}
// VisitImportValue implements from api.BaseApiParserVisitor
func (v *ApiVisitor) VisitImportValue(ctx *api.ImportValueContext) any {
return v.newExprWithTerminalNode(ctx.STRING())
}
// Format provides a formatter for api command, now nothing to do
func (i *ImportExpr) Format() error {
// todo
return nil
}
// Equal compares whether the element literals in two ImportExpr are equal
func (i *ImportExpr) Equal(v any) bool {
if v == nil {
return false
}
imp, ok := v.(*ImportExpr)
if !ok {
return false
}
if !EqualDoc(i, imp) {
return false
}
return i.Import.Equal(imp.Import) && i.Value.Equal(imp.Value)
}
// Doc returns the document of ImportExpr, like // some text
func (i *ImportExpr) Doc() []Expr {
return i.DocExpr
}
// Comment returns the comment of ImportExpr, like // some text
func (i *ImportExpr) Comment() Expr {
return i.CommentExpr
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/validate/validate.go | tools/goctl/api/validate/validate.go | package validate
import (
"errors"
"fmt"
"github.com/gookit/color"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/api/parser"
)
// VarStringAPI describes an API.
var VarStringAPI string
// GoValidateApi verifies whether the api has a syntax error
func GoValidateApi(_ *cobra.Command, _ []string) error {
apiFile := VarStringAPI
if len(apiFile) == 0 {
return errors.New("missing -api")
}
spec, err := parser.Parse(apiFile)
if err != nil {
return err
}
err = spec.Validate()
if err == nil {
fmt.Println(color.Green.Render("api format ok"))
}
return err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/hello.go | tools/goctl/example/rpc/hello/hello.go | package main
import (
"flag"
"fmt"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/config"
greetServer "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/server/greet"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/pb/hello"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/hello.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
hello.RegisterGreetServer(grpcServer, greetServer.NewGreetServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/pb/hello/hello.pb.go | tools/goctl/example/rpc/hello/pb/hello/hello.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.0
// protoc v3.19.4
// source: hello.proto
package hello
import (
reflect "reflect"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type HelloReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
In string `protobuf:"bytes,1,opt,name=in,proto3" json:"in,omitempty"`
}
func (x *HelloReq) Reset() {
*x = HelloReq{}
if protoimpl.UnsafeEnabled {
mi := &file_hello_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *HelloReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HelloReq) ProtoMessage() {}
func (x *HelloReq) ProtoReflect() protoreflect.Message {
mi := &file_hello_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HelloReq.ProtoReflect.Descriptor instead.
func (*HelloReq) Descriptor() ([]byte, []int) {
return file_hello_proto_rawDescGZIP(), []int{0}
}
func (x *HelloReq) GetIn() string {
if x != nil {
return x.In
}
return ""
}
type HelloResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Msg string `protobuf:"bytes,1,opt,name=msg,proto3" json:"msg,omitempty"`
}
func (x *HelloResp) Reset() {
*x = HelloResp{}
if protoimpl.UnsafeEnabled {
mi := &file_hello_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *HelloResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HelloResp) ProtoMessage() {}
func (x *HelloResp) ProtoReflect() protoreflect.Message {
mi := &file_hello_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HelloResp.ProtoReflect.Descriptor instead.
func (*HelloResp) Descriptor() ([]byte, []int) {
return file_hello_proto_rawDescGZIP(), []int{1}
}
func (x *HelloResp) GetMsg() string {
if x != nil {
return x.Msg
}
return ""
}
var File_hello_proto protoreflect.FileDescriptor
var file_hello_proto_rawDesc = []byte{
0x0a, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x68,
0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x1a, 0x0a, 0x08, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71,
0x12, 0x0e, 0x0a, 0x02, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x6e,
0x22, 0x1d, 0x0a, 0x09, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x12, 0x10, 0x0a,
0x03, 0x6d, 0x73, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x32,
0x36, 0x0a, 0x05, 0x47, 0x72, 0x65, 0x65, 0x74, 0x12, 0x2d, 0x0a, 0x08, 0x53, 0x61, 0x79, 0x48,
0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x0f, 0x2e, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x48, 0x65, 0x6c,
0x6c, 0x6f, 0x52, 0x65, 0x71, 0x1a, 0x10, 0x2e, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x48, 0x65,
0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x42, 0x09, 0x5a, 0x07, 0x2e, 0x2f, 0x68, 0x65, 0x6c,
0x6c, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_hello_proto_rawDescOnce sync.Once
file_hello_proto_rawDescData = file_hello_proto_rawDesc
)
func file_hello_proto_rawDescGZIP() []byte {
file_hello_proto_rawDescOnce.Do(func() {
file_hello_proto_rawDescData = protoimpl.X.CompressGZIP(file_hello_proto_rawDescData)
})
return file_hello_proto_rawDescData
}
var file_hello_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_hello_proto_goTypes = []any{
(*HelloReq)(nil), // 0: hello.HelloReq
(*HelloResp)(nil), // 1: hello.HelloResp
}
var file_hello_proto_depIdxs = []int32{
0, // 0: hello.Greet.SayHello:input_type -> hello.HelloReq
1, // 1: hello.Greet.SayHello:output_type -> hello.HelloResp
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_hello_proto_init() }
func file_hello_proto_init() {
if File_hello_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_hello_proto_msgTypes[0].Exporter = func(v any, i int) any {
switch v := v.(*HelloReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_hello_proto_msgTypes[1].Exporter = func(v any, i int) any {
switch v := v.(*HelloResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_hello_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_hello_proto_goTypes,
DependencyIndexes: file_hello_proto_depIdxs,
MessageInfos: file_hello_proto_msgTypes,
}.Build()
File_hello_proto = out.File
file_hello_proto_rawDesc = nil
file_hello_proto_goTypes = nil
file_hello_proto_depIdxs = nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/pb/hello/hello_grpc.pb.go | tools/goctl/example/rpc/hello/pb/hello/hello_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.19.4
// source: hello.proto
package hello
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// GreetClient is the client API for Greet service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GreetClient interface {
SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error)
}
type greetClient struct {
cc grpc.ClientConnInterface
}
func NewGreetClient(cc grpc.ClientConnInterface) GreetClient {
return &greetClient{cc}
}
func (c *greetClient) SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error) {
out := new(HelloResp)
err := c.cc.Invoke(ctx, "/hello.Greet/SayHello", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// GreetServer is the server API for Greet service.
// All implementations must embed UnimplementedGreetServer
// for forward compatibility
type GreetServer interface {
SayHello(context.Context, *HelloReq) (*HelloResp, error)
mustEmbedUnimplementedGreetServer()
}
// UnimplementedGreetServer must be embedded to have forward compatible implementations.
type UnimplementedGreetServer struct {
}
func (UnimplementedGreetServer) SayHello(context.Context, *HelloReq) (*HelloResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}
func (UnimplementedGreetServer) mustEmbedUnimplementedGreetServer() {}
// UnsafeGreetServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreetServer will
// result in compilation errors.
type UnsafeGreetServer interface {
mustEmbedUnimplementedGreetServer()
}
func RegisterGreetServer(s grpc.ServiceRegistrar, srv GreetServer) {
s.RegisterService(&Greet_ServiceDesc, srv)
}
func _Greet_SayHello_Handler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(HelloReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreetServer).SayHello(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/hello.Greet/SayHello",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(GreetServer).SayHello(ctx, req.(*HelloReq))
}
return interceptor(ctx, in, info, handler)
}
// Greet_ServiceDesc is the grpc.ServiceDesc for Greet service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greet_ServiceDesc = grpc.ServiceDesc{
ServiceName: "hello.Greet",
HandlerType: (*GreetServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "SayHello",
Handler: _Greet_SayHello_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "hello.proto",
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/internal/svc/servicecontext.go | tools/goctl/example/rpc/hello/internal/svc/servicecontext.go | package svc
import "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/config"
type ServiceContext struct {
Config config.Config
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/internal/server/greet/greetserver.go | tools/goctl/example/rpc/hello/internal/server/greet/greetserver.go | // Code generated by goctl. DO NOT EDIT!
// Source: hello.proto
package server
import (
"context"
greetlogic "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/logic/greet"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/pb/hello"
)
type GreetServer struct {
svcCtx *svc.ServiceContext
hello.UnimplementedGreetServer
}
func NewGreetServer(svcCtx *svc.ServiceContext) *GreetServer {
return &GreetServer{
svcCtx: svcCtx,
}
}
func (s *GreetServer) SayHello(ctx context.Context, in *hello.HelloReq) (*hello.HelloResp, error) {
l := greetlogic.NewSayHelloLogic(ctx, s.svcCtx)
return l.SayHello(in)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/internal/config/config.go | tools/goctl/example/rpc/hello/internal/config/config.go | package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/internal/logic/greet/sayhellologic.go | tools/goctl/example/rpc/hello/internal/logic/greet/sayhellologic.go | package greetlogic
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/pb/hello"
)
type SayHelloLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSayHelloLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SayHelloLogic {
return &SayHelloLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SayHelloLogic) SayHello(in *hello.HelloReq) (*hello.HelloResp, error) {
// todo: add your logic here and delete this line
return &hello.HelloResp{}, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hello/client/greet/greet.go | tools/goctl/example/rpc/hello/client/greet/greet.go | // Code generated by goctl. DO NOT EDIT!
// Source: hello.proto
package client
import (
"context"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hello/pb/hello"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
HelloReq = hello.HelloReq
HelloResp = hello.HelloResp
Greet interface {
SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error)
}
defaultGreet struct {
cli zrpc.Client
}
)
func NewGreet(cli zrpc.Client) Greet {
return &defaultGreet{
cli: cli,
}
}
func (m *defaultGreet) SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error) {
client := hello.NewGreetClient(m.cli.Conn())
return client.SayHello(ctx, in, opts...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/hi.go | tools/goctl/example/rpc/hi/hi.go | package main
import (
"flag"
"fmt"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/config"
eventServer "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/server/event"
greetServer "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/server/greet"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/hi.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
hi.RegisterGreetServer(grpcServer, greetServer.NewGreetServer(ctx))
hi.RegisterEventServer(grpcServer, eventServer.NewEventServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/pb/hi/hi_grpc.pb.go | tools/goctl/example/rpc/hi/pb/hi/hi_grpc.pb.go | // Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.19.4
// source: hi.proto
package hi
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// GreetClient is the client API for Greet service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GreetClient interface {
SayHi(ctx context.Context, in *HiReq, opts ...grpc.CallOption) (*HiResp, error)
SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error)
}
type greetClient struct {
cc grpc.ClientConnInterface
}
func NewGreetClient(cc grpc.ClientConnInterface) GreetClient {
return &greetClient{cc}
}
func (c *greetClient) SayHi(ctx context.Context, in *HiReq, opts ...grpc.CallOption) (*HiResp, error) {
out := new(HiResp)
err := c.cc.Invoke(ctx, "/hi.Greet/SayHi", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greetClient) SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error) {
out := new(HelloResp)
err := c.cc.Invoke(ctx, "/hi.Greet/SayHello", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// GreetServer is the server API for Greet service.
// All implementations must embed UnimplementedGreetServer
// for forward compatibility
type GreetServer interface {
SayHi(context.Context, *HiReq) (*HiResp, error)
SayHello(context.Context, *HelloReq) (*HelloResp, error)
mustEmbedUnimplementedGreetServer()
}
// UnimplementedGreetServer must be embedded to have forward compatible implementations.
type UnimplementedGreetServer struct {
}
func (UnimplementedGreetServer) SayHi(context.Context, *HiReq) (*HiResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHi not implemented")
}
func (UnimplementedGreetServer) SayHello(context.Context, *HelloReq) (*HelloResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}
func (UnimplementedGreetServer) mustEmbedUnimplementedGreetServer() {}
// UnsafeGreetServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreetServer will
// result in compilation errors.
type UnsafeGreetServer interface {
mustEmbedUnimplementedGreetServer()
}
func RegisterGreetServer(s grpc.ServiceRegistrar, srv GreetServer) {
s.RegisterService(&Greet_ServiceDesc, srv)
}
func _Greet_SayHi_Handler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(HiReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreetServer).SayHi(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/hi.Greet/SayHi",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(GreetServer).SayHi(ctx, req.(*HiReq))
}
return interceptor(ctx, in, info, handler)
}
func _Greet_SayHello_Handler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(HelloReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreetServer).SayHello(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/hi.Greet/SayHello",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(GreetServer).SayHello(ctx, req.(*HelloReq))
}
return interceptor(ctx, in, info, handler)
}
// Greet_ServiceDesc is the grpc.ServiceDesc for Greet service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greet_ServiceDesc = grpc.ServiceDesc{
ServiceName: "hi.Greet",
HandlerType: (*GreetServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "SayHi",
Handler: _Greet_SayHi_Handler,
},
{
MethodName: "SayHello",
Handler: _Greet_SayHello_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "hi.proto",
}
// EventClient is the client API for Event service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type EventClient interface {
AskQuestion(ctx context.Context, in *EventReq, opts ...grpc.CallOption) (*EventResp, error)
}
type eventClient struct {
cc grpc.ClientConnInterface
}
func NewEventClient(cc grpc.ClientConnInterface) EventClient {
return &eventClient{cc}
}
func (c *eventClient) AskQuestion(ctx context.Context, in *EventReq, opts ...grpc.CallOption) (*EventResp, error) {
out := new(EventResp)
err := c.cc.Invoke(ctx, "/hi.Event/AskQuestion", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// EventServer is the server API for Event service.
// All implementations must embed UnimplementedEventServer
// for forward compatibility
type EventServer interface {
AskQuestion(context.Context, *EventReq) (*EventResp, error)
mustEmbedUnimplementedEventServer()
}
// UnimplementedEventServer must be embedded to have forward compatible implementations.
type UnimplementedEventServer struct {
}
func (UnimplementedEventServer) AskQuestion(context.Context, *EventReq) (*EventResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method AskQuestion not implemented")
}
func (UnimplementedEventServer) mustEmbedUnimplementedEventServer() {}
// UnsafeEventServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to EventServer will
// result in compilation errors.
type UnsafeEventServer interface {
mustEmbedUnimplementedEventServer()
}
func RegisterEventServer(s grpc.ServiceRegistrar, srv EventServer) {
s.RegisterService(&Event_ServiceDesc, srv)
}
func _Event_AskQuestion_Handler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(EventReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EventServer).AskQuestion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/hi.Event/AskQuestion",
}
handler := func(ctx context.Context, req any) (any, error) {
return srv.(EventServer).AskQuestion(ctx, req.(*EventReq))
}
return interceptor(ctx, in, info, handler)
}
// Event_ServiceDesc is the grpc.ServiceDesc for Event service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Event_ServiceDesc = grpc.ServiceDesc{
ServiceName: "hi.Event",
HandlerType: (*EventServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "AskQuestion",
Handler: _Event_AskQuestion_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "hi.proto",
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/pb/hi/hi.pb.go | tools/goctl/example/rpc/hi/pb/hi/hi.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.0
// protoc v3.19.4
// source: hi.proto
package hi
import (
reflect "reflect"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type HiReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
In string `protobuf:"bytes,1,opt,name=in,proto3" json:"in,omitempty"`
}
func (x *HiReq) Reset() {
*x = HiReq{}
if protoimpl.UnsafeEnabled {
mi := &file_hi_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *HiReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HiReq) ProtoMessage() {}
func (x *HiReq) ProtoReflect() protoreflect.Message {
mi := &file_hi_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HiReq.ProtoReflect.Descriptor instead.
func (*HiReq) Descriptor() ([]byte, []int) {
return file_hi_proto_rawDescGZIP(), []int{0}
}
func (x *HiReq) GetIn() string {
if x != nil {
return x.In
}
return ""
}
type HelloReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
In string `protobuf:"bytes,1,opt,name=in,proto3" json:"in,omitempty"`
}
func (x *HelloReq) Reset() {
*x = HelloReq{}
if protoimpl.UnsafeEnabled {
mi := &file_hi_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *HelloReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HelloReq) ProtoMessage() {}
func (x *HelloReq) ProtoReflect() protoreflect.Message {
mi := &file_hi_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HelloReq.ProtoReflect.Descriptor instead.
func (*HelloReq) Descriptor() ([]byte, []int) {
return file_hi_proto_rawDescGZIP(), []int{1}
}
func (x *HelloReq) GetIn() string {
if x != nil {
return x.In
}
return ""
}
type HiResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Msg string `protobuf:"bytes,1,opt,name=msg,proto3" json:"msg,omitempty"`
}
func (x *HiResp) Reset() {
*x = HiResp{}
if protoimpl.UnsafeEnabled {
mi := &file_hi_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *HiResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HiResp) ProtoMessage() {}
func (x *HiResp) ProtoReflect() protoreflect.Message {
mi := &file_hi_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HiResp.ProtoReflect.Descriptor instead.
func (*HiResp) Descriptor() ([]byte, []int) {
return file_hi_proto_rawDescGZIP(), []int{2}
}
func (x *HiResp) GetMsg() string {
if x != nil {
return x.Msg
}
return ""
}
type HelloResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Msg string `protobuf:"bytes,1,opt,name=msg,proto3" json:"msg,omitempty"`
}
func (x *HelloResp) Reset() {
*x = HelloResp{}
if protoimpl.UnsafeEnabled {
mi := &file_hi_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *HelloResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HelloResp) ProtoMessage() {}
func (x *HelloResp) ProtoReflect() protoreflect.Message {
mi := &file_hi_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HelloResp.ProtoReflect.Descriptor instead.
func (*HelloResp) Descriptor() ([]byte, []int) {
return file_hi_proto_rawDescGZIP(), []int{3}
}
func (x *HelloResp) GetMsg() string {
if x != nil {
return x.Msg
}
return ""
}
type EventReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *EventReq) Reset() {
*x = EventReq{}
if protoimpl.UnsafeEnabled {
mi := &file_hi_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *EventReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*EventReq) ProtoMessage() {}
func (x *EventReq) ProtoReflect() protoreflect.Message {
mi := &file_hi_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use EventReq.ProtoReflect.Descriptor instead.
func (*EventReq) Descriptor() ([]byte, []int) {
return file_hi_proto_rawDescGZIP(), []int{4}
}
type EventResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *EventResp) Reset() {
*x = EventResp{}
if protoimpl.UnsafeEnabled {
mi := &file_hi_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *EventResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*EventResp) ProtoMessage() {}
func (x *EventResp) ProtoReflect() protoreflect.Message {
mi := &file_hi_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use EventResp.ProtoReflect.Descriptor instead.
func (*EventResp) Descriptor() ([]byte, []int) {
return file_hi_proto_rawDescGZIP(), []int{5}
}
var File_hi_proto protoreflect.FileDescriptor
var file_hi_proto_rawDesc = []byte{
0x0a, 0x08, 0x68, 0x69, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x68, 0x69, 0x22, 0x17,
0x0a, 0x05, 0x48, 0x69, 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x6e, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x6e, 0x22, 0x1a, 0x0a, 0x08, 0x48, 0x65, 0x6c, 0x6c, 0x6f,
0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x02, 0x69, 0x6e, 0x22, 0x1a, 0x0a, 0x06, 0x48, 0x69, 0x52, 0x65, 0x73, 0x70, 0x12, 0x10, 0x0a,
0x03, 0x6d, 0x73, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22,
0x1d, 0x0a, 0x09, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x12, 0x10, 0x0a, 0x03,
0x6d, 0x73, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0x0a,
0x0a, 0x08, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x22, 0x0b, 0x0a, 0x09, 0x45, 0x76,
0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x32, 0x50, 0x0a, 0x05, 0x47, 0x72, 0x65, 0x65, 0x74,
0x12, 0x1e, 0x0a, 0x05, 0x53, 0x61, 0x79, 0x48, 0x69, 0x12, 0x09, 0x2e, 0x68, 0x69, 0x2e, 0x48,
0x69, 0x52, 0x65, 0x71, 0x1a, 0x0a, 0x2e, 0x68, 0x69, 0x2e, 0x48, 0x69, 0x52, 0x65, 0x73, 0x70,
0x12, 0x27, 0x0a, 0x08, 0x53, 0x61, 0x79, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x0c, 0x2e, 0x68,
0x69, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x1a, 0x0d, 0x2e, 0x68, 0x69, 0x2e,
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x32, 0x33, 0x0a, 0x05, 0x45, 0x76, 0x65,
0x6e, 0x74, 0x12, 0x2a, 0x0a, 0x0b, 0x41, 0x73, 0x6b, 0x51, 0x75, 0x65, 0x73, 0x74, 0x69, 0x6f,
0x6e, 0x12, 0x0c, 0x2e, 0x68, 0x69, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a,
0x0d, 0x2e, 0x68, 0x69, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x42, 0x06,
0x5a, 0x04, 0x2e, 0x2f, 0x68, 0x69, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_hi_proto_rawDescOnce sync.Once
file_hi_proto_rawDescData = file_hi_proto_rawDesc
)
func file_hi_proto_rawDescGZIP() []byte {
file_hi_proto_rawDescOnce.Do(func() {
file_hi_proto_rawDescData = protoimpl.X.CompressGZIP(file_hi_proto_rawDescData)
})
return file_hi_proto_rawDescData
}
var file_hi_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_hi_proto_goTypes = []any{
(*HiReq)(nil), // 0: hi.HiReq
(*HelloReq)(nil), // 1: hi.HelloReq
(*HiResp)(nil), // 2: hi.HiResp
(*HelloResp)(nil), // 3: hi.HelloResp
(*EventReq)(nil), // 4: hi.EventReq
(*EventResp)(nil), // 5: hi.EventResp
}
var file_hi_proto_depIdxs = []int32{
0, // 0: hi.Greet.SayHi:input_type -> hi.HiReq
1, // 1: hi.Greet.SayHello:input_type -> hi.HelloReq
4, // 2: hi.Event.AskQuestion:input_type -> hi.EventReq
2, // 3: hi.Greet.SayHi:output_type -> hi.HiResp
3, // 4: hi.Greet.SayHello:output_type -> hi.HelloResp
5, // 5: hi.Event.AskQuestion:output_type -> hi.EventResp
3, // [3:6] is the sub-list for method output_type
0, // [0:3] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_hi_proto_init() }
func file_hi_proto_init() {
if File_hi_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_hi_proto_msgTypes[0].Exporter = func(v any, i int) any {
switch v := v.(*HiReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_hi_proto_msgTypes[1].Exporter = func(v any, i int) any {
switch v := v.(*HelloReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_hi_proto_msgTypes[2].Exporter = func(v any, i int) any {
switch v := v.(*HiResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_hi_proto_msgTypes[3].Exporter = func(v any, i int) any {
switch v := v.(*HelloResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_hi_proto_msgTypes[4].Exporter = func(v any, i int) any {
switch v := v.(*EventReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_hi_proto_msgTypes[5].Exporter = func(v any, i int) any {
switch v := v.(*EventResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_hi_proto_rawDesc,
NumEnums: 0,
NumMessages: 6,
NumExtensions: 0,
NumServices: 2,
},
GoTypes: file_hi_proto_goTypes,
DependencyIndexes: file_hi_proto_depIdxs,
MessageInfos: file_hi_proto_msgTypes,
}.Build()
File_hi_proto = out.File
file_hi_proto_rawDesc = nil
file_hi_proto_goTypes = nil
file_hi_proto_depIdxs = nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/svc/servicecontext.go | tools/goctl/example/rpc/hi/internal/svc/servicecontext.go | package svc
import "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/config"
type ServiceContext struct {
Config config.Config
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/server/greet/greetserver.go | tools/goctl/example/rpc/hi/internal/server/greet/greetserver.go | // Code generated by goctl. DO NOT EDIT!
// Source: hi.proto
package server
import (
"context"
greetlogic "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/logic/greet"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
)
type GreetServer struct {
svcCtx *svc.ServiceContext
hi.UnimplementedGreetServer
}
func NewGreetServer(svcCtx *svc.ServiceContext) *GreetServer {
return &GreetServer{
svcCtx: svcCtx,
}
}
func (s *GreetServer) SayHi(ctx context.Context, in *hi.HiReq) (*hi.HiResp, error) {
l := greetlogic.NewSayHiLogic(ctx, s.svcCtx)
return l.SayHi(in)
}
func (s *GreetServer) SayHello(ctx context.Context, in *hi.HelloReq) (*hi.HelloResp, error) {
l := greetlogic.NewSayHelloLogic(ctx, s.svcCtx)
return l.SayHello(in)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/server/event/eventserver.go | tools/goctl/example/rpc/hi/internal/server/event/eventserver.go | // Code generated by goctl. DO NOT EDIT!
// Source: hi.proto
package server
import (
"context"
eventlogic "github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/logic/event"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
)
type EventServer struct {
svcCtx *svc.ServiceContext
hi.UnimplementedEventServer
}
func NewEventServer(svcCtx *svc.ServiceContext) *EventServer {
return &EventServer{
svcCtx: svcCtx,
}
}
func (s *EventServer) AskQuestion(ctx context.Context, in *hi.EventReq) (*hi.EventResp, error) {
l := eventlogic.NewAskQuestionLogic(ctx, s.svcCtx)
return l.AskQuestion(in)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/config/config.go | tools/goctl/example/rpc/hi/internal/config/config.go | package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/logic/greet/sayhellologic.go | tools/goctl/example/rpc/hi/internal/logic/greet/sayhellologic.go | package greetlogic
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
)
type SayHelloLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSayHelloLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SayHelloLogic {
return &SayHelloLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SayHelloLogic) SayHello(in *hi.HelloReq) (*hi.HelloResp, error) {
// todo: add your logic here and delete this line
return &hi.HelloResp{}, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/logic/greet/sayhilogic.go | tools/goctl/example/rpc/hi/internal/logic/greet/sayhilogic.go | package greetlogic
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
)
type SayHiLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSayHiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SayHiLogic {
return &SayHiLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SayHiLogic) SayHi(in *hi.HiReq) (*hi.HiResp, error) {
// todo: add your logic here and delete this line
return &hi.HiResp{}, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/internal/logic/event/askquestionlogic.go | tools/goctl/example/rpc/hi/internal/logic/event/askquestionlogic.go | package eventlogic
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/internal/svc"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
)
type AskQuestionLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewAskQuestionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AskQuestionLogic {
return &AskQuestionLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *AskQuestionLogic) AskQuestion(in *hi.EventReq) (*hi.EventResp, error) {
// todo: add your logic here and delete this line
return &hi.EventResp{}, nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/client/greet/greet.go | tools/goctl/example/rpc/hi/client/greet/greet.go | // Code generated by goctl. DO NOT EDIT!
// Source: hi.proto
package client
import (
"context"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
EventReq = hi.EventReq
EventResp = hi.EventResp
HelloReq = hi.HelloReq
HelloResp = hi.HelloResp
HiReq = hi.HiReq
HiResp = hi.HiResp
Greet interface {
SayHi(ctx context.Context, in *HiReq, opts ...grpc.CallOption) (*HiResp, error)
SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error)
}
defaultGreet struct {
cli zrpc.Client
}
)
func NewGreet(cli zrpc.Client) Greet {
return &defaultGreet{
cli: cli,
}
}
func (m *defaultGreet) SayHi(ctx context.Context, in *HiReq, opts ...grpc.CallOption) (*HiResp, error) {
client := hi.NewGreetClient(m.cli.Conn())
return client.SayHi(ctx, in, opts...)
}
func (m *defaultGreet) SayHello(ctx context.Context, in *HelloReq, opts ...grpc.CallOption) (*HelloResp, error) {
client := hi.NewGreetClient(m.cli.Conn())
return client.SayHello(ctx, in, opts...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/example/rpc/hi/client/event/event.go | tools/goctl/example/rpc/hi/client/event/event.go | // Code generated by goctl. DO NOT EDIT!
// Source: hi.proto
package client
import (
"context"
"github.com/zeromicro/go-zero/tools/goctl/example/rpc/hi/pb/hi"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
EventReq = hi.EventReq
EventResp = hi.EventResp
HelloReq = hi.HelloReq
HelloResp = hi.HelloResp
HiReq = hi.HiReq
HiResp = hi.HiResp
Event interface {
AskQuestion(ctx context.Context, in *EventReq, opts ...grpc.CallOption) (*EventResp, error)
}
defaultEvent struct {
cli zrpc.Client
}
)
func NewEvent(cli zrpc.Client) Event {
return &defaultEvent{
cli: cli,
}
}
func (m *defaultEvent) AskQuestion(ctx context.Context, in *EventReq, opts ...grpc.CallOption) (*EventResp, error) {
client := hi.NewEventClient(m.cli.Conn())
return client.AskQuestion(ctx, in, opts...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/cobrax/cobrax.go | tools/goctl/internal/cobrax/cobrax.go | package cobrax
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/zeromicro/go-zero/tools/goctl/internal/flags"
)
type Option func(*cobra.Command)
func WithRunE(runE func(*cobra.Command, []string) error) Option {
return func(cmd *cobra.Command) {
cmd.RunE = runE
}
}
func WithRun(run func(*cobra.Command, []string)) Option {
return func(cmd *cobra.Command) {
cmd.Run = run
}
}
func WithArgs(arg cobra.PositionalArgs) Option {
return func(command *cobra.Command) {
command.Args = arg
}
}
func WithHidden() Option {
return func(command *cobra.Command) {
command.Hidden = true
}
}
type Command struct {
*cobra.Command
}
type FlagSet struct {
*pflag.FlagSet
}
func (f *FlagSet) StringVar(p *string, name string) {
f.StringVarWithDefaultValue(p, name, "")
}
func (f *FlagSet) StringVarWithDefaultValue(p *string, name string, value string) {
f.FlagSet.StringVar(p, name, value, "")
}
func (f *FlagSet) StringVarP(p *string, name, shorthand string) {
f.StringVarPWithDefaultValue(p, name, shorthand, "")
}
func (f *FlagSet) StringVarPWithDefaultValue(p *string, name, shorthand string, value string) {
f.FlagSet.StringVarP(p, name, shorthand, value, "")
}
func (f *FlagSet) BoolVar(p *bool, name string) {
f.BoolVarWithDefaultValue(p, name, false)
}
func (f *FlagSet) BoolVarWithDefaultValue(p *bool, name string, value bool) {
f.FlagSet.BoolVar(p, name, value, "")
}
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string) {
f.BoolVarPWithDefaultValue(p, name, shorthand, false)
}
func (f *FlagSet) BoolVarPWithDefaultValue(p *bool, name, shorthand string, value bool) {
f.FlagSet.BoolVarP(p, name, shorthand, value, "")
}
func (f *FlagSet) IntVar(p *int, name string) {
f.IntVarWithDefaultValue(p, name, 0)
}
func (f *FlagSet) IntVarWithDefaultValue(p *int, name string, value int) {
f.FlagSet.IntVar(p, name, value, "")
}
func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string) {
f.FlagSet.StringSliceVarP(p, name, shorthand, []string{}, "")
}
func (f *FlagSet) StringSliceVarPWithDefaultValue(p *[]string, name, shorthand string, value []string) {
f.FlagSet.StringSliceVarP(p, name, shorthand, value, "")
}
func (f *FlagSet) StringSliceVar(p *[]string, name string) {
f.StringSliceVarWithDefaultValue(p, name, []string{})
}
func (f *FlagSet) StringSliceVarWithDefaultValue(p *[]string, name string, value []string) {
f.FlagSet.StringSliceVar(p, name, value, "")
}
func NewCommand(use string, opts ...Option) *Command {
c := &Command{
Command: &cobra.Command{
Use: use,
},
}
for _, opt := range opts {
opt(c.Command)
}
return c
}
func (c *Command) AddCommand(cmds ...*Command) {
for _, cmd := range cmds {
c.Command.AddCommand(cmd.Command)
}
}
func (c *Command) Flags() *FlagSet {
set := c.Command.Flags()
return &FlagSet{
FlagSet: set,
}
}
func (c *Command) PersistentFlags() *FlagSet {
set := c.Command.PersistentFlags()
return &FlagSet{
FlagSet: set,
}
}
func (c *Command) MustInit() {
commands := append([]*cobra.Command{c.Command}, getCommandsRecursively(c.Command)...)
for _, command := range commands {
commandKey := getCommandName(command)
if len(command.Short) == 0 {
command.Short = flags.Get(commandKey + ".short")
}
if len(command.Long) == 0 {
command.Long = flags.Get(commandKey + ".long")
}
if len(command.Example) == 0 {
command.Example = flags.Get(commandKey + ".example")
}
command.Flags().VisitAll(func(flag *pflag.Flag) {
flag.Usage = flags.Get(fmt.Sprintf("%s.%s", commandKey, flag.Name))
})
command.PersistentFlags().VisitAll(func(flag *pflag.Flag) {
flag.Usage = flags.Get(fmt.Sprintf("%s.%s", commandKey, flag.Name))
})
}
}
func getCommandName(cmd *cobra.Command) string {
if cmd.HasParent() {
return getCommandName(cmd.Parent()) + "." + cmd.Name()
}
return cmd.Name()
}
func getCommandsRecursively(parent *cobra.Command) []*cobra.Command {
var commands []*cobra.Command
for _, cmd := range parent.Commands() {
commands = append(commands, cmd)
commands = append(commands, getCommandsRecursively(cmd)...)
}
return commands
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/version/version_test.go | tools/goctl/internal/version/version_test.go | package version
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_convertVersion(t *testing.T) {
number, tag := convertVersion("1.1.10")
assert.Equal(t, 1.110, number)
assert.Equal(t, "", tag)
number, tag = convertVersion("0.1.11")
assert.Equal(t, 0.111, number)
assert.Equal(t, "", tag)
number, tag = convertVersion("1.11-pre")
assert.Equal(t, 1.11, number)
assert.Equal(t, "pre", tag)
number, tag = convertVersion("1.11-beta-v1")
assert.Equal(t, 1.11, number)
assert.Equal(t, "betav1", tag)
}
func Test_IsVersionGatherThan(t *testing.T) {
assert.False(t, IsVersionGreaterThan("0.11", "1.1"))
assert.True(t, IsVersionGreaterThan("0.112", "0.1"))
assert.True(t, IsVersionGreaterThan("1.1.10", "1.0.111"))
assert.True(t, IsVersionGreaterThan("1.1.10", "1.1.10-pre"))
assert.True(t, IsVersionGreaterThan("1.1.11-pre", "1.1.10"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/version/version.go | tools/goctl/internal/version/version.go | package version
import (
"encoding/json"
"strings"
)
// BuildVersion is the version of goctl.
const BuildVersion = "1.9.2"
var tag = map[string]int{"pre-alpha": 0, "alpha": 1, "pre-beta": 2, "beta": 3, "released": 4, "": 5}
// GetGoctlVersion returns BuildVersion
func GetGoctlVersion() string {
return BuildVersion
}
// IsVersionGreaterThan compares whether the current goctl version
// is greater than the target version
func IsVersionGreaterThan(version, target string) bool {
versionNumber, versionTag := convertVersion(version)
targetVersionNumber, targetTag := convertVersion(target)
if versionNumber > targetVersionNumber {
return true
} else if versionNumber < targetVersionNumber {
return false
} else {
// unchecked case, in normal, the goctl version does not contain suffix in release.
return tag[versionTag] > tag[targetTag]
}
}
// version format: number[.number]*(-tag)
func convertVersion(version string) (versionNumber float64, tag string) {
splits := strings.Split(version, "-")
tag = strings.Join(splits[1:], "")
var flag bool
numberStr := strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
if r == '.' {
if flag {
return '_'
}
flag = true
return r
}
return '_'
}, splits[0])
numberStr = strings.Replace(numberStr, "_", "", -1)
versionNumber, _ = json.Number(numberStr).Float64()
return
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/flags/flags.go | tools/goctl/internal/flags/flags.go | package flags
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"io"
"log"
"strings"
"testing"
"github.com/zeromicro/go-zero/tools/goctl/util"
)
//go:embed default_en.json
var defaultEnFlagConfig []byte
type ConfigLoader struct {
conf map[string]any
}
func (cl *ConfigLoader) ReadConfig(in io.Reader) error {
return json.NewDecoder(in).Decode(&cl.conf)
}
func (cl *ConfigLoader) GetString(key string) string {
keyList := strings.FieldsFunc(key, func(r rune) bool {
return r == '.'
})
var conf = cl.conf
for idx, k := range keyList {
val, ok := conf[k]
if !ok {
return ""
}
if idx < len(keyList)-1 {
conf, ok = val.(map[string]any)
if !ok {
return ""
}
continue
}
return fmt.Sprint(val)
}
return ""
}
type Flags struct {
loader *ConfigLoader
}
func MustLoad() *Flags {
loader := &ConfigLoader{
conf: map[string]any{},
}
if err := loader.ReadConfig(bytes.NewBuffer(defaultEnFlagConfig)); err != nil {
log.Fatal(err)
}
return &Flags{
loader: loader,
}
}
func setTestData(t *testing.T, data []byte) {
origin := defaultEnFlagConfig
defaultEnFlagConfig = data
t.Cleanup(func() {
defaultEnFlagConfig = origin
})
}
func (f *Flags) Get(key string) (string, error) {
value := f.loader.GetString(key)
for util.IsTemplateVariable(value) {
value = util.TemplateVariable(value)
if value == key {
return "", fmt.Errorf("the variable can not be self: %q", key)
}
return f.Get(value)
}
return value, nil
}
var flags *Flags
func Get(key string) string {
if flags == nil {
flags = MustLoad()
}
v, err := flags.Get(key)
if err != nil {
log.Fatal(err)
return ""
}
return v
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/flags/flags_test.go | tools/goctl/internal/flags/flags_test.go | package flags
import (
"fmt"
"testing"
"github.com/zeromicro/go-zero/tools/goctl/test"
)
func TestFlags_Get(t *testing.T) {
setTestData(t, []byte(`{"host":"0.0.0.0","port":8888,"service":{"host":"{{.host}}","port":"{{.port}}","invalid":"{{.service.invalid}}"}}`))
f := MustLoad()
executor := test.NewExecutor[string, string]()
executor.Add([]test.Data[string, string]{
{
Name: "key_host",
Input: "host",
Want: "0.0.0.0",
},
{
Name: "key_port",
Input: "port",
Want: "8888",
},
{
Name: "key_service.host",
Input: "service.host",
Want: "0.0.0.0",
},
{
Name: "key_service.port",
Input: "service.port",
Want: "8888",
},
{
Name: "key_not_exists",
Input: "service.port.invalid",
},
{
Name: "key_service.invalid",
Input: "service.invalid",
E: fmt.Errorf("the variable can not be self: %q", "service.invalid"),
},
}...)
executor.RunE(t, f.Get)
}
func Test_Get(t *testing.T) {
setTestData(t, []byte(`{"host":"0.0.0.0","port":8888,"service":{"host":"{{.host}}","port":"{{.port}}","invalid":"{{.service.invalid}}"}}`))
executor := test.NewExecutor[string, string]()
executor.Add([]test.Data[string, string]{
{
Name: "key_host",
Input: "host",
Want: "0.0.0.0",
},
{
Name: "key_port",
Input: "port",
Want: "8888",
},
{
Name: "key_service.host",
Input: "service.host",
Want: "0.0.0.0",
},
{
Name: "key_service.port",
Input: "service.port",
Want: "8888",
},
{
Name: "key_not_exists",
Input: "service.port.invalid",
},
}...)
executor.Run(t, Get)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/errorx/errorx.go | tools/goctl/internal/errorx/errorx.go | package errorx
import (
"fmt"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/pkg/env"
)
var errorFormat = `goctl error: %+v
goctl env:
%s
%s`
// GoctlError represents a goctl error.
type GoctlError struct {
message []string
err error
}
func (e *GoctlError) Error() string {
detail := wrapMessage(e.message...)
return fmt.Sprintf(errorFormat, e.err, env.Print(), detail)
}
// Wrap wraps an error with goctl version and message.
func Wrap(err error, message ...string) error {
e, ok := err.(*GoctlError)
if ok {
return e
}
return &GoctlError{
message: message,
err: err,
}
}
func wrapMessage(message ...string) string {
if len(message) == 0 {
return ""
}
return fmt.Sprintf(`message: %s`, strings.Join(message, "\n"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/internal/errorx/errorx._test.go | tools/goctl/internal/errorx/errorx._test.go | package errorx
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWrap(t *testing.T) {
err := errors.New("foo")
err = Wrap(err)
_, ok := err.(*GoctlError)
assert.True(t, ok)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/update/update.go | tools/goctl/update/update.go | package main
import (
"flag"
"net/http"
"os"
"path"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/hash"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/tools/goctl/update/config"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
contentMd5Header = "Content-Md5"
filename = "goctl"
)
var configFile = flag.String("f", "etc/update-api.json", "the config file")
func forChksumHandler(file string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !pathx.FileExists(file) {
logx.Errorf("file %q not exist", file)
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
content, err := os.ReadFile(file)
if err != nil {
logx.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
chksum := hash.Md5Hex(content)
if chksum == r.Header.Get(contentMd5Header) {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set(contentMd5Header, chksum)
next.ServeHTTP(w, r)
})
}
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
fs := http.FileServer(http.Dir(c.FileDir))
http.Handle(c.FilePath, http.StripPrefix(c.FilePath, forChksumHandler(path.Join(c.FileDir, filename), fs)))
logx.Must(http.ListenAndServe(c.ListenOn, nil))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/update/config/config.go | tools/goctl/update/config/config.go | package config
import "github.com/zeromicro/go-zero/core/logx"
// Config defines a service configure for goctl update
type Config struct {
logx.LogConf
ListenOn string
FileDir string
FilePath string
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/config/config.go | tools/goctl/config/config.go | package config
import (
_ "embed"
"errors"
"os"
"path/filepath"
"strings"
"github.com/zeromicro/go-zero/tools/goctl/util/ctx"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"gopkg.in/yaml.v2"
)
const (
// DefaultFormat defines a default naming style
DefaultFormat = "gozero"
configFile = "goctl.yaml"
)
//go:embed default.yaml
var defaultConfig []byte
// Config defines the file naming style
type (
Config struct {
// NamingFormat is used to define the naming format of the generated file name.
// just like time formatting, you can specify the formatting style through the
// two format characters go, and zero. for example: snake format you can
// define as go_zero, camel case format you can it is defined as goZero,
// and even split characters can be specified, such as go#zero. in theory,
// any combination can be used, but the prerequisite must meet the naming conventions
// of each operating system file name.
// Note: NamingFormat is based on snake or camel string
NamingFormat string `yaml:"namingFormat"`
}
External struct {
// Model is the configuration for the model code generation.
Model Model `yaml:"model,omitempty"`
}
// Model defines the configuration for the model code generation.
Model struct {
// TypesMap: custom Data Type Mapping Table.
TypesMap map[string]ModelTypeMapOption `yaml:"types_map,omitempty" `
}
// ModelTypeMapOption custom Type Options.
ModelTypeMapOption struct {
// Type: valid when not using UnsignedType and NullType.
Type string `yaml:"type"`
// UnsignedType: valid when not using NullType.
UnsignedType string `yaml:"unsigned_type,omitempty"`
// NullType: priority use.
NullType string `yaml:"null_type,omitempty"`
// Pkg defines the package of the custom type.
Pkg string `yaml:"pkg,omitempty"`
}
)
// NewConfig creates an instance for Config
func NewConfig(format string) (*Config, error) {
if len(format) == 0 {
format = DefaultFormat
}
cfg := &Config{NamingFormat: format}
err := validate(cfg)
return cfg, err
}
func GetExternalConfig() (*External, error) {
var cfg External
err := loadConfig(&cfg)
if err != nil {
return nil, err
}
return &cfg, nil
}
func loadConfig(cfg *External) error {
wd, err := os.Getwd()
if err != nil {
return err
}
cfgFile, err := getConfigPath(wd)
if err != nil {
return err
}
var content []byte
if pathx.FileExists(cfgFile) {
content, err = os.ReadFile(cfgFile)
if err != nil {
return err
}
}
if len(content) == 0 {
content = append(content, defaultConfig...)
}
return yaml.Unmarshal(content, cfg)
}
// getConfigPath returns the configuration file path, but not create the file.
func getConfigPath(workDir string) (string, error) {
abs, err := filepath.Abs(workDir)
if err != nil {
return "", err
}
err = pathx.MkdirIfNotExist(abs)
if err != nil {
return "", err
}
projectCtx, err := ctx.Prepare(abs)
if err != nil {
return "", err
}
return filepath.Join(projectCtx.Dir, configFile), nil
}
func validate(cfg *Config) error {
if len(strings.TrimSpace(cfg.NamingFormat)) == 0 {
return errors.New("missing namingFormat")
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/config/cmd.go | tools/goctl/config/cmd.go | package config
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/zeromicro/go-zero/tools/goctl/internal/cobrax"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
var (
// Cmd describes a bug command.
Cmd = cobrax.NewCommand("config")
initCmd = cobrax.NewCommand("init", cobrax.WithRunE(runConfigInit))
cleanCmd = cobrax.NewCommand("clean", cobrax.WithRunE(runConfigClean))
)
func init() {
Cmd.AddCommand(initCmd, cleanCmd)
}
func runConfigInit(*cobra.Command, []string) error {
wd, err := os.Getwd()
if err != nil {
return err
}
cfgFile, err := getConfigPath(wd)
if err != nil {
return err
}
if pathx.FileExists(cfgFile) {
fmt.Printf("%s already exists, path: %s\n", configFile, cfgFile)
return nil
}
err = os.WriteFile(cfgFile, defaultConfig, 0644)
if err != nil {
return err
}
fmt.Printf("%s generated in %s\n", configFile, cfgFile)
return nil
}
func runConfigClean(*cobra.Command, []string) error {
wd, err := os.Getwd()
if err != nil {
return err
}
cfgFile, err := getConfigPath(wd)
if err != nil {
return err
}
return pathx.RemoveIfExist(cfgFile)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/migrate/cancel.go | tools/goctl/migrate/cancel.go | //go:build linux || darwin || freebsd
package migrate
import (
"os"
"os/signal"
"syscall"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
)
func cancelOnSignals() {
doneChan := syncx.NewDoneChan()
defer doneChan.Close()
go func(dc *syncx.DoneChan) {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT, syscall.SIGTSTP, syscall.SIGQUIT)
select {
case <-c:
console.Error(`
migrate failed, reason: "User Canceled"`)
os.Exit(0)
case <-dc.Done():
return
}
}(doneChan)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.