Debian Codegraph @

repl/typefmt.go

raw
1 // Copyright 2022 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package repl
16
17 import (
18 "fmt"
19 "strings"
20
21 antlr "github.com/antlr4-go/antlr/v4"
22
23 "github.com/google/cel-go/checker"
24 "github.com/google/cel-go/repl/parser"
25
26 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
27 )
28
29 // UnparseType pretty-prints a type for the REPL.
30 func UnparseType(t *exprpb.Type) string {
31 s := checker.FormatCheckedType(t)
32 if s == "" {
33 return "<unknown type>"
34 }
35
36 return s
37 }
38
39 type errorListener struct {
40 *antlr.DefaultErrorListener
41 errs []error
42 }
43
44 func (l *errorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) {
45 l.errs = append(l.errs, fmt.Errorf("type parse error: %s", msg))
46 l.DefaultErrorListener.SyntaxError(recognizer, offendingSymbol, line, column, msg, e)
47 }
48
49 type typesVisitor struct {
50 parser.BaseCommandsVisitor
51
52 errs []error
53 }
54
55 var _ parser.CommandsVisitor = &typesVisitor{}
56
57 type typeParams []*exprpb.Type
58
59 func (t *typesVisitor) Visit(tree antlr.ParseTree) any {
60 switch ctx := tree.(type) {
61 case *parser.StartTypeContext:
62 return t.VisitStartType(ctx)
63 case *parser.TypeContext:
64 return t.VisitType(ctx)
65 case *parser.TypeIdContext:
66 return t.VisitTypeID(ctx)
67 case *parser.TypeParamListContext:
68 return t.VisitTypeParamList(ctx)
69 default:
70 t.errs = append(t.errs, fmt.Errorf("unhandled parse node kind"))
71 return nil
72 }
73
74 }
75
76 func (t *typesVisitor) VisitStartType(ctx *parser.StartTypeContext) any {
77 return t.Visit(ctx.GetT())
78 }
79
80 func (t *typesVisitor) expectUnparameterized(p typeParams, id string) {
81 if p != nil {
82 t.errs = append(t.errs, fmt.Errorf("unexpected type params for %s", id))
83 }
84 }
85
86 func makeAbstract(name string, params typeParams) *exprpb.Type {
87 return &exprpb.Type{TypeKind: &exprpb.Type_AbstractType_{
88 AbstractType: &exprpb.Type_AbstractType{
89 Name: name,
90 ParameterTypes: params}}}
91 }
92
93 func checkWellKnown(name string) *exprpb.Type {
94 switch name {
95 case "google.protobuf.Timestamp", ".google.protobuf.Timestamp", "timestamp":
96 return &exprpb.Type{TypeKind: &exprpb.Type_WellKnown{WellKnown: exprpb.Type_TIMESTAMP}}
97 case "google.protobuf.Duration", ".google.protobuf.Duration", "duration":
98 return &exprpb.Type{TypeKind: &exprpb.Type_WellKnown{WellKnown: exprpb.Type_DURATION}}
99 case "google.protobuf.Any", ".google.protobuf.Any", "any":
100 return &exprpb.Type{TypeKind: &exprpb.Type_WellKnown{WellKnown: exprpb.Type_ANY}}
101 }
102 return nil
103 }
104
105 func (t *typesVisitor) VisitTypeID(ctx *parser.TypeIdContext) any {
106 id := ""
107 if ctx.GetLeadingDot() != nil {
108 id += "."
109 }
110 tl := ctx.GetId()
111 if tl == nil {
112 return nil
113 }
114 id += tl.GetText()
115 for _, tok := range ctx.GetQualifiers() {
116 id += "." + tok.GetText()
117 }
118 return id
119 }
120
121 func (t *typesVisitor) VisitTypeParamList(ctx *parser.TypeParamListContext) any {
122 var params typeParams
123 for _, ty := range ctx.GetTypes() {
124 p := t.Visit(ty)
125 params = append(params, p.(*exprpb.Type))
126 }
127 return params
128 }
129
130 func (t *typesVisitor) VisitType(ctx *parser.TypeContext) any {
131 emptyType := &exprpb.Type{}
132
133 r := t.Visit(ctx.GetId())
134 if r == nil {
135 return emptyType
136 }
137
138 typeID := r.(string)
139
140 paramsCtx := ctx.GetParams()
141
142 var params typeParams
143 if paramsCtx != nil {
144 r = t.Visit(paramsCtx)
145 if r == nil {
146 return emptyType
147 }
148 params = r.(typeParams)
149 }
150
151 switch typeID {
152 case "int":
153 t.expectUnparameterized(params, typeID)
154 return &exprpb.Type{TypeKind: &exprpb.Type_Primitive{Primitive: exprpb.Type_INT64}}
155 case "uint":
156 t.expectUnparameterized(params, typeID)
157 return &exprpb.Type{TypeKind: &exprpb.Type_Primitive{Primitive: exprpb.Type_UINT64}}
158 case "double":
159 t.expectUnparameterized(params, typeID)
160 return &exprpb.Type{TypeKind: &exprpb.Type_Primitive{Primitive: exprpb.Type_DOUBLE}}
161 case "bytes":
162 t.expectUnparameterized(params, typeID)
163 return &exprpb.Type{TypeKind: &exprpb.Type_Primitive{Primitive: exprpb.Type_BYTES}}
164 case "string":
165 t.expectUnparameterized(params, typeID)
166 return &exprpb.Type{TypeKind: &exprpb.Type_Primitive{Primitive: exprpb.Type_STRING}}
167 case "bool":
168 t.expectUnparameterized(params, typeID)
169 return &exprpb.Type{TypeKind: &exprpb.Type_Primitive{Primitive: exprpb.Type_BOOL}}
170 case "dyn":
171 t.expectUnparameterized(params, typeID)
172 return &exprpb.Type{TypeKind: &exprpb.Type_Dyn{}}
173 case "null":
174 t.expectUnparameterized(params, typeID)
175 return &exprpb.Type{TypeKind: &exprpb.Type_Null{}}
176 case "wrapper":
177 if params == nil || len(params) != 1 {
178 t.errs = append(t.errs, fmt.Errorf("expected exactly one parameter for wrapper"))
179 return emptyType
180 }
181 p := params[0]
182 if p.GetPrimitive() == exprpb.Type_PRIMITIVE_TYPE_UNSPECIFIED {
183 t.errs = append(t.errs, fmt.Errorf("expected primitive param for wrapper"))
184 }
185 return &exprpb.Type{TypeKind: &exprpb.Type_Wrapper{Wrapper: p.GetPrimitive()}}
186 case "list":
187 if params == nil || len(params) != 1 {
188 t.errs = append(t.errs, fmt.Errorf("expected exactly one parameter for list"))
189 return emptyType
190 }
191 p := params[0]
192 return &exprpb.Type{TypeKind: &exprpb.Type_ListType_{ListType: &exprpb.Type_ListType{ElemType: p}}}
193 case "map":
194 if params == nil || len(params) != 2 {
195 t.errs = append(t.errs, fmt.Errorf("expected exactly two parameters for map"))
196 return emptyType
197 }
198 k, v := params[0], params[1]
199 return &exprpb.Type{TypeKind: &exprpb.Type_MapType_{
200 MapType: &exprpb.Type_MapType{
201 KeyType: k,
202 ValueType: v,
203 }}}
204 case "type":
205 if params == nil || len(params) != 1 {
206 t.errs = append(t.errs, fmt.Errorf("expected exactly one parameter for type"))
207 return emptyType
208 }
209 p := params[0]
210 return &exprpb.Type{TypeKind: &exprpb.Type_Type{Type: p}}
211 case "optional_type":
212 if len(params) == 0 {
213 params = []*exprpb.Type{{TypeKind: &exprpb.Type_Dyn{}}}
214 }
215 if len(params) != 1 {
216 t.errs = append(t.errs, fmt.Errorf("expected exactly one parameter for optional_type"))
217 return emptyType
218 }
219 return makeAbstract("optional_type", params)
220 default:
221 wkt := checkWellKnown(typeID)
222 if wkt != nil {
223 return wkt
224 }
225
226 if params != nil {
227 return makeAbstract(typeID, params)
228 }
229 return &exprpb.Type{TypeKind: &exprpb.Type_MessageType{MessageType: typeID}}
230 }
231 }
232
233 // ParseType parses a human readable type string into the protobuf representation.
234 func ParseType(t string) (*exprpb.Type, error) {
235 var errListener errorListener
236 visitor := &typesVisitor{}
237 is := antlr.NewInputStream(t)
238 lexer := parser.NewCommandsLexer(is)
239 lexer.RemoveErrorListeners()
240 lexer.AddErrorListener(&errListener)
241 p := parser.NewCommandsParser(antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel))
242 p.RemoveErrorListeners()
243 p.AddErrorListener(&errListener)
244
245 var result *exprpb.Type
246 s := visitor.Visit(p.StartType())
247 if s != nil {
248 result = s.(*exprpb.Type)
249 }
250
251 errs := append(errListener.errs, visitor.errs...)
252 var err error = nil
253
254 if len(errs) > 0 {
255 msgs := make([]string, len(errs))
256 for i, e := range errs {
257 msgs[i] = e.Error()
258 }
259 err = fmt.Errorf("errors parsing type:\n%s", strings.Join(msgs, "\n"))
260 }
261
262 return result, err
263 }