github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/sql/sem/tree/treebin/binary_operator.go (about) 1 // Copyright 2022 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package treebin 12 13 import ( 14 "fmt" 15 16 "github.com/cockroachdb/errors" 17 ) 18 19 // BinaryOperator represents a unary operator used in a BinaryExpr. 20 type BinaryOperator struct { 21 Symbol BinaryOperatorSymbol 22 // IsExplicitOperator is true if OPERATOR(symbol) is used. 23 IsExplicitOperator bool 24 } 25 26 // MakeBinaryOperator creates a BinaryOperator given a symbol. 27 func MakeBinaryOperator(symbol BinaryOperatorSymbol) BinaryOperator { 28 return BinaryOperator{Symbol: symbol} 29 } 30 31 func (o BinaryOperator) String() string { 32 if o.IsExplicitOperator { 33 return fmt.Sprintf("OPERATOR(%s)", o.Symbol.String()) 34 } 35 return o.Symbol.String() 36 } 37 38 // Operator implements tree.Operator. 39 func (BinaryOperator) Operator() {} 40 41 // BinaryOperatorSymbol is a symbol for a binary operator. 42 type BinaryOperatorSymbol uint8 43 44 // BinaryExpr.Operator 45 const ( 46 Bitand BinaryOperatorSymbol = iota 47 Bitor 48 Bitxor 49 Plus 50 Minus 51 Mult 52 Div 53 FloorDiv 54 Mod 55 Pow 56 Concat 57 LShift 58 RShift 59 JSONFetchVal 60 JSONFetchText 61 JSONFetchValPath 62 JSONFetchTextPath 63 TSMatch 64 65 NumBinaryOperatorSymbols 66 ) 67 68 var _ = NumBinaryOperatorSymbols 69 70 var binaryOpName = [...]string{ 71 Bitand: "&", 72 Bitor: "|", 73 Bitxor: "#", 74 Plus: "+", 75 Minus: "-", 76 Mult: "*", 77 Div: "/", 78 FloorDiv: "//", 79 Mod: "%", 80 Pow: "^", 81 Concat: "||", 82 LShift: "<<", 83 RShift: ">>", 84 JSONFetchVal: "->", 85 JSONFetchText: "->>", 86 JSONFetchValPath: "#>", 87 JSONFetchTextPath: "#>>", 88 TSMatch: "@@", 89 } 90 91 // IsPadded returns whether the binary operator needs to be padded. 92 func (i BinaryOperatorSymbol) IsPadded() bool { 93 return !(i == JSONFetchVal || i == JSONFetchText || i == JSONFetchValPath || i == JSONFetchTextPath) 94 } 95 96 func (i BinaryOperatorSymbol) String() string { 97 if i > BinaryOperatorSymbol(len(binaryOpName)-1) { 98 return fmt.Sprintf("BinaryOp(%d)", i) 99 } 100 return binaryOpName[i] 101 } 102 103 // BinaryOpName returns the name of op. 104 func BinaryOpName(op BinaryOperatorSymbol) string { 105 if int(op) >= len(binaryOpName) || binaryOpName[op] == "" { 106 panic(errors.AssertionFailedf("missing name for operator %q", op.String())) 107 } 108 return binaryOpName[op] 109 }