valuer.go 25 KB

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