1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
|
// Copyright 2021 CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package textproto
import (
"fmt"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/literal"
"cuelang.org/go/cue/token"
"cuelang.org/go/encoding/protobuf/pbinternal"
"cuelang.org/go/internal/core/adt"
"cuelang.org/go/internal/value"
pbast "github.com/protocolbuffers/txtpbfmt/ast"
"github.com/protocolbuffers/txtpbfmt/parser"
"github.com/protocolbuffers/txtpbfmt/unquote"
)
// Option defines options for the decoder.
// There are currently no options.
type Option func(*options)
type options struct {
}
// NewDecoder returns a new [Decoder].
func NewDecoder(option ...Option) *Decoder {
d := &Decoder{}
_ = d.m // work around linter bug.
return d
}
// A Decoder caches conversions of [cue.Value] between calls to its methods.
type Decoder struct {
m map[*adt.Vertex]*mapping
}
type decoder struct {
*Decoder
// Reset on each call
errs errors.Error
file *token.File
}
// Parse parses the given textproto bytes and converts them to a CUE expression,
// using schema as the guideline for conversion using the following rules:
//
// - the @protobuf attribute is optional, but is necessary for:
// - interpreting protobuf maps
// - using a name different from the CUE name
// - fields in the textproto that have no corresponding field in
// schema are ignored
//
// NOTE: the filename is used for associating position information. However,
// currently no position information is associated with the text proto because
// the position information of github.com/protocolbuffers/txtpbfmt is too
// unreliable to be useful.
func (d *Decoder) Parse(schema cue.Value, filename string, b []byte) (ast.Expr, error) {
dec := decoder{Decoder: d}
// dec.errs = nil
f := token.NewFile(filename, -1, len(b))
f.SetLinesForContent(b)
dec.file = f
cfg := parser.Config{}
nodes, err := parser.ParseWithConfig(b, cfg)
if err != nil {
return nil, errors.Newf(token.NoPos, "textproto: %v", err)
}
m := dec.parseSchema(schema)
if dec.errs != nil {
return nil, dec.errs
}
n := dec.decodeMsg(m, nodes)
if dec.errs != nil {
return nil, dec.errs
}
return n, nil
}
// Don't expose until the protobuf APIs settle down.
// func (d *decoder) Decode(schema cue.Value, textpbfmt) (cue.Value, error) {
// }
type mapping struct {
children map[string]*fieldInfo
}
type fieldInfo struct {
pbinternal.Info
msg *mapping
// keytype, for now
}
func (d *decoder) addErr(err error) {
d.errs = errors.Append(d.errs, errors.Promote(err, "textproto"))
}
func (d *decoder) addErrf(pos pbast.Position, format string, args ...interface{}) {
err := errors.Newf(d.protoPos(pos), "textproto: "+format, args...)
d.errs = errors.Append(d.errs, err)
}
func (d *decoder) protoPos(p pbast.Position) token.Pos {
return d.file.Pos(int(p.Byte), token.NoRelPos)
}
// parseSchema walks over a CUE "type", converts it to an internal data
// structure that is used for parsing text proto, and writes it to
func (d *decoder) parseSchema(schema cue.Value) *mapping {
_, v := value.ToInternal(schema)
if v == nil {
return nil
}
if d.m == nil {
d.m = map[*adt.Vertex]*mapping{}
} else if m := d.m[v]; m != nil {
return m
}
m := &mapping{children: map[string]*fieldInfo{}}
i, err := schema.Fields(cue.Optional(true))
if err != nil {
d.addErr(err)
return nil
}
for i.Next() {
info, err := pbinternal.FromIter(i)
if err != nil {
d.addErr(err)
continue
}
var msg *mapping
switch info.CompositeType {
case pbinternal.Normal:
switch info.ValueType {
case pbinternal.Message:
msg = d.parseSchema(i.Value())
}
case pbinternal.List, pbinternal.Map:
e, _ := i.Value().Elem()
if e.IncompleteKind() == cue.StructKind {
msg = d.parseSchema(e)
}
}
m.children[info.Name] = &fieldInfo{
Info: info,
msg: msg,
}
}
d.m[v] = m
return m
}
func (d *decoder) decodeMsg(m *mapping, n []*pbast.Node) ast.Expr {
st := &ast.StructLit{}
var listMap map[string]*ast.ListLit
for _, x := range n {
if x.Values == nil && x.Children == nil {
if cg := addComments(x.PreComments...); cg != nil {
ast.SetRelPos(cg, token.NewSection)
st.Elts = append(st.Elts, cg)
continue
}
}
if m == nil {
continue
}
f, ok := m.children[x.Name]
if !ok {
continue // ignore unknown fields
}
var value ast.Expr
switch f.CompositeType {
default:
value = d.decodeValue(f, x)
case pbinternal.List:
if listMap == nil {
listMap = make(map[string]*ast.ListLit)
}
list := listMap[f.CUEName]
if list == nil {
list = &ast.ListLit{}
listMap[f.CUEName] = list
value = list
}
if len(x.Values) == 1 || f.ValueType == pbinternal.Message {
v := d.decodeValue(f, x)
if value == nil {
if cg := addComments(x.PreComments...); cg != nil {
cg.Doc = true
ast.AddComment(v, cg)
}
}
if cg := addComments(x.PostValuesComments...); cg != nil {
cg.Position = 4
ast.AddComment(v, cg)
}
list.Elts = append(list.Elts, v)
break
}
var last ast.Expr
// Handle [1, 2, 3]
for _, v := range x.Values {
if v.Value == "" {
if cg := addComments(v.PreComments...); cg != nil {
if last != nil {
cg.Position = 4
ast.AddComment(last, cg)
} else {
cg.Position = 1
ast.AddComment(list, cg)
}
}
continue
}
y := *x
y.Values = []*pbast.Value{v}
last = d.decodeValue(f, &y)
list.Elts = append(list.Elts, last)
}
if cg := addComments(x.PostValuesComments...); cg != nil {
if last != nil {
cg.Position = 4
ast.AddComment(last, cg)
} else {
cg.Position = 1
ast.AddComment(list, cg)
}
}
if cg := addComments(x.ClosingBraceComment); cg != nil {
cg.Position = 4
ast.AddComment(list, cg)
}
case pbinternal.Map:
// mapValue: {
// key: 123
// value: "string"
// }
if k := len(x.Values); k > 0 {
d.addErrf(x.Start, "values not allowed for Message type; found %d", k)
}
var (
key ast.Label
val ast.Expr
)
for _, c := range x.Children {
if len(c.Values) != 1 {
d.addErrf(x.Start, "expected 1 value, found %d", len(c.Values))
continue
}
s := c.Values[0].Value
switch c.Name {
case "key":
if strings.HasPrefix(s, `"`) {
key = &ast.BasicLit{Kind: token.STRING, Value: s}
} else {
key = ast.NewString(s)
}
case "value":
val = d.decodeValue(f, c)
if cg := addComments(x.ClosingBraceComment); cg != nil {
cg.Line = true
ast.AddComment(val, cg)
}
default:
d.addErrf(c.Start, "unsupported key name %q in map", c.Name)
continue
}
}
if key != nil && val != nil {
value = ast.NewStruct(key, val)
}
}
if value != nil {
var label ast.Label
if s := f.CUEName; ast.IsValidIdent(s) {
label = ast.NewIdent(s)
} else {
label = ast.NewString(s)
}
// TODO: convert line number information. However, position
// information in textpbfmt packages is too wonky to be useful
f := &ast.Field{
Label: label,
Value: value,
// Attrs: []*ast.Attribute{{Text: f.attr.}},
}
if cg := addComments(x.PreComments...); cg != nil {
cg.Doc = true
ast.AddComment(f, cg)
}
st.Elts = append(st.Elts, f)
}
}
return st
}
func addComments(lines ...string) (cg *ast.CommentGroup) {
var a []*ast.Comment
for _, c := range lines {
if !strings.HasPrefix(c, "#") {
continue
}
a = append(a, &ast.Comment{Text: "//" + c[1:]})
}
if a != nil {
cg = &ast.CommentGroup{List: a}
}
return cg
}
func (d *decoder) decodeValue(f *fieldInfo, n *pbast.Node) (x ast.Expr) {
if f.ValueType == pbinternal.Message {
if k := len(n.Values); k > 0 {
d.addErrf(n.Start, "values not allowed for Message type; found %d", k)
}
x = d.decodeMsg(f.msg, n.Children)
if cg := addComments(n.ClosingBraceComment); cg != nil {
cg.Line = true
cg.Position = 4
ast.AddComment(x, cg)
}
return x
}
if len(n.Values) != 1 {
d.addErrf(n.Start, "expected 1 value, found %d", len(n.Values))
return nil
}
v := n.Values[0]
defer func() {
if cg := addComments(v.PreComments...); cg != nil {
cg.Doc = true
ast.AddComment(x, cg)
}
if cg := addComments(v.InlineComment); cg != nil {
cg.Line = true
cg.Position = 2
ast.AddComment(x, cg)
}
}()
switch f.ValueType {
case pbinternal.String, pbinternal.Bytes:
s, _, err := unquote.Unquote(n)
if err != nil {
d.addErrf(n.Start, "invalid string or bytes: %v", err)
}
if f.ValueType == pbinternal.String {
s = literal.String.Quote(s)
} else {
s = literal.Bytes.Quote(s)
}
return &ast.BasicLit{Kind: token.STRING, Value: s}
case pbinternal.Bool:
switch v.Value {
case "true":
return ast.NewBool(true)
case "false":
default:
d.addErrf(n.Start, "invalid bool %s", v.Value)
}
return ast.NewBool(false)
case pbinternal.Int, pbinternal.Float:
s := v.Value
switch s {
case "inf", "nan":
// TODO: include message.
return &ast.BottomLit{}
}
var info literal.NumInfo
if err := literal.ParseNum(s, &info); err != nil {
var x ast.BasicLit
if pbinternal.MatchBySymbol(f.Value, s, &x) {
return &x
}
d.addErrf(n.Start, "invalid number %s", s)
}
if !info.IsInt() {
return &ast.BasicLit{Kind: token.FLOAT, Value: s}
}
return &ast.BasicLit{Kind: token.INT, Value: info.String()}
default:
panic(fmt.Sprintf("unexpected type %v", f.ValueType))
}
}
|