valuer.go 26 KB

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