maybeOptimizeSetMembership may convert an 'in' operation against a list to map key membership test if the following conditions are true: - the list is a constant with homogeneous element types. - the elements are all of primitive type.
(i InterpretableV2, inlist InterpretableCall)
| 214 | // - the list is a constant with homogeneous element types. |
| 215 | // - the elements are all of primitive type. |
| 216 | func maybeOptimizeSetMembership(i InterpretableV2, inlist InterpretableCall) (InterpretableV2, error) { |
| 217 | args := inlist.Args() |
| 218 | lhs := args[0] |
| 219 | rhs := args[1] |
| 220 | l, isConst := rhs.(InterpretableConst) |
| 221 | if !isConst { |
| 222 | return i, nil |
| 223 | } |
| 224 | // When the incoming binary call is flagged with as the InList overload, the value will |
| 225 | // always be convertible to a `traits.Lister` type. |
| 226 | list := l.Value().(traits.Lister) |
| 227 | if list.Size() == types.IntZero { |
| 228 | return NewConstValue(inlist.ID(), types.False), nil |
| 229 | } |
| 230 | it := list.Iterator() |
| 231 | valueSet := make(map[ref.Val]ref.Val) |
| 232 | for it.HasNext() == types.True { |
| 233 | elem := it.Next() |
| 234 | if !types.IsPrimitiveType(elem) || elem.Type() == types.BytesType { |
| 235 | // Note, non-primitive type are not yet supported, and []byte isn't hashable. |
| 236 | return i, nil |
| 237 | } |
| 238 | valueSet[elem] = types.True |
| 239 | switch ev := elem.(type) { |
| 240 | case types.Double: |
| 241 | iv := ev.ConvertToType(types.IntType) |
| 242 | // Ensure that only lossless conversions are added to the set |
| 243 | if !types.IsError(iv) && iv.Equal(ev) == types.True { |
| 244 | valueSet[iv] = types.True |
| 245 | } |
| 246 | // Ensure that only lossless conversions are added to the set |
| 247 | uv := ev.ConvertToType(types.UintType) |
| 248 | if !types.IsError(uv) && uv.Equal(ev) == types.True { |
| 249 | valueSet[uv] = types.True |
| 250 | } |
| 251 | case types.Int: |
| 252 | dv := ev.ConvertToType(types.DoubleType) |
| 253 | if !types.IsError(dv) { |
| 254 | valueSet[dv] = types.True |
| 255 | } |
| 256 | uv := ev.ConvertToType(types.UintType) |
| 257 | if !types.IsError(uv) { |
| 258 | valueSet[uv] = types.True |
| 259 | } |
| 260 | case types.Uint: |
| 261 | dv := ev.ConvertToType(types.DoubleType) |
| 262 | if !types.IsError(dv) { |
| 263 | valueSet[dv] = types.True |
| 264 | } |
| 265 | iv := ev.ConvertToType(types.IntType) |
| 266 | if !types.IsError(iv) { |
| 267 | valueSet[iv] = types.True |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | return &evalSetMembership{ |
| 272 | inst: inlist, |
| 273 | arg: lhs, |
no test coverage detected