valuer.go 24 KB

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