valuer.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. return nil
  197. }
  198. type EvalResultMessage struct {
  199. Emitter string
  200. Result interface{}
  201. Message Message
  202. }
  203. type ResultsAndMessages []EvalResultMessage
  204. // Eval evaluates expr against a map.
  205. func Eval(expr ast.Expr, m Valuer) interface{} {
  206. eval := ValuerEval{Valuer: m}
  207. return eval.Eval(expr)
  208. }
  209. // ValuerEval will evaluate an expression using the Valuer.
  210. type ValuerEval struct {
  211. Valuer Valuer
  212. // IntegerFloatDivision will set the eval system to treat
  213. // a division between two integers as a floating point division.
  214. IntegerFloatDivision bool
  215. }
  216. // MultiValuer returns a Valuer that iterates over multiple Valuer instances
  217. // to find a match.
  218. func MultiValuer(valuers ...Valuer) Valuer {
  219. return multiValuer(valuers)
  220. }
  221. type multiValuer []Valuer
  222. func (a multiValuer) Value(key string) (interface{}, bool) {
  223. for _, valuer := range a {
  224. if v, ok := valuer.Value(key); ok {
  225. return v, true
  226. }
  227. }
  228. return nil, false
  229. }
  230. func (a multiValuer) Meta(key string) (interface{}, bool) {
  231. for _, valuer := range a {
  232. if v, ok := valuer.Meta(key); ok {
  233. return v, true
  234. }
  235. }
  236. return nil, false
  237. }
  238. func (a multiValuer) AppendAlias(key string, value interface{}) bool {
  239. for _, valuer := range a {
  240. if ok := valuer.AppendAlias(key, value); ok {
  241. return true
  242. }
  243. }
  244. return false
  245. }
  246. func (a multiValuer) Call(name string, args []interface{}) (interface{}, bool) {
  247. for _, valuer := range a {
  248. if valuer, ok := valuer.(CallValuer); ok {
  249. if v, ok := valuer.Call(name, args); ok {
  250. return v, true
  251. } else {
  252. return fmt.Errorf("call func %s error: %v", name, v), false
  253. }
  254. }
  255. }
  256. return nil, false
  257. }
  258. type multiAggregateValuer struct {
  259. data AggregateData
  260. multiValuer
  261. singleCallValuer CallValuer
  262. }
  263. func MultiAggregateValuer(data AggregateData, singleCallValuer CallValuer, valuers ...Valuer) Valuer {
  264. return &multiAggregateValuer{
  265. data: data,
  266. multiValuer: valuers,
  267. singleCallValuer: singleCallValuer,
  268. }
  269. }
  270. func (a *multiAggregateValuer) Call(name string, args []interface{}) (interface{}, bool) {
  271. // assume the aggFuncMap already cache the custom agg funcs in IsAggFunc()
  272. isAgg := ast.FuncFinderSingleton().FuncType(name) == ast.AggFunc
  273. for _, valuer := range a.multiValuer {
  274. if a, ok := valuer.(AggregateCallValuer); ok && isAgg {
  275. if v, ok := a.Call(name, args); ok {
  276. return v, true
  277. } else {
  278. return fmt.Errorf("call func %s error: %v", name, v), false
  279. }
  280. } else if c, ok := valuer.(CallValuer); ok && !isAgg {
  281. if v, ok := c.Call(name, args); ok {
  282. return v, true
  283. }
  284. }
  285. }
  286. return nil, false
  287. }
  288. func (a *multiAggregateValuer) GetAllTuples() AggregateData {
  289. return a.data
  290. }
  291. func (a *multiAggregateValuer) GetSingleCallValuer() CallValuer {
  292. return a.singleCallValuer
  293. }
  294. type BracketEvalResult struct {
  295. Start, End int
  296. }
  297. func (ber *BracketEvalResult) isIndex() bool {
  298. return ber.Start == ber.End
  299. }
  300. // Eval evaluates an expression and returns a value.
  301. func (v *ValuerEval) Eval(expr ast.Expr) interface{} {
  302. if expr == nil {
  303. return nil
  304. }
  305. switch expr := expr.(type) {
  306. case *ast.BinaryExpr:
  307. return v.evalBinaryExpr(expr)
  308. case *ast.IntegerLiteral:
  309. return expr.Val
  310. case *ast.NumberLiteral:
  311. return expr.Val
  312. case *ast.ParenExpr:
  313. return v.Eval(expr.Expr)
  314. case *ast.StringLiteral:
  315. return expr.Val
  316. case *ast.BooleanLiteral:
  317. return expr.Val
  318. case *ast.ColonExpr:
  319. return &BracketEvalResult{Start: expr.Start, End: expr.End}
  320. case *ast.IndexExpr:
  321. return &BracketEvalResult{Start: expr.Index, End: expr.Index}
  322. case *ast.Call:
  323. if valuer, ok := v.Valuer.(CallValuer); ok {
  324. switch expr.Name {
  325. case "window_start", "window_end":
  326. if aggreValuer, ok := valuer.(AggregateCallValuer); ok {
  327. ad := aggreValuer.GetAllTuples()
  328. if expr.Name == "window_start" {
  329. return ad.GetWindowStart()
  330. } else {
  331. return ad.GetWindowEnd()
  332. }
  333. }
  334. default:
  335. var args []interface{}
  336. if len(expr.Args) > 0 {
  337. args = make([]interface{}, len(expr.Args))
  338. for i, arg := range expr.Args {
  339. if aggreValuer, ok := valuer.(AggregateCallValuer); ast.FuncFinderSingleton().IsAggFunc(expr) && ok {
  340. args[i] = aggreValuer.GetAllTuples().AggregateEval(arg, aggreValuer.GetSingleCallValuer())
  341. } else {
  342. args[i] = v.Eval(arg)
  343. if _, ok := args[i].(error); ok {
  344. return args[i]
  345. }
  346. }
  347. }
  348. }
  349. val, _ := valuer.Call(expr.Name, args)
  350. return val
  351. }
  352. }
  353. return nil
  354. case *ast.FieldRef:
  355. var n string
  356. if expr.IsAlias() { // alias is renamed internally to avoid accidentally evaled as a col with the same name
  357. n = fmt.Sprintf("%s%s", PRIVATE_PREFIX, expr.Name)
  358. } else if expr.StreamName == ast.DefaultStream {
  359. n = expr.Name
  360. } else {
  361. n = fmt.Sprintf("%s%s%s", string(expr.StreamName), ast.COLUMN_SEPARATOR, expr.Name)
  362. }
  363. if n != "" {
  364. val, ok := v.Valuer.Value(n)
  365. if ok {
  366. return val
  367. }
  368. }
  369. if expr.IsAlias() {
  370. r := v.Eval(expr.Expression)
  371. v.Valuer.AppendAlias(expr.Name, r)
  372. return r
  373. }
  374. return nil
  375. case *ast.MetaRef:
  376. if expr.StreamName == "" || expr.StreamName == ast.DefaultStream {
  377. val, _ := v.Valuer.Meta(expr.Name)
  378. return val
  379. } else {
  380. //The field specified with stream source
  381. val, _ := v.Valuer.Meta(string(expr.StreamName) + ast.COLUMN_SEPARATOR + expr.Name)
  382. return val
  383. }
  384. case *ast.Wildcard:
  385. val, _ := v.Valuer.Value("")
  386. return val
  387. case *ast.CaseExpr:
  388. return v.evalCase(expr)
  389. default:
  390. return nil
  391. }
  392. }
  393. func (v *ValuerEval) evalBinaryExpr(expr *ast.BinaryExpr) interface{} {
  394. lhs := v.Eval(expr.LHS)
  395. switch val := lhs.(type) {
  396. case map[string]interface{}:
  397. return v.evalJsonExpr(val, expr.OP, expr.RHS)
  398. case Message:
  399. return v.evalJsonExpr(map[string]interface{}(val), expr.OP, expr.RHS)
  400. case error:
  401. return val
  402. }
  403. // shortcut for bool
  404. switch expr.OP {
  405. case ast.AND:
  406. if bv, ok := lhs.(bool); ok && !bv {
  407. return false
  408. }
  409. case ast.OR:
  410. if bv, ok := lhs.(bool); ok && bv {
  411. return true
  412. }
  413. }
  414. if isSliceOrArray(lhs) {
  415. return v.evalJsonExpr(lhs, expr.OP, expr.RHS)
  416. }
  417. rhs := v.Eval(expr.RHS)
  418. if _, ok := rhs.(error); ok {
  419. return rhs
  420. }
  421. return v.simpleDataEval(lhs, rhs, expr.OP)
  422. }
  423. func (v *ValuerEval) evalCase(expr *ast.CaseExpr) interface{} {
  424. if expr.Value != nil { // compare value to all when clause
  425. ev := v.Eval(expr.Value)
  426. for _, w := range expr.WhenClauses {
  427. wv := v.Eval(w.Expr)
  428. switch r := v.simpleDataEval(ev, wv, ast.EQ).(type) {
  429. case error:
  430. return fmt.Errorf("evaluate case expression error: %s", r)
  431. case bool:
  432. if r {
  433. return v.Eval(w.Result)
  434. }
  435. }
  436. }
  437. } else {
  438. for _, w := range expr.WhenClauses {
  439. switch r := v.Eval(w.Expr).(type) {
  440. case error:
  441. return fmt.Errorf("evaluate case expression error: %s", r)
  442. case bool:
  443. if r {
  444. return v.Eval(w.Result)
  445. }
  446. }
  447. }
  448. }
  449. if expr.ElseClause != nil {
  450. return v.Eval(expr.ElseClause)
  451. }
  452. return nil
  453. }
  454. func isSliceOrArray(v interface{}) bool {
  455. kind := reflect.ValueOf(v).Kind()
  456. return kind == reflect.Array || kind == reflect.Slice
  457. }
  458. func (v *ValuerEval) evalJsonExpr(result interface{}, op ast.Token, expr ast.Expr) interface{} {
  459. switch op {
  460. case ast.ARROW:
  461. if val, ok := result.(map[string]interface{}); ok {
  462. switch e := expr.(type) {
  463. case *ast.FieldRef, *ast.MetaRef:
  464. ve := &ValuerEval{Valuer: Message(val)}
  465. return ve.Eval(e)
  466. default:
  467. return fmt.Errorf("the right expression is not a field reference node")
  468. }
  469. } else {
  470. return fmt.Errorf("the result %v is not a type of map[string]interface{}", result)
  471. }
  472. case ast.SUBSET:
  473. if isSliceOrArray(result) {
  474. return v.subset(result, expr)
  475. } else {
  476. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  477. }
  478. default:
  479. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  480. }
  481. }
  482. func (v *ValuerEval) subset(result interface{}, expr ast.Expr) interface{} {
  483. val := reflect.ValueOf(result)
  484. ber := v.Eval(expr)
  485. if berVal, ok1 := ber.(*BracketEvalResult); ok1 {
  486. if berVal.isIndex() {
  487. if 0 > berVal.Start {
  488. if 0 > berVal.Start+val.Len() {
  489. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  490. }
  491. berVal.Start += val.Len()
  492. } else if berVal.Start >= val.Len() {
  493. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  494. }
  495. return val.Index(berVal.Start).Interface()
  496. } else {
  497. if 0 > berVal.Start {
  498. if 0 > berVal.Start+val.Len() {
  499. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  500. }
  501. berVal.Start += val.Len()
  502. } else if berVal.Start >= val.Len() {
  503. return fmt.Errorf("start value is out of index: %d of %d", berVal.Start, val.Len())
  504. }
  505. if math.MinInt32 == berVal.End {
  506. berVal.End = val.Len()
  507. } else if 0 > berVal.End {
  508. if 0 > berVal.End+val.Len() {
  509. return fmt.Errorf("out of index: %d of %d", berVal.End, val.Len())
  510. }
  511. berVal.End += val.Len()
  512. } else if berVal.End > val.Len() {
  513. return fmt.Errorf("end value is out of index: %d of %d", berVal.End, val.Len())
  514. } else if berVal.Start >= berVal.End {
  515. return fmt.Errorf("start cannot be greater than end. start:%d end:%d", berVal.Start, berVal.End)
  516. }
  517. return val.Slice(berVal.Start, berVal.End).Interface()
  518. }
  519. } else {
  520. return fmt.Errorf("invalid evaluation result - %v", berVal)
  521. }
  522. }
  523. //lhs and rhs are non-nil
  524. func (v *ValuerEval) simpleDataEval(lhs, rhs interface{}, op ast.Token) interface{} {
  525. if lhs == nil || rhs == nil {
  526. switch op {
  527. case ast.EQ, ast.LTE, ast.GTE:
  528. if lhs == nil && rhs == nil {
  529. return true
  530. } else {
  531. return false
  532. }
  533. case ast.NEQ:
  534. if lhs == nil && rhs == nil {
  535. return false
  536. } else {
  537. return true
  538. }
  539. case ast.LT, ast.GT:
  540. return false
  541. default:
  542. return nil
  543. }
  544. }
  545. lhs = convertNum(lhs)
  546. rhs = convertNum(rhs)
  547. // Evaluate if both sides are simple types.
  548. switch lhs := lhs.(type) {
  549. case bool:
  550. rhs, ok := rhs.(bool)
  551. if !ok {
  552. return invalidOpError(lhs, op, rhs)
  553. }
  554. switch op {
  555. case ast.AND:
  556. return lhs && rhs
  557. case ast.OR:
  558. return lhs || rhs
  559. case ast.BITWISE_AND:
  560. return lhs && rhs
  561. case ast.BITWISE_OR:
  562. return lhs || rhs
  563. case ast.BITWISE_XOR:
  564. return lhs != rhs
  565. case ast.EQ:
  566. return lhs == rhs
  567. case ast.NEQ:
  568. return lhs != rhs
  569. default:
  570. return invalidOpError(lhs, op, rhs)
  571. }
  572. case float64:
  573. // Try the rhs as a float64, int64, or uint64
  574. rhsf, ok := rhs.(float64)
  575. if !ok {
  576. switch val := rhs.(type) {
  577. case int64:
  578. rhsf, ok = float64(val), true
  579. case uint64:
  580. rhsf, ok = float64(val), true
  581. }
  582. }
  583. if !ok {
  584. return invalidOpError(lhs, op, rhs)
  585. }
  586. rhs := rhsf
  587. switch op {
  588. case ast.EQ:
  589. return lhs == rhs
  590. case ast.NEQ:
  591. return lhs != rhs
  592. case ast.LT:
  593. return lhs < rhs
  594. case ast.LTE:
  595. return lhs <= rhs
  596. case ast.GT:
  597. return lhs > rhs
  598. case ast.GTE:
  599. return lhs >= rhs
  600. case ast.ADD:
  601. return lhs + rhs
  602. case ast.SUB:
  603. return lhs - rhs
  604. case ast.MUL:
  605. return lhs * rhs
  606. case ast.DIV:
  607. if rhs == 0 {
  608. return fmt.Errorf("divided by zero")
  609. }
  610. return lhs / rhs
  611. case ast.MOD:
  612. if rhs == 0 {
  613. return fmt.Errorf("divided by zero")
  614. }
  615. return math.Mod(lhs, rhs)
  616. default:
  617. return invalidOpError(lhs, op, rhs)
  618. }
  619. case int64:
  620. // Try as a float64 to see if a float cast is required.
  621. switch rhs := rhs.(type) {
  622. case float64:
  623. lhs := float64(lhs)
  624. switch op {
  625. case ast.EQ:
  626. return lhs == rhs
  627. case ast.NEQ:
  628. return lhs != rhs
  629. case ast.LT:
  630. return lhs < rhs
  631. case ast.LTE:
  632. return lhs <= rhs
  633. case ast.GT:
  634. return lhs > rhs
  635. case ast.GTE:
  636. return lhs >= rhs
  637. case ast.ADD:
  638. return lhs + rhs
  639. case ast.SUB:
  640. return lhs - rhs
  641. case ast.MUL:
  642. return lhs * rhs
  643. case ast.DIV:
  644. if rhs == 0 {
  645. return fmt.Errorf("divided by zero")
  646. }
  647. return lhs / rhs
  648. case ast.MOD:
  649. if rhs == 0 {
  650. return fmt.Errorf("divided by zero")
  651. }
  652. return math.Mod(lhs, rhs)
  653. default:
  654. return invalidOpError(lhs, op, rhs)
  655. }
  656. case int64:
  657. switch op {
  658. case ast.EQ:
  659. return lhs == rhs
  660. case ast.NEQ:
  661. return lhs != rhs
  662. case ast.LT:
  663. return lhs < rhs
  664. case ast.LTE:
  665. return lhs <= rhs
  666. case ast.GT:
  667. return lhs > rhs
  668. case ast.GTE:
  669. return lhs >= rhs
  670. case ast.ADD:
  671. return lhs + rhs
  672. case ast.SUB:
  673. return lhs - rhs
  674. case ast.MUL:
  675. return lhs * rhs
  676. case ast.DIV:
  677. if v.IntegerFloatDivision {
  678. if rhs == 0 {
  679. return fmt.Errorf("divided by zero")
  680. }
  681. return float64(lhs) / float64(rhs)
  682. }
  683. if rhs == 0 {
  684. return fmt.Errorf("divided by zero")
  685. }
  686. return lhs / rhs
  687. case ast.MOD:
  688. if rhs == 0 {
  689. return fmt.Errorf("divided by zero")
  690. }
  691. return lhs % rhs
  692. case ast.BITWISE_AND:
  693. return lhs & rhs
  694. case ast.BITWISE_OR:
  695. return lhs | rhs
  696. case ast.BITWISE_XOR:
  697. return lhs ^ rhs
  698. default:
  699. return invalidOpError(lhs, op, rhs)
  700. }
  701. case uint64:
  702. switch op {
  703. case ast.EQ:
  704. return uint64(lhs) == rhs
  705. case ast.NEQ:
  706. return uint64(lhs) != rhs
  707. case ast.LT:
  708. if lhs < 0 {
  709. return true
  710. }
  711. return uint64(lhs) < rhs
  712. case ast.LTE:
  713. if lhs < 0 {
  714. return true
  715. }
  716. return uint64(lhs) <= rhs
  717. case ast.GT:
  718. if lhs < 0 {
  719. return false
  720. }
  721. return uint64(lhs) > rhs
  722. case ast.GTE:
  723. if lhs < 0 {
  724. return false
  725. }
  726. return uint64(lhs) >= rhs
  727. case ast.ADD:
  728. return uint64(lhs) + rhs
  729. case ast.SUB:
  730. return uint64(lhs) - rhs
  731. case ast.MUL:
  732. return uint64(lhs) * rhs
  733. case ast.DIV:
  734. if rhs == 0 {
  735. return fmt.Errorf("divided by zero")
  736. }
  737. return uint64(lhs) / rhs
  738. case ast.MOD:
  739. if rhs == 0 {
  740. return fmt.Errorf("divided by zero")
  741. }
  742. return uint64(lhs) % rhs
  743. case ast.BITWISE_AND:
  744. return uint64(lhs) & rhs
  745. case ast.BITWISE_OR:
  746. return uint64(lhs) | rhs
  747. case ast.BITWISE_XOR:
  748. return uint64(lhs) ^ rhs
  749. default:
  750. return invalidOpError(lhs, op, rhs)
  751. }
  752. default:
  753. return invalidOpError(lhs, op, rhs)
  754. }
  755. case uint64:
  756. // Try as a float64 to see if a float cast is required.
  757. switch rhs := rhs.(type) {
  758. case float64:
  759. lhs := float64(lhs)
  760. switch op {
  761. case ast.EQ:
  762. return lhs == rhs
  763. case ast.NEQ:
  764. return lhs != rhs
  765. case ast.LT:
  766. return lhs < rhs
  767. case ast.LTE:
  768. return lhs <= rhs
  769. case ast.GT:
  770. return lhs > rhs
  771. case ast.GTE:
  772. return lhs >= rhs
  773. case ast.ADD:
  774. return lhs + rhs
  775. case ast.SUB:
  776. return lhs - rhs
  777. case ast.MUL:
  778. return lhs * rhs
  779. case ast.DIV:
  780. if rhs == 0 {
  781. return fmt.Errorf("divided by zero")
  782. }
  783. return lhs / rhs
  784. case ast.MOD:
  785. if rhs == 0 {
  786. return fmt.Errorf("divided by zero")
  787. }
  788. return math.Mod(lhs, rhs)
  789. default:
  790. return invalidOpError(lhs, op, rhs)
  791. }
  792. case int64:
  793. switch op {
  794. case ast.EQ:
  795. return lhs == uint64(rhs)
  796. case ast.NEQ:
  797. return lhs != uint64(rhs)
  798. case ast.LT:
  799. if rhs < 0 {
  800. return false
  801. }
  802. return lhs < uint64(rhs)
  803. case ast.LTE:
  804. if rhs < 0 {
  805. return false
  806. }
  807. return lhs <= uint64(rhs)
  808. case ast.GT:
  809. if rhs < 0 {
  810. return true
  811. }
  812. return lhs > uint64(rhs)
  813. case ast.GTE:
  814. if rhs < 0 {
  815. return true
  816. }
  817. return lhs >= uint64(rhs)
  818. case ast.ADD:
  819. return lhs + uint64(rhs)
  820. case ast.SUB:
  821. return lhs - uint64(rhs)
  822. case ast.MUL:
  823. return lhs * uint64(rhs)
  824. case ast.DIV:
  825. if rhs == 0 {
  826. return fmt.Errorf("divided by zero")
  827. }
  828. return lhs / uint64(rhs)
  829. case ast.MOD:
  830. if rhs == 0 {
  831. return fmt.Errorf("divided by zero")
  832. }
  833. return lhs % uint64(rhs)
  834. case ast.BITWISE_AND:
  835. return lhs & uint64(rhs)
  836. case ast.BITWISE_OR:
  837. return lhs | uint64(rhs)
  838. case ast.BITWISE_XOR:
  839. return lhs ^ uint64(rhs)
  840. default:
  841. return invalidOpError(lhs, op, rhs)
  842. }
  843. case uint64:
  844. switch op {
  845. case ast.EQ:
  846. return lhs == rhs
  847. case ast.NEQ:
  848. return lhs != rhs
  849. case ast.LT:
  850. return lhs < rhs
  851. case ast.LTE:
  852. return lhs <= rhs
  853. case ast.GT:
  854. return lhs > rhs
  855. case ast.GTE:
  856. return lhs >= rhs
  857. case ast.ADD:
  858. return lhs + rhs
  859. case ast.SUB:
  860. return lhs - rhs
  861. case ast.MUL:
  862. return lhs * rhs
  863. case ast.DIV:
  864. if rhs == 0 {
  865. return fmt.Errorf("divided by zero")
  866. }
  867. return lhs / rhs
  868. case ast.MOD:
  869. if rhs == 0 {
  870. return fmt.Errorf("divided by zero")
  871. }
  872. return lhs % rhs
  873. case ast.BITWISE_AND:
  874. return lhs & rhs
  875. case ast.BITWISE_OR:
  876. return lhs | rhs
  877. case ast.BITWISE_XOR:
  878. return lhs ^ rhs
  879. default:
  880. return invalidOpError(lhs, op, rhs)
  881. }
  882. default:
  883. return invalidOpError(lhs, op, rhs)
  884. }
  885. case string:
  886. rhss, ok := rhs.(string)
  887. if !ok {
  888. return invalidOpError(lhs, op, rhs)
  889. }
  890. switch op {
  891. case ast.EQ:
  892. return lhs == rhss
  893. case ast.NEQ:
  894. return lhs != rhss
  895. case ast.LT:
  896. return lhs < rhss
  897. case ast.LTE:
  898. return lhs <= rhss
  899. case ast.GT:
  900. return lhs > rhss
  901. case ast.GTE:
  902. return lhs >= rhss
  903. default:
  904. return invalidOpError(lhs, op, rhs)
  905. }
  906. case time.Time:
  907. rt, err := cast.InterfaceToTime(rhs, "")
  908. if err != nil {
  909. return invalidOpError(lhs, op, rhs)
  910. }
  911. switch op {
  912. case ast.EQ:
  913. return lhs.Equal(rt)
  914. case ast.NEQ:
  915. return !lhs.Equal(rt)
  916. case ast.LT:
  917. return lhs.Before(rt)
  918. case ast.LTE:
  919. return lhs.Before(rt) || lhs.Equal(rt)
  920. case ast.GT:
  921. return lhs.After(rt)
  922. case ast.GTE:
  923. return lhs.After(rt) || lhs.Equal(rt)
  924. default:
  925. return invalidOpError(lhs, op, rhs)
  926. }
  927. default:
  928. return invalidOpError(lhs, op, rhs)
  929. }
  930. return invalidOpError(lhs, op, rhs)
  931. }
  932. func invalidOpError(lhs interface{}, op ast.Token, rhs interface{}) error {
  933. return fmt.Errorf("invalid operation %[1]T(%[1]v) %s %[3]T(%[3]v)", lhs, ast.Tokens[op], rhs)
  934. }
  935. func convertNum(para interface{}) interface{} {
  936. if isInt(para) {
  937. para = toInt64(para)
  938. } else if isFloat(para) {
  939. para = toFloat64(para)
  940. }
  941. return para
  942. }
  943. func isInt(para interface{}) bool {
  944. switch para.(type) {
  945. case int:
  946. return true
  947. case int8:
  948. return true
  949. case int16:
  950. return true
  951. case int32:
  952. return true
  953. case int64:
  954. return true
  955. }
  956. return false
  957. }
  958. func toInt64(para interface{}) int64 {
  959. if v, ok := para.(int); ok {
  960. return int64(v)
  961. } else if v, ok := para.(int8); ok {
  962. return int64(v)
  963. } else if v, ok := para.(int16); ok {
  964. return int64(v)
  965. } else if v, ok := para.(int32); ok {
  966. return int64(v)
  967. } else if v, ok := para.(int64); ok {
  968. return v
  969. }
  970. return 0
  971. }
  972. func isFloat(para interface{}) bool {
  973. switch para.(type) {
  974. case float32:
  975. return true
  976. case float64:
  977. return true
  978. }
  979. return false
  980. }
  981. func toFloat64(para interface{}) float64 {
  982. if v, ok := para.(float32); ok {
  983. return float64(v)
  984. } else if v, ok := para.(float64); ok {
  985. return v
  986. }
  987. return 0
  988. }