valuer.go 24 KB

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