valuer.go 24 KB

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