valuer.go 25 KB

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