valuer.go 25 KB

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