valuer.go 23 KB

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