valuer.go 27 KB

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