| 1 | // Copyright 2018 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 | // 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 types |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "math" |
| 20 | "reflect" |
| 21 | "strconv" |
| 22 | "strings" |
| 23 | "time" |
| 24 | |
| 25 | "github.com/google/cel-go/common/types/ref" |
| 26 | |
| 27 | anypb "google.golang.org/protobuf/types/known/anypb" |
| 28 | structpb "google.golang.org/protobuf/types/known/structpb" |
| 29 | wrapperspb "google.golang.org/protobuf/types/known/wrapperspb" |
| 30 | ) |
| 31 | |
| 32 | // Int type that implements ref.Val as well as comparison and math operators. |
| 33 | type Int int64 |
| 34 | |
| 35 | // Int constants used for comparison results. |
| 36 | const ( |
| 37 | // IntZero is the zero-value for Int |
| 38 | IntZero = Int(0) |
| 39 | IntOne = Int(1) |
| 40 | IntNegOne = Int(-1) |
| 41 | ) |
| 42 | |
| 43 | var ( |
| 44 | // int32WrapperType reflected type for protobuf int32 wrapper type. |
| 45 | int32WrapperType = reflect.TypeOf(&wrapperspb.Int32Value{}) |
| 46 | |
| 47 | // int64WrapperType reflected type for protobuf int64 wrapper type. |
| 48 | int64WrapperType = reflect.TypeOf(&wrapperspb.Int64Value{}) |
| 49 | ) |
| 50 | |
| 51 | // Add implements traits.Adder.Add. |
| 52 | func (i Int) Add(other ref.Val) ref.Val { |
| 53 | otherInt, ok := other.(Int) |
| 54 | if !ok { |
| 55 | return MaybeNoSuchOverloadErr(other) |
| 56 | } |
| 57 | val, err := addInt64Checked(int64(i), int64(otherInt)) |
| 58 | if err != nil { |
| 59 | return WrapErr(err) |
| 60 | } |
| 61 | return Int(val) |
| 62 | } |
| 63 | |
| 64 | // Compare implements traits.Comparer.Compare. |
| 65 | func (i Int) Compare(other ref.Val) ref.Val { |
| 66 | switch ov := other.(type) { |
| 67 | case Double: |
| 68 | if math.IsNaN(float64(ov)) { |
| 69 | return NewErr("NaN values cannot be ordered") |
| 70 | } |
| 71 | return compareIntDouble(i, ov) |
| 72 | case Int: |
| 73 | return compareInt(i, ov) |
| 74 | case Uint: |
| 75 | return compareIntUint(i, ov) |
| 76 | default: |
| 77 | return MaybeNoSuchOverloadErr(other) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // ConvertToNative implements ref.Val.ConvertToNative. |
| 82 | func (i Int) ConvertToNative(typeDesc reflect.Type) (any, error) { |
| 83 | switch typeDesc.Kind() { |
| 84 | case reflect.Int, reflect.Int32: |
| 85 | // Enums are also mapped as int32 derivations. |
| 86 | // Note, the code doesn't convert to the enum value directly since this is not known, but |
| 87 | // the net effect with respect to proto-assignment is handled correctly by the reflection |
| 88 | // Convert method. |
| 89 | v, err := int64ToInt32Checked(int64(i)) |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | return reflect.ValueOf(v).Convert(typeDesc).Interface(), nil |
| 94 | case reflect.Int8: |
| 95 | v, err := int64ToInt8Checked(int64(i)) |
| 96 | if err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | return reflect.ValueOf(v).Convert(typeDesc).Interface(), nil |
| 100 | case reflect.Int16: |
| 101 | v, err := int64ToInt16Checked(int64(i)) |
| 102 | if err != nil { |
| 103 | return nil, err |
| 104 | } |
| 105 | return reflect.ValueOf(v).Convert(typeDesc).Interface(), nil |
| 106 | case reflect.Int64: |
| 107 | return reflect.ValueOf(i).Convert(typeDesc).Interface(), nil |
| 108 | case reflect.Ptr: |
| 109 | switch typeDesc { |
| 110 | case anyValueType: |
| 111 | // Primitives must be wrapped before being set on an Any field. |
| 112 | return anypb.New(wrapperspb.Int64(int64(i))) |
| 113 | case int32WrapperType: |
| 114 | // Convert the value to a wrapperspb.Int32Value, error on overflow. |
| 115 | v, err := int64ToInt32Checked(int64(i)) |
| 116 | if err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | return wrapperspb.Int32(v), nil |
| 120 | case int64WrapperType: |
| 121 | // Convert the value to a wrapperspb.Int64Value. |
| 122 | return wrapperspb.Int64(int64(i)), nil |
| 123 | case JSONValueType: |
| 124 | // The proto-to-JSON conversion rules would convert all 64-bit integer values to JSON |
| 125 | // decimal strings. Because CEL ints might come from the automatic widening of 32-bit |
| 126 | // values in protos, the JSON type is chosen dynamically based on the value. |
| 127 | // |
| 128 | // - Integers -2^53-1 < n < 2^53-1 are encoded as JSON numbers. |
| 129 | // - Integers outside this range are encoded as JSON strings. |
| 130 | // |
| 131 | // The integer to float range represents the largest interval where such a conversion |
| 132 | // can round-trip accurately. Thus, conversions from a 32-bit source can expect a JSON |
| 133 | // number as with protobuf. Those consuming JSON from a 64-bit source must be able to |
| 134 | // handle either a JSON number or a JSON decimal string. To handle these cases safely |
| 135 | // the string values must be explicitly converted to int() within a CEL expression; |
| 136 | // however, it is best to simply stay within the JSON number range when building JSON |
| 137 | // objects in CEL. |
| 138 | if i.isJSONSafe() { |
| 139 | return structpb.NewNumberValue(float64(i)), nil |
| 140 | } |
| 141 | // Proto3 to JSON conversion requires string-formatted int64 values |
| 142 | // since the conversion to floating point would result in truncation. |
| 143 | return structpb.NewStringValue(strconv.FormatInt(int64(i), 10)), nil |
| 144 | } |
| 145 | switch typeDesc.Elem().Kind() { |
| 146 | case reflect.Int32: |
| 147 | // Convert the value to a wrapperspb.Int32Value, error on overflow. |
| 148 | v, err := int64ToInt32Checked(int64(i)) |
| 149 | if err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | p := reflect.New(typeDesc.Elem()) |
| 153 | p.Elem().Set(reflect.ValueOf(v).Convert(typeDesc.Elem())) |
| 154 | return p.Interface(), nil |
| 155 | case reflect.Int64: |
| 156 | v := int64(i) |
| 157 | p := reflect.New(typeDesc.Elem()) |
| 158 | p.Elem().Set(reflect.ValueOf(v).Convert(typeDesc.Elem())) |
| 159 | return p.Interface(), nil |
| 160 | } |
| 161 | case reflect.Interface: |
| 162 | iv := i.Value() |
| 163 | if reflect.TypeOf(iv).Implements(typeDesc) { |
| 164 | return iv, nil |
| 165 | } |
| 166 | if reflect.TypeOf(i).Implements(typeDesc) { |
| 167 | return i, nil |
| 168 | } |
| 169 | } |
| 170 | return nil, fmt.Errorf("unsupported type conversion from 'int' to %v", typeDesc) |
| 171 | } |
| 172 | |
| 173 | // ConvertToType implements ref.Val.ConvertToType. |
| 174 | func (i Int) ConvertToType(typeVal ref.Type) ref.Val { |
| 175 | switch typeVal { |
| 176 | case IntType: |
| 177 | return i |
| 178 | case UintType: |
| 179 | u, err := int64ToUint64Checked(int64(i)) |
| 180 | if err != nil { |
| 181 | return WrapErr(err) |
| 182 | } |
| 183 | return Uint(u) |
| 184 | case DoubleType: |
| 185 | return Double(i) |
| 186 | case StringType: |
| 187 | return String(fmt.Sprintf("%d", int64(i))) |
| 188 | case TimestampType: |
| 189 | // The maximum positive value that can be passed to time.Unix is math.MaxInt64 minus the number |
| 190 | // of seconds between year 1 and year 1970. See comments on unixToInternal. |
| 191 | if int64(i) < minUnixTime || int64(i) > maxUnixTime { |
| 192 | return celErrTimestampOverflow |
| 193 | } |
| 194 | return timestampOf(time.Unix(int64(i), 0).UTC()) |
| 195 | case TypeType: |
| 196 | return IntType |
| 197 | } |
| 198 | return NewErr("type conversion error from '%s' to '%s'", IntType, typeVal) |
| 199 | } |
| 200 | |
| 201 | // Divide implements traits.Divider.Divide. |
| 202 | func (i Int) Divide(other ref.Val) ref.Val { |
| 203 | otherInt, ok := other.(Int) |
| 204 | if !ok { |
| 205 | return MaybeNoSuchOverloadErr(other) |
| 206 | } |
| 207 | val, err := divideInt64Checked(int64(i), int64(otherInt)) |
| 208 | if err != nil { |
| 209 | return WrapErr(err) |
| 210 | } |
| 211 | return Int(val) |
| 212 | } |
| 213 | |
| 214 | // Equal implements ref.Val.Equal. |
| 215 | func (i Int) Equal(other ref.Val) ref.Val { |
| 216 | switch ov := other.(type) { |
| 217 | case Double: |
| 218 | if math.IsNaN(float64(ov)) { |
| 219 | return False |
| 220 | } |
| 221 | return Bool(compareIntDouble(i, ov) == 0) |
| 222 | case Int: |
| 223 | return Bool(i == ov) |
| 224 | case Uint: |
| 225 | return Bool(compareIntUint(i, ov) == 0) |
| 226 | default: |
| 227 | return False |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // IsZeroValue returns true if integer is equal to 0 |
| 232 | func (i Int) IsZeroValue() bool { |
| 233 | return i == IntZero |
| 234 | } |
| 235 | |
| 236 | // Modulo implements traits.Modder.Modulo. |
| 237 | func (i Int) Modulo(other ref.Val) ref.Val { |
| 238 | otherInt, ok := other.(Int) |
| 239 | if !ok { |
| 240 | return MaybeNoSuchOverloadErr(other) |
| 241 | } |
| 242 | val, err := moduloInt64Checked(int64(i), int64(otherInt)) |
| 243 | if err != nil { |
| 244 | return WrapErr(err) |
| 245 | } |
| 246 | return Int(val) |
| 247 | } |
| 248 | |
| 249 | // Multiply implements traits.Multiplier.Multiply. |
| 250 | func (i Int) Multiply(other ref.Val) ref.Val { |
| 251 | otherInt, ok := other.(Int) |
| 252 | if !ok { |
| 253 | return MaybeNoSuchOverloadErr(other) |
| 254 | } |
| 255 | val, err := multiplyInt64Checked(int64(i), int64(otherInt)) |
| 256 | if err != nil { |
| 257 | return WrapErr(err) |
| 258 | } |
| 259 | return Int(val) |
| 260 | } |
| 261 | |
| 262 | // Negate implements traits.Negater.Negate. |
| 263 | func (i Int) Negate() ref.Val { |
| 264 | val, err := negateInt64Checked(int64(i)) |
| 265 | if err != nil { |
| 266 | return WrapErr(err) |
| 267 | } |
| 268 | return Int(val) |
| 269 | } |
| 270 | |
| 271 | // Subtract implements traits.Subtractor.Subtract. |
| 272 | func (i Int) Subtract(subtrahend ref.Val) ref.Val { |
| 273 | subtraInt, ok := subtrahend.(Int) |
| 274 | if !ok { |
| 275 | return MaybeNoSuchOverloadErr(subtrahend) |
| 276 | } |
| 277 | val, err := subtractInt64Checked(int64(i), int64(subtraInt)) |
| 278 | if err != nil { |
| 279 | return WrapErr(err) |
| 280 | } |
| 281 | return Int(val) |
| 282 | } |
| 283 | |
| 284 | // Type implements ref.Val.Type. |
| 285 | func (i Int) Type() ref.Type { |
| 286 | return IntType |
| 287 | } |
| 288 | |
| 289 | // Value implements ref.Val.Value. |
| 290 | func (i Int) Value() any { |
| 291 | return int64(i) |
| 292 | } |
| 293 | |
| 294 | func (i Int) format(sb *strings.Builder) { |
| 295 | sb.WriteString(strconv.FormatInt(int64(i), 10)) |
| 296 | } |
| 297 | |
| 298 | // isJSONSafe indicates whether the int is safely representable as a floating point value in JSON. |
| 299 | func (i Int) isJSONSafe() bool { |
| 300 | return i >= minIntJSON && i <= maxIntJSON |
| 301 | } |
| 302 | |
| 303 | const ( |
| 304 | // maxIntJSON is defined as the Number.MAX_SAFE_INTEGER value per EcmaScript 6. |
| 305 | maxIntJSON = 1<<53 - 1 |
| 306 | // minIntJSON is defined as the Number.MIN_SAFE_INTEGER value per EcmaScript 6. |
| 307 | minIntJSON = -maxIntJSON |
| 308 | ) |