valuer.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  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. package xsql
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/binder/function"
  18. "github.com/lf-edge/ekuiper/pkg/ast"
  19. "github.com/lf-edge/ekuiper/pkg/cast"
  20. "math"
  21. "reflect"
  22. "time"
  23. )
  24. var implicitValueFuncs = map[string]bool{
  25. "window_start": true,
  26. "window_end": true,
  27. }
  28. /*
  29. * Valuer definitions
  30. */
  31. // Valuer is the interface that wraps the Value() method.
  32. type Valuer interface {
  33. // Value returns the value and existence flag for a given key.
  34. Value(key, table string) (interface{}, bool)
  35. Meta(key, table string) (interface{}, bool)
  36. }
  37. // AliasValuer is used to calculate and cache the alias value
  38. type AliasValuer interface {
  39. // AliasValue Get the value of alias
  40. AliasValue(name string) (interface{}, bool)
  41. // AppendAlias set the alias result
  42. AppendAlias(key string, value interface{}) bool
  43. }
  44. // CallValuer implements the Call method for evaluating function calls.
  45. type CallValuer interface {
  46. Valuer
  47. // Call is invoked to evaluate a function call (if possible).
  48. Call(name string, funcId int, args []interface{}) (interface{}, bool)
  49. }
  50. // FuncValuer can calculate function type value like window_start and window_end
  51. type FuncValuer interface {
  52. FuncValue(key string) (interface{}, bool)
  53. }
  54. type AggregateCallValuer interface {
  55. CallValuer
  56. GetAllTuples() AggregateData
  57. GetSingleCallValuer() CallValuer
  58. }
  59. type WildcardValuer struct {
  60. Data Wildcarder
  61. }
  62. func (wv *WildcardValuer) Value(key, table string) (interface{}, bool) {
  63. if key == "*" {
  64. return wv.Data.All(table)
  65. }
  66. return nil, false
  67. }
  68. func (wv *WildcardValuer) Meta(_, _ string) (interface{}, bool) {
  69. return nil, false
  70. }
  71. // MultiValuer returns a Valuer that iterates over multiple Valuer instances
  72. // to find a match.
  73. func MultiValuer(valuers ...Valuer) Valuer {
  74. return multiValuer(valuers)
  75. }
  76. type multiValuer []Valuer
  77. func (a multiValuer) Value(key, table string) (interface{}, bool) {
  78. for _, valuer := range a {
  79. if v, ok := valuer.Value(key, table); ok {
  80. return v, true
  81. }
  82. }
  83. return nil, false
  84. }
  85. func (a multiValuer) Meta(key, table string) (interface{}, bool) {
  86. for _, valuer := range a {
  87. if v, ok := valuer.Meta(key, table); ok {
  88. return v, true
  89. }
  90. }
  91. return nil, false
  92. }
  93. func (a multiValuer) AppendAlias(key string, value interface{}) bool {
  94. for _, valuer := range a {
  95. if vv, ok := valuer.(AliasValuer); ok {
  96. if ok := vv.AppendAlias(key, value); ok {
  97. return true
  98. }
  99. }
  100. }
  101. return false
  102. }
  103. func (a multiValuer) AliasValue(key string) (interface{}, bool) {
  104. for _, valuer := range a {
  105. if vv, ok := valuer.(AliasValuer); ok {
  106. return vv.AliasValue(key)
  107. }
  108. }
  109. return nil, false
  110. }
  111. func (a multiValuer) FuncValue(key string) (interface{}, bool) {
  112. for _, valuer := range a {
  113. if vv, ok := valuer.(FuncValuer); ok {
  114. if r, ok := vv.FuncValue(key); ok {
  115. return r, true
  116. }
  117. }
  118. }
  119. return nil, false
  120. }
  121. func (a multiValuer) Call(name string, funcId int, args []interface{}) (interface{}, bool) {
  122. for _, valuer := range a {
  123. if valuer, ok := valuer.(CallValuer); ok {
  124. if v, ok := valuer.Call(name, funcId, args); ok {
  125. return v, true
  126. } else {
  127. return fmt.Errorf("call func %s error: %v", name, v), false
  128. }
  129. }
  130. }
  131. return nil, false
  132. }
  133. type multiAggregateValuer struct {
  134. data AggregateData
  135. multiValuer
  136. singleCallValuer CallValuer
  137. }
  138. func MultiAggregateValuer(data AggregateData, singleCallValuer CallValuer, valuers ...Valuer) Valuer {
  139. return &multiAggregateValuer{
  140. data: data,
  141. multiValuer: valuers,
  142. singleCallValuer: singleCallValuer,
  143. }
  144. }
  145. func (a *multiAggregateValuer) Call(name string, funcId int, args []interface{}) (interface{}, bool) {
  146. // assume the aggFuncMap already cache the custom agg funcs in IsAggFunc()
  147. isAgg := function.IsAggFunc(name)
  148. for _, valuer := range a.multiValuer {
  149. if a, ok := valuer.(AggregateCallValuer); ok && isAgg {
  150. if v, ok := a.Call(name, funcId, args); ok {
  151. return v, true
  152. } else {
  153. return fmt.Errorf("call func %s error: %v", name, v), false
  154. }
  155. } else if c, ok := valuer.(CallValuer); ok && !isAgg {
  156. if v, ok := c.Call(name, funcId, args); ok {
  157. return v, true
  158. }
  159. }
  160. }
  161. return nil, false
  162. }
  163. func (a *multiAggregateValuer) GetAllTuples() AggregateData {
  164. return a.data
  165. }
  166. func (a *multiAggregateValuer) GetSingleCallValuer() CallValuer {
  167. return a.singleCallValuer
  168. }
  169. func (a *multiAggregateValuer) AppendAlias(key string, value interface{}) bool {
  170. if vv, ok := a.data.(AliasValuer); ok {
  171. if ok := vv.AppendAlias(key, value); ok {
  172. return true
  173. }
  174. return false
  175. } else {
  176. return a.multiValuer.AppendAlias(key, value)
  177. }
  178. }
  179. func (a *multiAggregateValuer) AliasValue(key string) (interface{}, bool) {
  180. if vv, ok := a.data.(AliasValuer); ok {
  181. return vv.AliasValue(key)
  182. } else {
  183. return a.multiValuer.AliasValue(key)
  184. }
  185. }
  186. /*
  187. * Eval Logics
  188. */
  189. // Eval evaluates expr against a map.
  190. func Eval(expr ast.Expr, m Valuer) interface{} {
  191. eval := ValuerEval{Valuer: m}
  192. return eval.Eval(expr)
  193. }
  194. // ValuerEval will evaluate an expression using the Valuer.
  195. type ValuerEval struct {
  196. Valuer Valuer
  197. // IntegerFloatDivision will set the eval system to treat
  198. // a division between two integers as a floating point division.
  199. IntegerFloatDivision bool
  200. }
  201. // Eval evaluates an expression and returns a value.
  202. // map the expression to the correct valuer
  203. func (v *ValuerEval) Eval(expr ast.Expr) interface{} {
  204. if expr == nil {
  205. return nil
  206. }
  207. switch expr := expr.(type) {
  208. case *ast.BinaryExpr:
  209. return v.evalBinaryExpr(expr)
  210. case *ast.IntegerLiteral:
  211. return expr.Val
  212. case *ast.NumberLiteral:
  213. return expr.Val
  214. case *ast.ParenExpr:
  215. return v.Eval(expr.Expr)
  216. case *ast.StringLiteral:
  217. return expr.Val
  218. case *ast.BooleanLiteral:
  219. return expr.Val
  220. case *ast.ColonExpr:
  221. s, e := v.Eval(expr.Start), v.Eval(expr.End)
  222. si, err := cast.ToInt(s, cast.CONVERT_SAMEKIND)
  223. if err != nil {
  224. return fmt.Errorf("colon start %v is not int: %v", expr.Start, err)
  225. }
  226. ei, err := cast.ToInt(e, cast.CONVERT_SAMEKIND)
  227. if err != nil {
  228. return fmt.Errorf("colon end %v is not int: %v", expr.End, err)
  229. }
  230. return &BracketEvalResult{Start: si, End: ei}
  231. case *ast.IndexExpr:
  232. i := v.Eval(expr.Index)
  233. ii, err := cast.ToInt(i, cast.CONVERT_SAMEKIND)
  234. if err != nil {
  235. return fmt.Errorf("index %v is not int: %v", expr.Index, err)
  236. }
  237. return &BracketEvalResult{Start: ii, End: ii}
  238. case *ast.Call:
  239. if _, ok := implicitValueFuncs[expr.Name]; ok {
  240. if vv, ok := v.Valuer.(FuncValuer); ok {
  241. val, ok := vv.FuncValue(expr.Name)
  242. if ok {
  243. return val
  244. }
  245. }
  246. } else {
  247. if valuer, ok := v.Valuer.(CallValuer); ok {
  248. var (
  249. args []interface{}
  250. ft = function.GetFuncType(expr.Name)
  251. )
  252. if len(expr.Args) > 0 {
  253. switch ft {
  254. case function.FuncTypeAgg:
  255. args = make([]interface{}, len(expr.Args))
  256. for i, arg := range expr.Args {
  257. if aggreValuer, ok := valuer.(AggregateCallValuer); ok {
  258. args[i] = aggreValuer.GetAllTuples().AggregateEval(arg, aggreValuer.GetSingleCallValuer())
  259. } else {
  260. args[i] = v.Eval(arg)
  261. if _, ok := args[i].(error); ok {
  262. return args[i]
  263. }
  264. }
  265. }
  266. case function.FuncTypeScalar:
  267. args = make([]interface{}, len(expr.Args))
  268. for i, arg := range expr.Args {
  269. args[i] = v.Eval(arg)
  270. if _, ok := args[i].(error); ok {
  271. return args[i]
  272. }
  273. }
  274. case function.FuncTypeCols:
  275. var keys []string
  276. for _, arg := range expr.Args { // In the parser, the col func arguments must be ColField
  277. cf, ok := arg.(*ast.ColFuncField)
  278. if !ok {
  279. // won't happen
  280. return fmt.Errorf("expect colFuncField but got %v", arg)
  281. }
  282. temp := v.Eval(cf.Expr)
  283. if _, ok := temp.(error); ok {
  284. return temp
  285. }
  286. switch cf.Expr.(type) {
  287. case *ast.Wildcard:
  288. m, ok := temp.(Message)
  289. if !ok {
  290. return fmt.Errorf("wildcarder return non message result")
  291. }
  292. for kk, vv := range m {
  293. args = append(args, vv)
  294. keys = append(keys, kk)
  295. }
  296. default:
  297. args = append(args, temp)
  298. keys = append(keys, cf.Name)
  299. }
  300. }
  301. args = append(args, keys)
  302. default:
  303. // won't happen
  304. return fmt.Errorf("unknown function type")
  305. }
  306. }
  307. val, _ := valuer.Call(expr.Name, expr.FuncId, args)
  308. return val
  309. }
  310. }
  311. return nil
  312. case *ast.FieldRef:
  313. var (
  314. t, n string
  315. )
  316. if expr.IsAlias() {
  317. if valuer, ok := v.Valuer.(AliasValuer); ok {
  318. val, ok := valuer.AliasValue(expr.Name)
  319. if ok {
  320. return val
  321. } else {
  322. r := v.Eval(expr.Expression)
  323. // TODO possible performance elevation to eliminate this cal
  324. valuer.AppendAlias(expr.Name, r)
  325. return r
  326. }
  327. }
  328. } else if expr.StreamName == ast.DefaultStream {
  329. n = expr.Name
  330. } else {
  331. t = string(expr.StreamName)
  332. n = expr.Name
  333. }
  334. if n != "" {
  335. val, ok := v.Valuer.Value(n, t)
  336. if ok {
  337. return val
  338. }
  339. }
  340. return nil
  341. case *ast.MetaRef:
  342. if expr.StreamName == "" || expr.StreamName == ast.DefaultStream {
  343. val, _ := v.Valuer.Meta(expr.Name, "")
  344. return val
  345. } else {
  346. //The field specified with stream source
  347. val, _ := v.Valuer.Meta(expr.Name, string(expr.StreamName))
  348. return val
  349. }
  350. case *ast.JsonFieldRef:
  351. val, ok := v.Valuer.Value(expr.Name, "")
  352. if ok {
  353. return val
  354. } else {
  355. return nil
  356. }
  357. case *ast.Wildcard:
  358. val, _ := v.Valuer.Value("*", "")
  359. return val
  360. case *ast.CaseExpr:
  361. return v.evalCase(expr)
  362. case *ast.ValueSetExpr:
  363. return v.evalValueSet(expr)
  364. default:
  365. return nil
  366. }
  367. }
  368. func (v *ValuerEval) evalBinaryExpr(expr *ast.BinaryExpr) interface{} {
  369. lhs := v.Eval(expr.LHS)
  370. switch val := lhs.(type) {
  371. case map[string]interface{}:
  372. return v.evalJsonExpr(val, expr.OP, expr.RHS)
  373. case Message:
  374. return v.evalJsonExpr(map[string]interface{}(val), expr.OP, expr.RHS)
  375. case error:
  376. return val
  377. }
  378. // shortcut for bool
  379. switch expr.OP {
  380. case ast.AND:
  381. if bv, ok := lhs.(bool); ok && !bv {
  382. return false
  383. }
  384. case ast.OR:
  385. if bv, ok := lhs.(bool); ok && bv {
  386. return true
  387. }
  388. }
  389. if isSliceOrArray(lhs) {
  390. return v.evalJsonExpr(lhs, expr.OP, expr.RHS)
  391. }
  392. rhs := v.Eval(expr.RHS)
  393. if _, ok := rhs.(error); ok {
  394. return rhs
  395. }
  396. if isSetOperator(expr.OP) {
  397. return v.evalSetsExpr(lhs, expr.OP, rhs)
  398. }
  399. return v.simpleDataEval(lhs, rhs, expr.OP)
  400. }
  401. func (v *ValuerEval) evalCase(expr *ast.CaseExpr) interface{} {
  402. if expr.Value != nil { // compare value to all when clause
  403. ev := v.Eval(expr.Value)
  404. for _, w := range expr.WhenClauses {
  405. wv := v.Eval(w.Expr)
  406. switch r := v.simpleDataEval(ev, wv, ast.EQ).(type) {
  407. case error:
  408. return fmt.Errorf("evaluate case expression error: %s", r)
  409. case bool:
  410. if r {
  411. return v.Eval(w.Result)
  412. }
  413. }
  414. }
  415. } else {
  416. for _, w := range expr.WhenClauses {
  417. switch r := v.Eval(w.Expr).(type) {
  418. case error:
  419. return fmt.Errorf("evaluate case expression error: %s", r)
  420. case bool:
  421. if r {
  422. return v.Eval(w.Result)
  423. }
  424. }
  425. }
  426. }
  427. if expr.ElseClause != nil {
  428. return v.Eval(expr.ElseClause)
  429. }
  430. return nil
  431. }
  432. func (v *ValuerEval) evalValueSet(expr *ast.ValueSetExpr) interface{} {
  433. var valueSet []interface{}
  434. if expr.LiteralExprs != nil {
  435. for _, exp := range expr.LiteralExprs {
  436. valueSet = append(valueSet, v.Eval(exp))
  437. }
  438. return valueSet
  439. }
  440. value := v.Eval(expr.ArrayExpr)
  441. if isSliceOrArray(value) {
  442. return value
  443. }
  444. return nil
  445. }
  446. func (v *ValuerEval) evalSetsExpr(lhs interface{}, op ast.Token, rhsSet interface{}) interface{} {
  447. switch op {
  448. /*Semantic rules
  449. When using the IN operator, the following semantics apply in this order:
  450. Returns FALSE if value_set is empty.
  451. Returns NULL if search_value is NULL.
  452. Returns TRUE if value_set contains a value equal to search_value.
  453. Returns NULL if value_set contains a NULL.
  454. Returns FALSE.
  455. When using the NOT IN operator, the following semantics apply in this order:
  456. Returns TRUE if value_set is empty.
  457. Returns NULL if search_value is NULL.
  458. Returns FALSE if value_set contains a value equal to search_value.
  459. Returns NULL if value_set contains a NULL.
  460. Returns TRUE.
  461. */
  462. case ast.IN, ast.NOTIN:
  463. if rhsSet == nil {
  464. if op == ast.IN {
  465. return false
  466. } else {
  467. return true
  468. }
  469. }
  470. if lhs == nil {
  471. return nil
  472. }
  473. rhsSetVals := reflect.ValueOf(rhsSet)
  474. for i := 0; i < rhsSetVals.Len(); i++ {
  475. switch r := v.simpleDataEval(lhs, rhsSetVals.Index(i).Interface(), ast.EQ).(type) {
  476. case error:
  477. return fmt.Errorf("evaluate in expression error: %s", r)
  478. case bool:
  479. if r {
  480. if op == ast.IN {
  481. return true
  482. } else {
  483. return false
  484. }
  485. }
  486. }
  487. }
  488. if op == ast.IN {
  489. return false
  490. } else {
  491. return true
  492. }
  493. default:
  494. return fmt.Errorf("%v is an invalid operation for %T", op, lhs)
  495. }
  496. }
  497. func (v *ValuerEval) evalJsonExpr(result interface{}, op ast.Token, expr ast.Expr) interface{} {
  498. switch op {
  499. case ast.ARROW:
  500. if val, ok := result.(map[string]interface{}); ok {
  501. switch e := expr.(type) {
  502. case *ast.JsonFieldRef:
  503. ve := &ValuerEval{Valuer: Message(val)}
  504. return ve.Eval(e)
  505. default:
  506. return fmt.Errorf("the right expression is not a field reference node")
  507. }
  508. } else {
  509. return fmt.Errorf("the result %v is not a type of map[string]interface{}", result)
  510. }
  511. case ast.SUBSET:
  512. if isSliceOrArray(result) {
  513. return v.subset(result, expr)
  514. } else {
  515. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  516. }
  517. default:
  518. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  519. }
  520. }
  521. func (v *ValuerEval) subset(result interface{}, expr ast.Expr) interface{} {
  522. val := reflect.ValueOf(result)
  523. ber := v.Eval(expr)
  524. if berVal, ok1 := ber.(*BracketEvalResult); ok1 {
  525. if berVal.isIndex() {
  526. if 0 > berVal.Start {
  527. if 0 > berVal.Start+val.Len() {
  528. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  529. }
  530. berVal.Start += val.Len()
  531. } else if berVal.Start >= val.Len() {
  532. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  533. }
  534. return val.Index(berVal.Start).Interface()
  535. } else {
  536. if 0 > berVal.Start {
  537. if 0 > berVal.Start+val.Len() {
  538. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  539. }
  540. berVal.Start += val.Len()
  541. } else if berVal.Start >= val.Len() {
  542. return fmt.Errorf("start value is out of index: %d of %d", berVal.Start, val.Len())
  543. }
  544. if math.MinInt32 == berVal.End {
  545. berVal.End = val.Len()
  546. } else if 0 > berVal.End {
  547. if 0 > berVal.End+val.Len() {
  548. return fmt.Errorf("out of index: %d of %d", berVal.End, val.Len())
  549. }
  550. berVal.End += val.Len()
  551. } else if berVal.End > val.Len() {
  552. return fmt.Errorf("end value is out of index: %d of %d", berVal.End, val.Len())
  553. } else if berVal.Start >= berVal.End {
  554. return fmt.Errorf("start cannot be greater than end. start:%d end:%d", berVal.Start, berVal.End)
  555. }
  556. return val.Slice(berVal.Start, berVal.End).Interface()
  557. }
  558. } else {
  559. return fmt.Errorf("invalid evaluation result - %v", berVal)
  560. }
  561. }
  562. //lhs and rhs are non-nil
  563. func (v *ValuerEval) simpleDataEval(lhs, rhs interface{}, op ast.Token) interface{} {
  564. if lhs == nil || rhs == nil {
  565. switch op {
  566. case ast.EQ, ast.LTE, ast.GTE:
  567. if lhs == nil && rhs == nil {
  568. return true
  569. } else {
  570. return false
  571. }
  572. case ast.NEQ:
  573. if lhs == nil && rhs == nil {
  574. return false
  575. } else {
  576. return true
  577. }
  578. case ast.LT, ast.GT:
  579. return false
  580. default:
  581. return nil
  582. }
  583. }
  584. lhs = convertNum(lhs)
  585. rhs = convertNum(rhs)
  586. // Evaluate if both sides are simple types.
  587. switch lhs := lhs.(type) {
  588. case bool:
  589. rhs, ok := rhs.(bool)
  590. if !ok {
  591. return invalidOpError(lhs, op, rhs)
  592. }
  593. switch op {
  594. case ast.AND:
  595. return lhs && rhs
  596. case ast.OR:
  597. return lhs || rhs
  598. case ast.BITWISE_AND:
  599. return lhs && rhs
  600. case ast.BITWISE_OR:
  601. return lhs || rhs
  602. case ast.BITWISE_XOR:
  603. return lhs != rhs
  604. case ast.EQ:
  605. return lhs == rhs
  606. case ast.NEQ:
  607. return lhs != rhs
  608. default:
  609. return invalidOpError(lhs, op, rhs)
  610. }
  611. case float64:
  612. // Try the rhs as a float64, int64, or uint64
  613. rhsf, ok := rhs.(float64)
  614. if !ok {
  615. switch val := rhs.(type) {
  616. case int64:
  617. rhsf, ok = float64(val), true
  618. case uint64:
  619. rhsf, ok = float64(val), true
  620. }
  621. }
  622. if !ok {
  623. return invalidOpError(lhs, op, rhs)
  624. }
  625. rhs := rhsf
  626. switch op {
  627. case ast.EQ:
  628. return lhs == rhs
  629. case ast.NEQ:
  630. return lhs != rhs
  631. case ast.LT:
  632. return lhs < rhs
  633. case ast.LTE:
  634. return lhs <= rhs
  635. case ast.GT:
  636. return lhs > rhs
  637. case ast.GTE:
  638. return lhs >= rhs
  639. case ast.ADD:
  640. return lhs + rhs
  641. case ast.SUB:
  642. return lhs - rhs
  643. case ast.MUL:
  644. return lhs * rhs
  645. case ast.DIV:
  646. if rhs == 0 {
  647. return fmt.Errorf("divided by zero")
  648. }
  649. return lhs / rhs
  650. case ast.MOD:
  651. if rhs == 0 {
  652. return fmt.Errorf("divided by zero")
  653. }
  654. return math.Mod(lhs, rhs)
  655. default:
  656. return invalidOpError(lhs, op, rhs)
  657. }
  658. case int64:
  659. // Try as a float64 to see if a float cast is required.
  660. switch rhs := rhs.(type) {
  661. case float64:
  662. lhs := float64(lhs)
  663. switch op {
  664. case ast.EQ:
  665. return lhs == rhs
  666. case ast.NEQ:
  667. return lhs != rhs
  668. case ast.LT:
  669. return lhs < rhs
  670. case ast.LTE:
  671. return lhs <= rhs
  672. case ast.GT:
  673. return lhs > rhs
  674. case ast.GTE:
  675. return lhs >= rhs
  676. case ast.ADD:
  677. return lhs + rhs
  678. case ast.SUB:
  679. return lhs - rhs
  680. case ast.MUL:
  681. return lhs * rhs
  682. case ast.DIV:
  683. if rhs == 0 {
  684. return fmt.Errorf("divided by zero")
  685. }
  686. return lhs / rhs
  687. case ast.MOD:
  688. if rhs == 0 {
  689. return fmt.Errorf("divided by zero")
  690. }
  691. return math.Mod(lhs, rhs)
  692. default:
  693. return invalidOpError(lhs, op, rhs)
  694. }
  695. case int64:
  696. switch op {
  697. case ast.EQ:
  698. return lhs == rhs
  699. case ast.NEQ:
  700. return lhs != rhs
  701. case ast.LT:
  702. return lhs < rhs
  703. case ast.LTE:
  704. return lhs <= rhs
  705. case ast.GT:
  706. return lhs > rhs
  707. case ast.GTE:
  708. return lhs >= rhs
  709. case ast.ADD:
  710. return lhs + rhs
  711. case ast.SUB:
  712. return lhs - rhs
  713. case ast.MUL:
  714. return lhs * rhs
  715. case ast.DIV:
  716. if v.IntegerFloatDivision {
  717. if rhs == 0 {
  718. return fmt.Errorf("divided by zero")
  719. }
  720. return float64(lhs) / float64(rhs)
  721. }
  722. if rhs == 0 {
  723. return fmt.Errorf("divided by zero")
  724. }
  725. return lhs / rhs
  726. case ast.MOD:
  727. if rhs == 0 {
  728. return fmt.Errorf("divided by zero")
  729. }
  730. return lhs % rhs
  731. case ast.BITWISE_AND:
  732. return lhs & rhs
  733. case ast.BITWISE_OR:
  734. return lhs | rhs
  735. case ast.BITWISE_XOR:
  736. return lhs ^ rhs
  737. default:
  738. return invalidOpError(lhs, op, rhs)
  739. }
  740. case uint64:
  741. switch op {
  742. case ast.EQ:
  743. return uint64(lhs) == rhs
  744. case ast.NEQ:
  745. return uint64(lhs) != rhs
  746. case ast.LT:
  747. if lhs < 0 {
  748. return true
  749. }
  750. return uint64(lhs) < rhs
  751. case ast.LTE:
  752. if lhs < 0 {
  753. return true
  754. }
  755. return uint64(lhs) <= rhs
  756. case ast.GT:
  757. if lhs < 0 {
  758. return false
  759. }
  760. return uint64(lhs) > rhs
  761. case ast.GTE:
  762. if lhs < 0 {
  763. return false
  764. }
  765. return uint64(lhs) >= rhs
  766. case ast.ADD:
  767. return uint64(lhs) + rhs
  768. case ast.SUB:
  769. return uint64(lhs) - rhs
  770. case ast.MUL:
  771. return uint64(lhs) * rhs
  772. case ast.DIV:
  773. if rhs == 0 {
  774. return fmt.Errorf("divided by zero")
  775. }
  776. return uint64(lhs) / rhs
  777. case ast.MOD:
  778. if rhs == 0 {
  779. return fmt.Errorf("divided by zero")
  780. }
  781. return uint64(lhs) % rhs
  782. case ast.BITWISE_AND:
  783. return uint64(lhs) & rhs
  784. case ast.BITWISE_OR:
  785. return uint64(lhs) | rhs
  786. case ast.BITWISE_XOR:
  787. return uint64(lhs) ^ rhs
  788. default:
  789. return invalidOpError(lhs, op, rhs)
  790. }
  791. default:
  792. return invalidOpError(lhs, op, rhs)
  793. }
  794. case uint64:
  795. // Try as a float64 to see if a float cast is required.
  796. switch rhs := rhs.(type) {
  797. case float64:
  798. lhs := float64(lhs)
  799. switch op {
  800. case ast.EQ:
  801. return lhs == rhs
  802. case ast.NEQ:
  803. return lhs != rhs
  804. case ast.LT:
  805. return lhs < rhs
  806. case ast.LTE:
  807. return lhs <= rhs
  808. case ast.GT:
  809. return lhs > rhs
  810. case ast.GTE:
  811. return lhs >= rhs
  812. case ast.ADD:
  813. return lhs + rhs
  814. case ast.SUB:
  815. return lhs - rhs
  816. case ast.MUL:
  817. return lhs * rhs
  818. case ast.DIV:
  819. if rhs == 0 {
  820. return fmt.Errorf("divided by zero")
  821. }
  822. return lhs / rhs
  823. case ast.MOD:
  824. if rhs == 0 {
  825. return fmt.Errorf("divided by zero")
  826. }
  827. return math.Mod(lhs, rhs)
  828. default:
  829. return invalidOpError(lhs, op, rhs)
  830. }
  831. case int64:
  832. switch op {
  833. case ast.EQ:
  834. return lhs == uint64(rhs)
  835. case ast.NEQ:
  836. return lhs != uint64(rhs)
  837. case ast.LT:
  838. if rhs < 0 {
  839. return false
  840. }
  841. return lhs < uint64(rhs)
  842. case ast.LTE:
  843. if rhs < 0 {
  844. return false
  845. }
  846. return lhs <= uint64(rhs)
  847. case ast.GT:
  848. if rhs < 0 {
  849. return true
  850. }
  851. return lhs > uint64(rhs)
  852. case ast.GTE:
  853. if rhs < 0 {
  854. return true
  855. }
  856. return lhs >= uint64(rhs)
  857. case ast.ADD:
  858. return lhs + uint64(rhs)
  859. case ast.SUB:
  860. return lhs - uint64(rhs)
  861. case ast.MUL:
  862. return lhs * uint64(rhs)
  863. case ast.DIV:
  864. if rhs == 0 {
  865. return fmt.Errorf("divided by zero")
  866. }
  867. return lhs / uint64(rhs)
  868. case ast.MOD:
  869. if rhs == 0 {
  870. return fmt.Errorf("divided by zero")
  871. }
  872. return lhs % uint64(rhs)
  873. case ast.BITWISE_AND:
  874. return lhs & uint64(rhs)
  875. case ast.BITWISE_OR:
  876. return lhs | uint64(rhs)
  877. case ast.BITWISE_XOR:
  878. return lhs ^ uint64(rhs)
  879. default:
  880. return invalidOpError(lhs, op, rhs)
  881. }
  882. case uint64:
  883. switch op {
  884. case ast.EQ:
  885. return lhs == rhs
  886. case ast.NEQ:
  887. return lhs != rhs
  888. case ast.LT:
  889. return lhs < rhs
  890. case ast.LTE:
  891. return lhs <= rhs
  892. case ast.GT:
  893. return lhs > rhs
  894. case ast.GTE:
  895. return lhs >= rhs
  896. case ast.ADD:
  897. return lhs + rhs
  898. case ast.SUB:
  899. return lhs - rhs
  900. case ast.MUL:
  901. return lhs * rhs
  902. case ast.DIV:
  903. if rhs == 0 {
  904. return fmt.Errorf("divided by zero")
  905. }
  906. return lhs / rhs
  907. case ast.MOD:
  908. if rhs == 0 {
  909. return fmt.Errorf("divided by zero")
  910. }
  911. return lhs % rhs
  912. case ast.BITWISE_AND:
  913. return lhs & rhs
  914. case ast.BITWISE_OR:
  915. return lhs | rhs
  916. case ast.BITWISE_XOR:
  917. return lhs ^ rhs
  918. default:
  919. return invalidOpError(lhs, op, rhs)
  920. }
  921. default:
  922. return invalidOpError(lhs, op, rhs)
  923. }
  924. case string:
  925. rhss, ok := rhs.(string)
  926. if !ok {
  927. return invalidOpError(lhs, op, rhs)
  928. }
  929. switch op {
  930. case ast.EQ:
  931. return lhs == rhss
  932. case ast.NEQ:
  933. return lhs != rhss
  934. case ast.LT:
  935. return lhs < rhss
  936. case ast.LTE:
  937. return lhs <= rhss
  938. case ast.GT:
  939. return lhs > rhss
  940. case ast.GTE:
  941. return lhs >= rhss
  942. default:
  943. return invalidOpError(lhs, op, rhs)
  944. }
  945. case time.Time:
  946. rt, err := cast.InterfaceToTime(rhs, "")
  947. if err != nil {
  948. return invalidOpError(lhs, op, rhs)
  949. }
  950. switch op {
  951. case ast.EQ:
  952. return lhs.Equal(rt)
  953. case ast.NEQ:
  954. return !lhs.Equal(rt)
  955. case ast.LT:
  956. return lhs.Before(rt)
  957. case ast.LTE:
  958. return lhs.Before(rt) || lhs.Equal(rt)
  959. case ast.GT:
  960. return lhs.After(rt)
  961. case ast.GTE:
  962. return lhs.After(rt) || lhs.Equal(rt)
  963. default:
  964. return invalidOpError(lhs, op, rhs)
  965. }
  966. default:
  967. return invalidOpError(lhs, op, rhs)
  968. }
  969. }
  970. /*
  971. * Helper functions
  972. */
  973. type BracketEvalResult struct {
  974. Start, End int
  975. }
  976. func (ber *BracketEvalResult) isIndex() bool {
  977. return ber.Start == ber.End
  978. }
  979. func isSliceOrArray(v interface{}) bool {
  980. kind := reflect.ValueOf(v).Kind()
  981. return kind == reflect.Array || kind == reflect.Slice
  982. }
  983. func isSetOperator(op ast.Token) bool {
  984. return op == ast.IN || op == ast.NOTIN
  985. }
  986. func invalidOpError(lhs interface{}, op ast.Token, rhs interface{}) error {
  987. return fmt.Errorf("invalid operation %[1]T(%[1]v) %s %[3]T(%[3]v)", lhs, ast.Tokens[op], rhs)
  988. }
  989. func convertNum(para interface{}) interface{} {
  990. if isInt(para) {
  991. para = toInt64(para)
  992. } else if isFloat(para) {
  993. para = toFloat64(para)
  994. }
  995. return para
  996. }
  997. func isInt(para interface{}) bool {
  998. switch para.(type) {
  999. case int:
  1000. return true
  1001. case int8:
  1002. return true
  1003. case int16:
  1004. return true
  1005. case int32:
  1006. return true
  1007. case int64:
  1008. return true
  1009. }
  1010. return false
  1011. }
  1012. func toInt64(para interface{}) int64 {
  1013. if v, ok := para.(int); ok {
  1014. return int64(v)
  1015. } else if v, ok := para.(int8); ok {
  1016. return int64(v)
  1017. } else if v, ok := para.(int16); ok {
  1018. return int64(v)
  1019. } else if v, ok := para.(int32); ok {
  1020. return int64(v)
  1021. } else if v, ok := para.(int64); ok {
  1022. return v
  1023. }
  1024. return 0
  1025. }
  1026. func isFloat(para interface{}) bool {
  1027. switch para.(type) {
  1028. case float32:
  1029. return true
  1030. case float64:
  1031. return true
  1032. }
  1033. return false
  1034. }
  1035. func toFloat64(para interface{}) float64 {
  1036. if v, ok := para.(float32); ok {
  1037. return float64(v)
  1038. } else if v, ok := para.(float64); ok {
  1039. return v
  1040. }
  1041. return 0
  1042. }