cuelang.org/go@v0.10.1/encoding/protobuf/pbinternal/symbol.go (about) 1 // Copyright 2021 CUE Authors 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 // http://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 pbinternal 16 17 import ( 18 "strconv" 19 20 "cuelang.org/go/cue" 21 "cuelang.org/go/cue/ast" 22 "cuelang.org/go/cue/token" 23 ) 24 25 // MatchBySymbol finds an integer value for a given symbol name, representing 26 // an enum value, and sets it in x. 27 func MatchBySymbol(v cue.Value, name string, x *ast.BasicLit) bool { 28 if op, a := v.Expr(); op == cue.AndOp { 29 for _, v := range a { 30 if MatchBySymbol(v, name, x) { 31 return true 32 } 33 } 34 } 35 return matchBySymbol(cue.Dereference(v), name, x) 36 } 37 38 func matchBySymbol(v cue.Value, name string, x *ast.BasicLit) bool { 39 switch op, a := v.Expr(); op { 40 case cue.OrOp, cue.AndOp: 41 for _, v := range a { 42 if matchBySymbol(v, name, x) { 43 return true 44 } 45 } 46 47 default: 48 _, path := v.ReferencePath() 49 50 a := path.Selectors() 51 if len(a) == 0 { 52 break 53 } 54 if s := a[len(a)-1]; !s.IsDefinition() || s.String()[1:] != name { 55 break 56 } 57 58 if i, err := v.Int64(); err == nil { 59 x.Kind = token.INT 60 x.Value = strconv.Itoa(int(i)) 61 return true 62 } 63 } 64 65 return false 66 } 67 68 // MatchByInt finds a symbol for a given enum value and sets it in x. 69 func MatchByInt(v cue.Value, val int64) string { 70 if op, a := v.Expr(); op == cue.AndOp { 71 for _, v := range a { 72 if s := MatchByInt(v, val); s != "" { 73 return s 74 } 75 } 76 } 77 v = cue.Dereference(v) 78 return matchByInt(v, val) 79 } 80 81 func matchByInt(v cue.Value, val int64) string { 82 switch op, a := v.Expr(); op { 83 case cue.OrOp, cue.AndOp: 84 for _, v := range a { 85 if s := matchByInt(v, val); s != "" { 86 return s 87 } 88 } 89 90 default: 91 if i, err := v.Int64(); err != nil || i != val { 92 break 93 } 94 95 _, path := v.ReferencePath() 96 a := path.Selectors() 97 if len(a) == 0 { 98 break 99 } 100 101 sel := a[len(a)-1] 102 if !sel.IsDefinition() { 103 break 104 } 105 106 return sel.String()[1:] 107 } 108 109 return "" 110 }