ast.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  1. package xsql
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/emqx/kuiper/common"
  6. "math"
  7. "reflect"
  8. "sort"
  9. "strings"
  10. "time"
  11. )
  12. type Node interface {
  13. node()
  14. }
  15. type NameNode interface {
  16. Node
  17. GetName() string
  18. }
  19. type Expr interface {
  20. Node
  21. expr()
  22. }
  23. type Field struct {
  24. Name string
  25. AName string
  26. Expr
  27. }
  28. type Source interface {
  29. Node
  30. source()
  31. }
  32. type Sources []Source
  33. func (ss Sources) node() {}
  34. type Table struct {
  35. Name string
  36. Alias string
  37. }
  38. func (t *Table) source() {}
  39. func (ss *Table) node() {}
  40. type JoinType int
  41. const (
  42. LEFT_JOIN JoinType = iota
  43. INNER_JOIN
  44. RIGHT_JOIN
  45. FULL_JOIN
  46. CROSS_JOIN
  47. )
  48. var AsteriskExpr = StringLiteral{Val: "*"}
  49. var COLUMN_SEPARATOR = tokens[COLSEP]
  50. type Join struct {
  51. Name string
  52. Alias string
  53. JoinType JoinType
  54. Expr Expr
  55. }
  56. func (j *Join) source() {}
  57. func (ss *Join) node() {}
  58. type Joins []Join
  59. func (ss Joins) node() {}
  60. type Statement interface {
  61. Stmt()
  62. Node
  63. }
  64. type SelectStatement struct {
  65. Fields Fields
  66. Sources Sources
  67. Joins Joins
  68. Condition Expr
  69. Dimensions Dimensions
  70. Having Expr
  71. SortFields SortFields
  72. }
  73. func (ss *SelectStatement) Stmt() {}
  74. func (ss *SelectStatement) node() {}
  75. type Literal interface {
  76. Expr
  77. literal()
  78. }
  79. type ParenExpr struct {
  80. Expr Expr
  81. }
  82. type ArrowExpr struct {
  83. Expr Expr
  84. }
  85. type BracketExpr struct {
  86. Expr Expr
  87. }
  88. type ColonExpr struct {
  89. Start int
  90. End int
  91. }
  92. type IndexExpr struct {
  93. Index int
  94. }
  95. type BooleanLiteral struct {
  96. Val bool
  97. }
  98. type TimeLiteral struct {
  99. Val Token
  100. }
  101. type IntegerLiteral struct {
  102. Val int
  103. }
  104. type StringLiteral struct {
  105. Val string
  106. }
  107. type NumberLiteral struct {
  108. Val float64
  109. }
  110. type Wildcard struct {
  111. Token Token
  112. }
  113. type Dimension struct {
  114. Expr Expr
  115. }
  116. type SortField struct {
  117. Name string
  118. Ascending bool
  119. }
  120. type SortFields []SortField
  121. type Dimensions []Dimension
  122. func (f *Field) expr() {}
  123. func (f *Field) node() {}
  124. func (pe *ParenExpr) expr() {}
  125. func (pe *ParenExpr) node() {}
  126. func (ae *ArrowExpr) expr() {}
  127. func (ae *ArrowExpr) node() {}
  128. func (be *BracketExpr) expr() {}
  129. func (be *BracketExpr) node() {}
  130. func (be *ColonExpr) expr() {}
  131. func (be *ColonExpr) node() {}
  132. func (be *IndexExpr) expr() {}
  133. func (be *IndexExpr) node() {}
  134. func (w *Wildcard) expr() {}
  135. func (w *Wildcard) node() {}
  136. func (bl *BooleanLiteral) expr() {}
  137. func (bl *BooleanLiteral) literal() {}
  138. func (bl *BooleanLiteral) node() {}
  139. func (tl *TimeLiteral) expr() {}
  140. func (tl *TimeLiteral) literal() {}
  141. func (tl *TimeLiteral) node() {}
  142. func (il *IntegerLiteral) expr() {}
  143. func (il *IntegerLiteral) literal() {}
  144. func (il *IntegerLiteral) node() {}
  145. func (nl *NumberLiteral) expr() {}
  146. func (nl *NumberLiteral) literal() {}
  147. func (nl *NumberLiteral) node() {}
  148. func (sl *StringLiteral) expr() {}
  149. func (sl *StringLiteral) literal() {}
  150. func (sl *StringLiteral) node() {}
  151. func (d *Dimension) expr() {}
  152. func (d *Dimension) node() {}
  153. func (d Dimensions) node() {}
  154. func (d *Dimensions) GetWindow() *Window {
  155. for _, child := range *d {
  156. if w, ok := child.Expr.(*Window); ok {
  157. return w
  158. }
  159. }
  160. return nil
  161. }
  162. func (d *Dimensions) GetGroups() Dimensions {
  163. var nd Dimensions
  164. for _, child := range *d {
  165. if _, ok := child.Expr.(*Window); !ok {
  166. nd = append(nd, child)
  167. }
  168. }
  169. return nd
  170. }
  171. func (sf *SortField) expr() {}
  172. func (sf *SortField) node() {}
  173. func (sf SortFields) node() {}
  174. type Call struct {
  175. Name string
  176. Args []Expr
  177. }
  178. func (c *Call) expr() {}
  179. func (c *Call) literal() {}
  180. func (c *Call) node() {}
  181. type WhenClause struct {
  182. // The condition expression
  183. Expr Expr
  184. Result Expr
  185. }
  186. func (w *WhenClause) expr() {}
  187. func (w *WhenClause) literal() {}
  188. func (w *WhenClause) node() {}
  189. type CaseExpr struct {
  190. // The compare value expression. It can be a value expression or nil.
  191. // When it is nil, the WhenClause Expr must be a logical(comparison) expression
  192. Value Expr
  193. WhenClauses []*WhenClause
  194. ElseClause Expr
  195. }
  196. func (c *CaseExpr) expr() {}
  197. func (c *CaseExpr) literal() {}
  198. func (c *CaseExpr) node() {}
  199. type WindowType int
  200. const (
  201. NOT_WINDOW WindowType = iota
  202. TUMBLING_WINDOW
  203. HOPPING_WINDOW
  204. SLIDING_WINDOW
  205. SESSION_WINDOW
  206. COUNT_WINDOW
  207. )
  208. type Window struct {
  209. WindowType WindowType
  210. Length *IntegerLiteral
  211. Interval *IntegerLiteral
  212. Filter Expr
  213. }
  214. func (w *Window) expr() {}
  215. func (w *Window) literal() {}
  216. func (w *Window) node() {}
  217. type SelectStatements []SelectStatement
  218. func (ss *SelectStatements) node() {}
  219. type Fields []Field
  220. func (fs Fields) node() {}
  221. type BinaryExpr struct {
  222. OP Token
  223. LHS Expr
  224. RHS Expr
  225. }
  226. func (fe *BinaryExpr) expr() {}
  227. func (be *BinaryExpr) node() {}
  228. type FieldRef struct {
  229. StreamName StreamName
  230. Name string
  231. }
  232. func (fr *FieldRef) expr() {}
  233. func (fr *FieldRef) node() {}
  234. type MetaRef struct {
  235. StreamName StreamName
  236. Name string
  237. }
  238. func (fr *MetaRef) expr() {}
  239. func (fr *MetaRef) node() {}
  240. // The stream AST tree
  241. type Options map[string]string
  242. func (o Options) node() {}
  243. type StreamName string
  244. func (sn *StreamName) node() {}
  245. type StreamType int
  246. const (
  247. TypeStream StreamType = iota
  248. TypeTable
  249. )
  250. var StreamTypeMap = map[StreamType]string{
  251. TypeStream: "stream",
  252. TypeTable: "table",
  253. }
  254. type StreamStmt struct {
  255. Name StreamName
  256. StreamFields StreamFields
  257. Options Options
  258. StreamType StreamType //default to TypeStream
  259. }
  260. func (ss *StreamStmt) node() {}
  261. func (ss *StreamStmt) Stmt() {}
  262. type FieldType interface {
  263. fieldType()
  264. Node
  265. }
  266. type StreamField struct {
  267. Name string
  268. FieldType
  269. }
  270. func (u *StreamField) MarshalJSON() ([]byte, error) {
  271. return json.Marshal(&struct {
  272. FieldType interface{}
  273. Name string
  274. }{
  275. FieldType: PrintFieldTypeForJson(u.FieldType),
  276. Name: u.Name,
  277. })
  278. }
  279. type StreamFields []StreamField
  280. func (sf StreamFields) node() {}
  281. type BasicType struct {
  282. Type DataType
  283. }
  284. func (bt *BasicType) fieldType() {}
  285. func (bt *BasicType) node() {}
  286. type ArrayType struct {
  287. Type DataType
  288. FieldType
  289. }
  290. func (at *ArrayType) fieldType() {}
  291. func (at *ArrayType) node() {}
  292. type RecType struct {
  293. StreamFields StreamFields
  294. }
  295. func (rt *RecType) fieldType() {}
  296. func (rt *RecType) node() {}
  297. type ShowStreamsStatement struct {
  298. }
  299. type DescribeStreamStatement struct {
  300. Name string
  301. }
  302. type ExplainStreamStatement struct {
  303. Name string
  304. }
  305. type DropStreamStatement struct {
  306. Name string
  307. }
  308. func (ss *ShowStreamsStatement) Stmt() {}
  309. func (ss *ShowStreamsStatement) node() {}
  310. func (dss *DescribeStreamStatement) Stmt() {}
  311. func (dss *DescribeStreamStatement) node() {}
  312. func (dss *DescribeStreamStatement) GetName() string { return dss.Name }
  313. func (ess *ExplainStreamStatement) Stmt() {}
  314. func (ess *ExplainStreamStatement) node() {}
  315. func (ess *ExplainStreamStatement) GetName() string { return ess.Name }
  316. func (dss *DropStreamStatement) Stmt() {}
  317. func (dss *DropStreamStatement) node() {}
  318. func (dss *DropStreamStatement) GetName() string { return dss.Name }
  319. type ShowTablesStatement struct {
  320. }
  321. type DescribeTableStatement struct {
  322. Name string
  323. }
  324. type ExplainTableStatement struct {
  325. Name string
  326. }
  327. type DropTableStatement struct {
  328. Name string
  329. }
  330. func (ss *ShowTablesStatement) Stmt() {}
  331. func (ss *ShowTablesStatement) node() {}
  332. func (dss *DescribeTableStatement) Stmt() {}
  333. func (dss *DescribeTableStatement) node() {}
  334. func (dss *DescribeTableStatement) GetName() string { return dss.Name }
  335. func (ess *ExplainTableStatement) Stmt() {}
  336. func (ess *ExplainTableStatement) node() {}
  337. func (ess *ExplainTableStatement) GetName() string { return ess.Name }
  338. func (dss *DropTableStatement) Stmt() {}
  339. func (dss *DropTableStatement) node() {}
  340. func (dss *DropTableStatement) GetName() string { return dss.Name }
  341. type Visitor interface {
  342. Visit(Node) Visitor
  343. }
  344. func Walk(v Visitor, node Node) {
  345. if node == nil {
  346. return
  347. }
  348. if v = v.Visit(node); v == nil {
  349. return
  350. }
  351. switch n := node.(type) {
  352. case *BinaryExpr:
  353. Walk(v, n.LHS)
  354. Walk(v, n.RHS)
  355. case *Call:
  356. for _, expr := range n.Args {
  357. Walk(v, expr)
  358. }
  359. case *Window:
  360. Walk(v, n.Length)
  361. Walk(v, n.Interval)
  362. case *Field:
  363. Walk(v, n.Expr)
  364. case Fields:
  365. for _, c := range n {
  366. Walk(v, &c)
  367. }
  368. case *ParenExpr:
  369. Walk(v, n.Expr)
  370. case *SelectStatement:
  371. Walk(v, n.Fields)
  372. Walk(v, n.Dimensions)
  373. Walk(v, n.Sources)
  374. Walk(v, n.Joins)
  375. Walk(v, n.Condition)
  376. Walk(v, n.SortFields)
  377. Walk(v, n.Having)
  378. case SortFields:
  379. for _, sf := range n {
  380. Walk(v, &sf)
  381. }
  382. case Sources:
  383. for _, s := range n {
  384. Walk(v, s)
  385. }
  386. case Joins:
  387. for _, s := range n {
  388. Walk(v, &s)
  389. }
  390. case *Join:
  391. Walk(v, n.Expr)
  392. case *CaseExpr:
  393. Walk(v, n.Value)
  394. for _, w := range n.WhenClauses {
  395. Walk(v, w)
  396. }
  397. Walk(v, n.ElseClause)
  398. case *WhenClause:
  399. Walk(v, n.Expr)
  400. Walk(v, n.Result)
  401. case *StreamStmt:
  402. Walk(v, &n.Name)
  403. Walk(v, n.StreamFields)
  404. Walk(v, n.Options)
  405. case *BasicType, *ArrayType, *RecType:
  406. Walk(v, n)
  407. case *ShowStreamsStatement, *DescribeStreamStatement, *ExplainStreamStatement, *DropStreamStatement,
  408. *ShowTablesStatement, *DescribeTableStatement, *ExplainTableStatement, *DropTableStatement:
  409. Walk(v, n)
  410. }
  411. }
  412. // WalkFunc traverses a node hierarchy in depth-first order.
  413. func WalkFunc(node Node, fn func(Node)) {
  414. Walk(walkFuncVisitor(fn), node)
  415. }
  416. type walkFuncVisitor func(Node)
  417. func (fn walkFuncVisitor) Visit(n Node) Visitor { fn(n); return fn }
  418. // Valuer is the interface that wraps the Value() method.
  419. type Valuer interface {
  420. // Value returns the value and existence flag for a given key.
  421. Value(key string) (interface{}, bool)
  422. Meta(key string) (interface{}, bool)
  423. }
  424. // CallValuer implements the Call method for evaluating function calls.
  425. type CallValuer interface {
  426. Valuer
  427. // Call is invoked to evaluate a function call (if possible).
  428. Call(name string, args []interface{}) (interface{}, bool)
  429. }
  430. type AggregateCallValuer interface {
  431. CallValuer
  432. GetAllTuples() AggregateData
  433. GetSingleCallValuer() CallValuer
  434. }
  435. type Wildcarder interface {
  436. // Value returns the value and existence flag for a given key.
  437. All(stream string) (interface{}, bool)
  438. }
  439. type DataValuer interface {
  440. Valuer
  441. Wildcarder
  442. }
  443. type WildcardValuer struct {
  444. Data Wildcarder
  445. }
  446. //TODO deal with wildcard of a stream, e.g. SELECT Table.* from Table inner join Table1
  447. func (wv *WildcardValuer) Value(key string) (interface{}, bool) {
  448. if key == "" {
  449. return wv.Data.All(key)
  450. } else {
  451. a := strings.Index(key, COLUMN_SEPARATOR+"*")
  452. if a <= 0 {
  453. return nil, false
  454. } else {
  455. return wv.Data.All(key[:a])
  456. }
  457. }
  458. }
  459. func (wv *WildcardValuer) Meta(key string) (interface{}, bool) {
  460. return nil, false
  461. }
  462. /**********************************
  463. ** Various Data Types for SQL transformation
  464. */
  465. type AggregateData interface {
  466. AggregateEval(expr Expr, v CallValuer) []interface{}
  467. }
  468. // Message is a valuer that substitutes values for the mapped interface.
  469. type Message map[string]interface{}
  470. // Value returns the value for a key in the Message.
  471. func (m Message) Value(key string) (interface{}, bool) {
  472. var colkey string
  473. if keys := strings.Split(key, COLUMN_SEPARATOR); len(keys) == 1 {
  474. colkey = key
  475. } else if len(keys) == 2 {
  476. colkey = keys[1]
  477. } else {
  478. common.Log.Println("Invalid key: " + key + ", expect source.field or field.")
  479. return nil, false
  480. }
  481. key1 := strings.ToLower(colkey)
  482. if v, ok := m[key1]; ok {
  483. return v, ok
  484. } else {
  485. //Only when with 'SELECT * FROM ...' and 'schemaless', the key in map is not convert to lower case.
  486. //So all of keys in map should be convert to lowercase and then compare them.
  487. return m.getIgnoreCase(colkey)
  488. }
  489. }
  490. func (m Message) getIgnoreCase(key interface{}) (interface{}, bool) {
  491. if k, ok := key.(string); ok {
  492. key = strings.ToLower(k)
  493. for k, v := range m {
  494. if strings.ToLower(k) == key {
  495. return v, true
  496. }
  497. }
  498. }
  499. return nil, false
  500. }
  501. func (m Message) Meta(key string) (interface{}, bool) {
  502. if key == "*" {
  503. return map[string]interface{}(m), true
  504. }
  505. return m.Value(key)
  506. }
  507. type Event interface {
  508. GetTimestamp() int64
  509. IsWatermark() bool
  510. }
  511. type Metadata Message
  512. func (m Metadata) Value(key string) (interface{}, bool) {
  513. msg := Message(m)
  514. return msg.Value(key)
  515. }
  516. func (m Metadata) Meta(key string) (interface{}, bool) {
  517. if key == "*" {
  518. return map[string]interface{}(m), true
  519. }
  520. msg := Message(m)
  521. return msg.Meta(key)
  522. }
  523. type Tuple struct {
  524. Emitter string
  525. Message Message
  526. Timestamp int64
  527. Metadata Metadata
  528. }
  529. func (t *Tuple) Value(key string) (interface{}, bool) {
  530. return t.Message.Value(key)
  531. }
  532. func (t *Tuple) Meta(key string) (interface{}, bool) {
  533. if key == "*" {
  534. return map[string]interface{}(t.Metadata), true
  535. }
  536. return t.Metadata.Value(key)
  537. }
  538. func (t *Tuple) All(stream string) (interface{}, bool) {
  539. return t.Message, true
  540. }
  541. func (t *Tuple) AggregateEval(expr Expr, v CallValuer) []interface{} {
  542. return []interface{}{Eval(expr, MultiValuer(t, v, &WildcardValuer{t}))}
  543. }
  544. func (t *Tuple) GetTimestamp() int64 {
  545. return t.Timestamp
  546. }
  547. func (t *Tuple) GetMetadata() Metadata {
  548. return t.Metadata
  549. }
  550. func (t *Tuple) IsWatermark() bool {
  551. return false
  552. }
  553. type WindowTuples struct {
  554. Emitter string
  555. Tuples []Tuple
  556. }
  557. type WindowTuplesSet []WindowTuples
  558. func (w WindowTuplesSet) GetBySrc(src string) []Tuple {
  559. for _, me := range w {
  560. if me.Emitter == src {
  561. return me.Tuples
  562. }
  563. }
  564. return nil
  565. }
  566. func (w WindowTuplesSet) Len() int {
  567. if len(w) > 0 {
  568. return len(w[0].Tuples)
  569. }
  570. return 0
  571. }
  572. func (w WindowTuplesSet) Swap(i, j int) {
  573. if len(w) > 0 {
  574. s := w[0].Tuples
  575. s[i], s[j] = s[j], s[i]
  576. }
  577. }
  578. func (w WindowTuplesSet) Index(i int) Valuer {
  579. if len(w) > 0 {
  580. s := w[0].Tuples
  581. return &(s[i])
  582. }
  583. return nil
  584. }
  585. func (w WindowTuplesSet) AddTuple(tuple *Tuple) WindowTuplesSet {
  586. found := false
  587. for i, t := range w {
  588. if t.Emitter == tuple.Emitter {
  589. t.Tuples = append(t.Tuples, *tuple)
  590. found = true
  591. w[i] = t
  592. break
  593. }
  594. }
  595. if !found {
  596. ets := &WindowTuples{Emitter: tuple.Emitter}
  597. ets.Tuples = append(ets.Tuples, *tuple)
  598. w = append(w, *ets)
  599. }
  600. return w
  601. }
  602. //Sort by tuple timestamp
  603. func (w WindowTuplesSet) Sort() {
  604. for _, t := range w {
  605. tuples := t.Tuples
  606. sort.SliceStable(tuples, func(i, j int) bool {
  607. return tuples[i].Timestamp < tuples[j].Timestamp
  608. })
  609. t.Tuples = tuples
  610. }
  611. }
  612. func (w WindowTuplesSet) AggregateEval(expr Expr, v CallValuer) []interface{} {
  613. var result []interface{}
  614. if len(w) != 1 { //should never happen
  615. return nil
  616. }
  617. for _, t := range w[0].Tuples {
  618. result = append(result, Eval(expr, MultiValuer(&t, v, &WildcardValuer{&t})))
  619. }
  620. return result
  621. }
  622. type JoinTuple struct {
  623. Tuples []Tuple
  624. }
  625. func (jt *JoinTuple) AddTuple(tuple Tuple) {
  626. jt.Tuples = append(jt.Tuples, tuple)
  627. }
  628. func (jt *JoinTuple) AddTuples(tuples []Tuple) {
  629. for _, t := range tuples {
  630. jt.Tuples = append(jt.Tuples, t)
  631. }
  632. }
  633. func getTupleValue(tuple Tuple, t string, key string) (interface{}, bool) {
  634. switch t {
  635. case "value":
  636. return tuple.Value(key)
  637. case "meta":
  638. return tuple.Meta(key)
  639. default:
  640. common.Log.Errorf("cannot get tuple for type %s", t)
  641. return nil, false
  642. }
  643. }
  644. func (jt *JoinTuple) doGetValue(t string, key string) (interface{}, bool) {
  645. keys := strings.Split(key, COLUMN_SEPARATOR)
  646. tuples := jt.Tuples
  647. switch len(keys) {
  648. case 1:
  649. if len(tuples) > 1 {
  650. for _, tuple := range tuples { //TODO support key without modifier?
  651. v, ok := getTupleValue(tuple, t, key)
  652. if ok {
  653. return v, ok
  654. }
  655. }
  656. common.Log.Debugf("Wrong key: %s not found", key)
  657. return nil, false
  658. } else {
  659. return getTupleValue(tuples[0], t, key)
  660. }
  661. case 2:
  662. emitter, key := keys[0], keys[1]
  663. //TODO should use hash here
  664. for _, tuple := range tuples {
  665. if tuple.Emitter == emitter {
  666. return getTupleValue(tuple, t, key)
  667. }
  668. }
  669. return nil, false
  670. default:
  671. common.Log.Infoln("Wrong key: ", key, ", expect dot in the expression.")
  672. return nil, false
  673. }
  674. }
  675. func (jt *JoinTuple) Value(key string) (interface{}, bool) {
  676. return jt.doGetValue("value", key)
  677. }
  678. func (jt *JoinTuple) Meta(key string) (interface{}, bool) {
  679. return jt.doGetValue("meta", key)
  680. }
  681. func (jt *JoinTuple) All(stream string) (interface{}, bool) {
  682. if stream != "" {
  683. for _, t := range jt.Tuples {
  684. if t.Emitter == stream {
  685. return t.Message, true
  686. }
  687. }
  688. } else {
  689. var r Message = make(map[string]interface{})
  690. for _, t := range jt.Tuples {
  691. for k, v := range t.Message {
  692. if _, ok := r[k]; !ok {
  693. r[k] = v
  694. }
  695. }
  696. }
  697. return r, true
  698. }
  699. return nil, false
  700. }
  701. type JoinTupleSets []JoinTuple
  702. func (s JoinTupleSets) Len() int { return len(s) }
  703. func (s JoinTupleSets) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  704. func (s JoinTupleSets) Index(i int) Valuer { return &(s[i]) }
  705. func (s JoinTupleSets) AggregateEval(expr Expr, v CallValuer) []interface{} {
  706. var result []interface{}
  707. for _, t := range s {
  708. result = append(result, Eval(expr, MultiValuer(&t, v, &WildcardValuer{&t})))
  709. }
  710. return result
  711. }
  712. type GroupedTuples []DataValuer
  713. func (s GroupedTuples) AggregateEval(expr Expr, v CallValuer) []interface{} {
  714. var result []interface{}
  715. for _, t := range s {
  716. result = append(result, Eval(expr, MultiValuer(t, v, &WildcardValuer{t})))
  717. }
  718. return result
  719. }
  720. type GroupedTuplesSet []GroupedTuples
  721. func (s GroupedTuplesSet) Len() int { return len(s) }
  722. func (s GroupedTuplesSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  723. func (s GroupedTuplesSet) Index(i int) Valuer { return s[i][0] }
  724. type SortingData interface {
  725. Len() int
  726. Swap(i, j int)
  727. Index(i int) Valuer
  728. }
  729. // multiSorter implements the Sort interface, sorting the changes within.Hi
  730. type MultiSorter struct {
  731. SortingData
  732. fields SortFields
  733. valuer CallValuer
  734. values []map[string]interface{}
  735. }
  736. // OrderedBy returns a Sorter that sorts using the less functions, in order.
  737. // Call its Sort method to sort the data.
  738. func OrderedBy(fields SortFields, fv *FunctionValuer) *MultiSorter {
  739. return &MultiSorter{
  740. fields: fields,
  741. valuer: fv,
  742. }
  743. }
  744. // Less is part of sort.Interface. It is implemented by looping along the
  745. // less functions until it finds a comparison that discriminates between
  746. // the two items (one is less than the other). Note that it can call the
  747. // less functions twice per call. We could change the functions to return
  748. // -1, 0, 1 and reduce the number of calls for greater efficiency: an
  749. // exercise for the reader.
  750. func (ms *MultiSorter) Less(i, j int) bool {
  751. p, q := ms.values[i], ms.values[j]
  752. v := &ValuerEval{Valuer: MultiValuer(ms.valuer)}
  753. for _, field := range ms.fields {
  754. n := field.Name
  755. vp, _ := p[n]
  756. vq, _ := q[n]
  757. if vp == nil && vq != nil {
  758. return false
  759. } else if vp != nil && vq == nil {
  760. ms.valueSwap(true, i, j)
  761. return true
  762. } else if vp == nil && vq == nil {
  763. return false
  764. }
  765. switch {
  766. case v.simpleDataEval(vp, vq, LT):
  767. ms.valueSwap(field.Ascending, i, j)
  768. return field.Ascending
  769. case v.simpleDataEval(vq, vp, LT):
  770. ms.valueSwap(!field.Ascending, i, j)
  771. return !field.Ascending
  772. }
  773. }
  774. return false
  775. }
  776. func (ms *MultiSorter) valueSwap(s bool, i, j int) {
  777. if s {
  778. ms.values[i], ms.values[j] = ms.values[j], ms.values[i]
  779. }
  780. }
  781. // Sort sorts the argument slice according to the less functions passed to OrderedBy.
  782. func (ms *MultiSorter) Sort(data SortingData) error {
  783. ms.SortingData = data
  784. types := make([]string, len(ms.fields))
  785. ms.values = make([]map[string]interface{}, data.Len())
  786. //load and validate data
  787. for i := 0; i < data.Len(); i++ {
  788. ms.values[i] = make(map[string]interface{})
  789. p := data.Index(i)
  790. vep := &ValuerEval{Valuer: MultiValuer(p, ms.valuer)}
  791. for j, field := range ms.fields {
  792. n := field.Name
  793. vp, _ := vep.Valuer.Value(n)
  794. if err, ok := vp.(error); ok {
  795. return err
  796. } else {
  797. if types[j] == "" && vp != nil {
  798. types[j] = fmt.Sprintf("%T", vp)
  799. }
  800. if err := validate(types[j], vp); err != nil {
  801. return err
  802. } else {
  803. ms.values[i][n] = vp
  804. }
  805. }
  806. }
  807. }
  808. sort.Sort(ms)
  809. return nil
  810. }
  811. func validate(t string, v interface{}) error {
  812. if v == nil || t == "" {
  813. return nil
  814. }
  815. vt := fmt.Sprintf("%T", v)
  816. switch t {
  817. case "int", "int64", "float64", "uint64":
  818. if vt == "int" || vt == "int64" || vt == "float64" || vt == "uint64" {
  819. return nil
  820. } else {
  821. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  822. }
  823. case "bool":
  824. if vt == "bool" {
  825. return nil
  826. } else {
  827. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  828. }
  829. case "string":
  830. if vt == "string" {
  831. return nil
  832. } else {
  833. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  834. }
  835. case "time.Time":
  836. _, err := common.InterfaceToTime(v, "")
  837. if err != nil {
  838. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  839. } else {
  840. return nil
  841. }
  842. default:
  843. return fmt.Errorf("incompatible types for comparison: %s and %s", t, vt)
  844. }
  845. return nil
  846. }
  847. type EvalResultMessage struct {
  848. Emitter string
  849. Result interface{}
  850. Message Message
  851. }
  852. type ResultsAndMessages []EvalResultMessage
  853. // Eval evaluates expr against a map.
  854. func Eval(expr Expr, m Valuer) interface{} {
  855. eval := ValuerEval{Valuer: m}
  856. return eval.Eval(expr)
  857. }
  858. // ValuerEval will evaluate an expression using the Valuer.
  859. type ValuerEval struct {
  860. Valuer Valuer
  861. // IntegerFloatDivision will set the eval system to treat
  862. // a division between two integers as a floating point division.
  863. IntegerFloatDivision bool
  864. }
  865. // MultiValuer returns a Valuer that iterates over multiple Valuer instances
  866. // to find a match.
  867. func MultiValuer(valuers ...Valuer) Valuer {
  868. return multiValuer(valuers)
  869. }
  870. type multiValuer []Valuer
  871. func (a multiValuer) Value(key string) (interface{}, bool) {
  872. for _, valuer := range a {
  873. if v, ok := valuer.Value(key); ok {
  874. return v, true
  875. }
  876. }
  877. return nil, false
  878. }
  879. func (a multiValuer) Meta(key string) (interface{}, bool) {
  880. for _, valuer := range a {
  881. if v, ok := valuer.Meta(key); ok {
  882. return v, true
  883. }
  884. }
  885. return nil, false
  886. }
  887. func (a multiValuer) Call(name string, args []interface{}) (interface{}, bool) {
  888. for _, valuer := range a {
  889. if valuer, ok := valuer.(CallValuer); ok {
  890. if v, ok := valuer.Call(name, args); ok {
  891. return v, true
  892. } else {
  893. return fmt.Errorf("call func %s error: %v", name, v), false
  894. }
  895. }
  896. }
  897. return nil, false
  898. }
  899. type multiAggregateValuer struct {
  900. data AggregateData
  901. multiValuer
  902. singleCallValuer CallValuer
  903. }
  904. func MultiAggregateValuer(data AggregateData, singleCallValuer CallValuer, valuers ...Valuer) Valuer {
  905. return &multiAggregateValuer{
  906. data: data,
  907. multiValuer: valuers,
  908. singleCallValuer: singleCallValuer,
  909. }
  910. }
  911. func (a *multiAggregateValuer) Call(name string, args []interface{}) (interface{}, bool) {
  912. // assume the aggFuncMap already cache the custom agg funcs in isAggFunc()
  913. _, isAgg := aggFuncMap[name]
  914. for _, valuer := range a.multiValuer {
  915. if a, ok := valuer.(AggregateCallValuer); ok && isAgg {
  916. if v, ok := a.Call(name, args); ok {
  917. return v, true
  918. } else {
  919. return fmt.Errorf("call func %s error: %v", name, v), false
  920. }
  921. } else if c, ok := valuer.(CallValuer); ok && !isAgg {
  922. if v, ok := c.Call(name, args); ok {
  923. return v, true
  924. }
  925. }
  926. }
  927. return nil, false
  928. }
  929. func (a *multiAggregateValuer) GetAllTuples() AggregateData {
  930. return a.data
  931. }
  932. func (a *multiAggregateValuer) GetSingleCallValuer() CallValuer {
  933. return a.singleCallValuer
  934. }
  935. type BracketEvalResult struct {
  936. Start, End int
  937. }
  938. func (ber *BracketEvalResult) isIndex() bool {
  939. return ber.Start == ber.End
  940. }
  941. // Eval evaluates an expression and returns a value.
  942. func (v *ValuerEval) Eval(expr Expr) interface{} {
  943. if expr == nil {
  944. return nil
  945. }
  946. switch expr := expr.(type) {
  947. case *BinaryExpr:
  948. return v.evalBinaryExpr(expr)
  949. //case *BooleanLiteral:
  950. // return expr.Val
  951. case *IntegerLiteral:
  952. return expr.Val
  953. case *NumberLiteral:
  954. return expr.Val
  955. case *ParenExpr:
  956. return v.Eval(expr.Expr)
  957. case *StringLiteral:
  958. return expr.Val
  959. case *BooleanLiteral:
  960. return expr.Val
  961. case *ColonExpr:
  962. return &BracketEvalResult{Start: expr.Start, End: expr.End}
  963. case *IndexExpr:
  964. return &BracketEvalResult{Start: expr.Index, End: expr.Index}
  965. case *Call:
  966. if valuer, ok := v.Valuer.(CallValuer); ok {
  967. var args []interface{}
  968. if len(expr.Args) > 0 {
  969. args = make([]interface{}, len(expr.Args))
  970. for i, arg := range expr.Args {
  971. if aggreValuer, ok := valuer.(AggregateCallValuer); isAggFunc(expr) && ok {
  972. args[i] = aggreValuer.GetAllTuples().AggregateEval(arg, aggreValuer.GetSingleCallValuer())
  973. } else {
  974. args[i] = v.Eval(arg)
  975. if _, ok := args[i].(error); ok {
  976. return args[i]
  977. }
  978. }
  979. }
  980. }
  981. val, _ := valuer.Call(expr.Name, args)
  982. return val
  983. }
  984. return nil
  985. case *FieldRef:
  986. if expr.StreamName == "" {
  987. val, _ := v.Valuer.Value(expr.Name)
  988. return val
  989. } else {
  990. //The field specified with stream source
  991. val, _ := v.Valuer.Value(string(expr.StreamName) + COLUMN_SEPARATOR + expr.Name)
  992. return val
  993. }
  994. case *MetaRef:
  995. if expr.StreamName == "" {
  996. val, _ := v.Valuer.Meta(expr.Name)
  997. return val
  998. } else {
  999. //The field specified with stream source
  1000. val, _ := v.Valuer.Meta(string(expr.StreamName) + COLUMN_SEPARATOR + expr.Name)
  1001. return val
  1002. }
  1003. case *Wildcard:
  1004. val, _ := v.Valuer.Value("")
  1005. return val
  1006. case *CaseExpr:
  1007. return v.evalCase(expr)
  1008. default:
  1009. return nil
  1010. }
  1011. }
  1012. func (v *ValuerEval) evalBinaryExpr(expr *BinaryExpr) interface{} {
  1013. lhs := v.Eval(expr.LHS)
  1014. switch val := lhs.(type) {
  1015. case map[string]interface{}:
  1016. return v.evalJsonExpr(val, expr.OP, expr.RHS)
  1017. case Message:
  1018. return v.evalJsonExpr(map[string]interface{}(val), expr.OP, expr.RHS)
  1019. case error:
  1020. return val
  1021. }
  1022. if isSliceOrArray(lhs) {
  1023. return v.evalJsonExpr(lhs, expr.OP, expr.RHS)
  1024. }
  1025. rhs := v.Eval(expr.RHS)
  1026. if _, ok := rhs.(error); ok {
  1027. return rhs
  1028. }
  1029. return v.simpleDataEval(lhs, rhs, expr.OP)
  1030. }
  1031. func (v *ValuerEval) evalCase(expr *CaseExpr) interface{} {
  1032. if expr.Value != nil { // compare value to all when clause
  1033. ev := v.Eval(expr.Value)
  1034. for _, w := range expr.WhenClauses {
  1035. wv := v.Eval(w.Expr)
  1036. switch r := v.simpleDataEval(ev, wv, EQ).(type) {
  1037. case error:
  1038. return fmt.Errorf("evaluate case expression error: %s", r)
  1039. case bool:
  1040. if r {
  1041. return v.Eval(w.Result)
  1042. }
  1043. }
  1044. }
  1045. } else {
  1046. for _, w := range expr.WhenClauses {
  1047. switch r := v.Eval(w.Expr).(type) {
  1048. case error:
  1049. return fmt.Errorf("evaluate case expression error: %s", r)
  1050. case bool:
  1051. if r {
  1052. return v.Eval(w.Result)
  1053. }
  1054. }
  1055. }
  1056. }
  1057. if expr.ElseClause != nil {
  1058. return v.Eval(expr.ElseClause)
  1059. }
  1060. return nil
  1061. }
  1062. func isSliceOrArray(v interface{}) bool {
  1063. kind := reflect.ValueOf(v).Kind()
  1064. return kind == reflect.Array || kind == reflect.Slice
  1065. }
  1066. func (v *ValuerEval) evalJsonExpr(result interface{}, op Token, expr Expr) interface{} {
  1067. switch op {
  1068. case ARROW:
  1069. if val, ok := result.(map[string]interface{}); ok {
  1070. switch e := expr.(type) {
  1071. case *FieldRef, *MetaRef:
  1072. ve := &ValuerEval{Valuer: Message(val)}
  1073. return ve.Eval(e)
  1074. default:
  1075. return fmt.Errorf("the right expression is not a field reference node")
  1076. }
  1077. } else {
  1078. return fmt.Errorf("the result %v is not a type of map[string]interface{}", result)
  1079. }
  1080. case SUBSET:
  1081. if isSliceOrArray(result) {
  1082. return v.subset(result, expr)
  1083. } else {
  1084. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  1085. }
  1086. default:
  1087. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  1088. }
  1089. }
  1090. func (v *ValuerEval) subset(result interface{}, expr Expr) interface{} {
  1091. val := reflect.ValueOf(result)
  1092. ber := v.Eval(expr)
  1093. if berVal, ok1 := ber.(*BracketEvalResult); ok1 {
  1094. if berVal.isIndex() {
  1095. if 0 > berVal.Start {
  1096. if 0 > berVal.Start+val.Len() {
  1097. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  1098. }
  1099. berVal.Start += val.Len()
  1100. } else if berVal.Start >= val.Len() {
  1101. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  1102. }
  1103. return val.Index(berVal.Start).Interface()
  1104. } else {
  1105. if 0 > berVal.Start {
  1106. if 0 > berVal.Start+val.Len() {
  1107. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  1108. }
  1109. berVal.Start += val.Len()
  1110. } else if berVal.Start >= val.Len() {
  1111. return fmt.Errorf("start value is out of index: %d of %d", berVal.Start, val.Len())
  1112. }
  1113. if math.MinInt32 == berVal.End {
  1114. berVal.End = val.Len()
  1115. } else if 0 > berVal.End {
  1116. if 0 > berVal.End+val.Len() {
  1117. return fmt.Errorf("out of index: %d of %d", berVal.End, val.Len())
  1118. }
  1119. berVal.End += val.Len()
  1120. } else if berVal.End > val.Len() {
  1121. return fmt.Errorf("end value is out of index: %d of %d", berVal.End, val.Len())
  1122. } else if berVal.Start >= berVal.End {
  1123. return fmt.Errorf("start cannot be greater than end. start:%d end:%d", berVal.Start, berVal.End)
  1124. }
  1125. return val.Slice(berVal.Start, berVal.End).Interface()
  1126. }
  1127. } else {
  1128. return fmt.Errorf("invalid evaluation result - %v", berVal)
  1129. }
  1130. }
  1131. //lhs and rhs are non-nil
  1132. func (v *ValuerEval) simpleDataEval(lhs, rhs interface{}, op Token) interface{} {
  1133. if lhs == nil || rhs == nil {
  1134. switch op {
  1135. case EQ, LTE, GTE:
  1136. if lhs == nil && rhs == nil {
  1137. return true
  1138. } else {
  1139. return false
  1140. }
  1141. case NEQ:
  1142. if lhs == nil && rhs == nil {
  1143. return false
  1144. } else {
  1145. return true
  1146. }
  1147. case LT, GT:
  1148. return false
  1149. default:
  1150. return nil
  1151. }
  1152. }
  1153. lhs = convertNum(lhs)
  1154. rhs = convertNum(rhs)
  1155. // Evaluate if both sides are simple types.
  1156. switch lhs := lhs.(type) {
  1157. case bool:
  1158. rhs, ok := rhs.(bool)
  1159. if !ok {
  1160. return invalidOpError(lhs, op, rhs)
  1161. }
  1162. switch op {
  1163. case AND:
  1164. return lhs && rhs
  1165. case OR:
  1166. return lhs || rhs
  1167. case BITWISE_AND:
  1168. return lhs && rhs
  1169. case BITWISE_OR:
  1170. return lhs || rhs
  1171. case BITWISE_XOR:
  1172. return lhs != rhs
  1173. case EQ:
  1174. return lhs == rhs
  1175. case NEQ:
  1176. return lhs != rhs
  1177. default:
  1178. return invalidOpError(lhs, op, rhs)
  1179. }
  1180. case float64:
  1181. // Try the rhs as a float64, int64, or uint64
  1182. rhsf, ok := rhs.(float64)
  1183. if !ok {
  1184. switch val := rhs.(type) {
  1185. case int64:
  1186. rhsf, ok = float64(val), true
  1187. case uint64:
  1188. rhsf, ok = float64(val), true
  1189. }
  1190. }
  1191. if !ok {
  1192. return invalidOpError(lhs, op, rhs)
  1193. }
  1194. rhs := rhsf
  1195. switch op {
  1196. case EQ:
  1197. return lhs == rhs
  1198. case NEQ:
  1199. return lhs != rhs
  1200. case LT:
  1201. return lhs < rhs
  1202. case LTE:
  1203. return lhs <= rhs
  1204. case GT:
  1205. return lhs > rhs
  1206. case GTE:
  1207. return lhs >= rhs
  1208. case ADD:
  1209. return lhs + rhs
  1210. case SUB:
  1211. return lhs - rhs
  1212. case MUL:
  1213. return lhs * rhs
  1214. case DIV:
  1215. if rhs == 0 {
  1216. return fmt.Errorf("divided by zero")
  1217. }
  1218. return lhs / rhs
  1219. case MOD:
  1220. if rhs == 0 {
  1221. return fmt.Errorf("divided by zero")
  1222. }
  1223. return math.Mod(lhs, rhs)
  1224. default:
  1225. return invalidOpError(lhs, op, rhs)
  1226. }
  1227. case int64:
  1228. // Try as a float64 to see if a float cast is required.
  1229. switch rhs := rhs.(type) {
  1230. case float64:
  1231. lhs := float64(lhs)
  1232. switch op {
  1233. case EQ:
  1234. return lhs == rhs
  1235. case NEQ:
  1236. return lhs != rhs
  1237. case LT:
  1238. return lhs < rhs
  1239. case LTE:
  1240. return lhs <= rhs
  1241. case GT:
  1242. return lhs > rhs
  1243. case GTE:
  1244. return lhs >= rhs
  1245. case ADD:
  1246. return lhs + rhs
  1247. case SUB:
  1248. return lhs - rhs
  1249. case MUL:
  1250. return lhs * rhs
  1251. case DIV:
  1252. if rhs == 0 {
  1253. return fmt.Errorf("divided by zero")
  1254. }
  1255. return lhs / rhs
  1256. case MOD:
  1257. if rhs == 0 {
  1258. return fmt.Errorf("divided by zero")
  1259. }
  1260. return math.Mod(lhs, rhs)
  1261. default:
  1262. return invalidOpError(lhs, op, rhs)
  1263. }
  1264. case int64:
  1265. switch op {
  1266. case EQ:
  1267. return lhs == rhs
  1268. case NEQ:
  1269. return lhs != rhs
  1270. case LT:
  1271. return lhs < rhs
  1272. case LTE:
  1273. return lhs <= rhs
  1274. case GT:
  1275. return lhs > rhs
  1276. case GTE:
  1277. return lhs >= rhs
  1278. case ADD:
  1279. return lhs + rhs
  1280. case SUB:
  1281. return lhs - rhs
  1282. case MUL:
  1283. return lhs * rhs
  1284. case DIV:
  1285. if v.IntegerFloatDivision {
  1286. if rhs == 0 {
  1287. return fmt.Errorf("divided by zero")
  1288. }
  1289. return float64(lhs) / float64(rhs)
  1290. }
  1291. if rhs == 0 {
  1292. return fmt.Errorf("divided by zero")
  1293. }
  1294. return lhs / rhs
  1295. case MOD:
  1296. if rhs == 0 {
  1297. return fmt.Errorf("divided by zero")
  1298. }
  1299. return lhs % rhs
  1300. case BITWISE_AND:
  1301. return lhs & rhs
  1302. case BITWISE_OR:
  1303. return lhs | rhs
  1304. case BITWISE_XOR:
  1305. return lhs ^ rhs
  1306. default:
  1307. return invalidOpError(lhs, op, rhs)
  1308. }
  1309. case uint64:
  1310. switch op {
  1311. case EQ:
  1312. return uint64(lhs) == rhs
  1313. case NEQ:
  1314. return uint64(lhs) != rhs
  1315. case LT:
  1316. if lhs < 0 {
  1317. return true
  1318. }
  1319. return uint64(lhs) < rhs
  1320. case LTE:
  1321. if lhs < 0 {
  1322. return true
  1323. }
  1324. return uint64(lhs) <= rhs
  1325. case GT:
  1326. if lhs < 0 {
  1327. return false
  1328. }
  1329. return uint64(lhs) > rhs
  1330. case GTE:
  1331. if lhs < 0 {
  1332. return false
  1333. }
  1334. return uint64(lhs) >= rhs
  1335. case ADD:
  1336. return uint64(lhs) + rhs
  1337. case SUB:
  1338. return uint64(lhs) - rhs
  1339. case MUL:
  1340. return uint64(lhs) * rhs
  1341. case DIV:
  1342. if rhs == 0 {
  1343. return fmt.Errorf("divided by zero")
  1344. }
  1345. return uint64(lhs) / rhs
  1346. case MOD:
  1347. if rhs == 0 {
  1348. return fmt.Errorf("divided by zero")
  1349. }
  1350. return uint64(lhs) % rhs
  1351. case BITWISE_AND:
  1352. return uint64(lhs) & rhs
  1353. case BITWISE_OR:
  1354. return uint64(lhs) | rhs
  1355. case BITWISE_XOR:
  1356. return uint64(lhs) ^ rhs
  1357. default:
  1358. return invalidOpError(lhs, op, rhs)
  1359. }
  1360. default:
  1361. return invalidOpError(lhs, op, rhs)
  1362. }
  1363. case uint64:
  1364. // Try as a float64 to see if a float cast is required.
  1365. switch rhs := rhs.(type) {
  1366. case float64:
  1367. lhs := float64(lhs)
  1368. switch op {
  1369. case EQ:
  1370. return lhs == rhs
  1371. case NEQ:
  1372. return lhs != rhs
  1373. case LT:
  1374. return lhs < rhs
  1375. case LTE:
  1376. return lhs <= rhs
  1377. case GT:
  1378. return lhs > rhs
  1379. case GTE:
  1380. return lhs >= rhs
  1381. case ADD:
  1382. return lhs + rhs
  1383. case SUB:
  1384. return lhs - rhs
  1385. case MUL:
  1386. return lhs * rhs
  1387. case DIV:
  1388. if rhs == 0 {
  1389. return fmt.Errorf("divided by zero")
  1390. }
  1391. return lhs / rhs
  1392. case MOD:
  1393. if rhs == 0 {
  1394. return fmt.Errorf("divided by zero")
  1395. }
  1396. return math.Mod(lhs, rhs)
  1397. default:
  1398. return invalidOpError(lhs, op, rhs)
  1399. }
  1400. case int64:
  1401. switch op {
  1402. case EQ:
  1403. return lhs == uint64(rhs)
  1404. case NEQ:
  1405. return lhs != uint64(rhs)
  1406. case LT:
  1407. if rhs < 0 {
  1408. return false
  1409. }
  1410. return lhs < uint64(rhs)
  1411. case LTE:
  1412. if rhs < 0 {
  1413. return false
  1414. }
  1415. return lhs <= uint64(rhs)
  1416. case GT:
  1417. if rhs < 0 {
  1418. return true
  1419. }
  1420. return lhs > uint64(rhs)
  1421. case GTE:
  1422. if rhs < 0 {
  1423. return true
  1424. }
  1425. return lhs >= uint64(rhs)
  1426. case ADD:
  1427. return lhs + uint64(rhs)
  1428. case SUB:
  1429. return lhs - uint64(rhs)
  1430. case MUL:
  1431. return lhs * uint64(rhs)
  1432. case DIV:
  1433. if rhs == 0 {
  1434. return fmt.Errorf("divided by zero")
  1435. }
  1436. return lhs / uint64(rhs)
  1437. case MOD:
  1438. if rhs == 0 {
  1439. return fmt.Errorf("divided by zero")
  1440. }
  1441. return lhs % uint64(rhs)
  1442. case BITWISE_AND:
  1443. return lhs & uint64(rhs)
  1444. case BITWISE_OR:
  1445. return lhs | uint64(rhs)
  1446. case BITWISE_XOR:
  1447. return lhs ^ uint64(rhs)
  1448. default:
  1449. return invalidOpError(lhs, op, rhs)
  1450. }
  1451. case uint64:
  1452. switch op {
  1453. case EQ:
  1454. return lhs == rhs
  1455. case NEQ:
  1456. return lhs != rhs
  1457. case LT:
  1458. return lhs < rhs
  1459. case LTE:
  1460. return lhs <= rhs
  1461. case GT:
  1462. return lhs > rhs
  1463. case GTE:
  1464. return lhs >= rhs
  1465. case ADD:
  1466. return lhs + rhs
  1467. case SUB:
  1468. return lhs - rhs
  1469. case MUL:
  1470. return lhs * rhs
  1471. case DIV:
  1472. if rhs == 0 {
  1473. return fmt.Errorf("divided by zero")
  1474. }
  1475. return lhs / rhs
  1476. case MOD:
  1477. if rhs == 0 {
  1478. return fmt.Errorf("divided by zero")
  1479. }
  1480. return lhs % rhs
  1481. case BITWISE_AND:
  1482. return lhs & rhs
  1483. case BITWISE_OR:
  1484. return lhs | rhs
  1485. case BITWISE_XOR:
  1486. return lhs ^ rhs
  1487. default:
  1488. return invalidOpError(lhs, op, rhs)
  1489. }
  1490. default:
  1491. return invalidOpError(lhs, op, rhs)
  1492. }
  1493. case string:
  1494. rhss, ok := rhs.(string)
  1495. if !ok {
  1496. return invalidOpError(lhs, op, rhs)
  1497. }
  1498. switch op {
  1499. case EQ:
  1500. return lhs == rhss
  1501. case NEQ:
  1502. return lhs != rhss
  1503. case LT:
  1504. return lhs < rhss
  1505. case LTE:
  1506. return lhs <= rhss
  1507. case GT:
  1508. return lhs > rhss
  1509. case GTE:
  1510. return lhs >= rhss
  1511. default:
  1512. return invalidOpError(lhs, op, rhs)
  1513. }
  1514. case time.Time:
  1515. rt, err := common.InterfaceToTime(rhs, "")
  1516. if err != nil {
  1517. return invalidOpError(lhs, op, rhs)
  1518. }
  1519. switch op {
  1520. case EQ:
  1521. return lhs.Equal(rt)
  1522. case NEQ:
  1523. return !lhs.Equal(rt)
  1524. case LT:
  1525. return lhs.Before(rt)
  1526. case LTE:
  1527. return lhs.Before(rt) || lhs.Equal(rt)
  1528. case GT:
  1529. return lhs.After(rt)
  1530. case GTE:
  1531. return lhs.After(rt) || lhs.Equal(rt)
  1532. default:
  1533. return invalidOpError(lhs, op, rhs)
  1534. }
  1535. default:
  1536. return invalidOpError(lhs, op, rhs)
  1537. }
  1538. return invalidOpError(lhs, op, rhs)
  1539. }
  1540. func invalidOpError(lhs interface{}, op Token, rhs interface{}) error {
  1541. return fmt.Errorf("invalid operation %[1]T(%[1]v) %s %[3]T(%[3]v)", lhs, tokens[op], rhs)
  1542. }
  1543. func convertNum(para interface{}) interface{} {
  1544. if isInt(para) {
  1545. para = toInt64(para)
  1546. } else if isFloat(para) {
  1547. para = toFloat64(para)
  1548. }
  1549. return para
  1550. }
  1551. func isInt(para interface{}) bool {
  1552. switch para.(type) {
  1553. case int:
  1554. return true
  1555. case int8:
  1556. return true
  1557. case int16:
  1558. return true
  1559. case int32:
  1560. return true
  1561. case int64:
  1562. return true
  1563. }
  1564. return false
  1565. }
  1566. func toInt64(para interface{}) int64 {
  1567. if v, ok := para.(int); ok {
  1568. return int64(v)
  1569. } else if v, ok := para.(int8); ok {
  1570. return int64(v)
  1571. } else if v, ok := para.(int16); ok {
  1572. return int64(v)
  1573. } else if v, ok := para.(int32); ok {
  1574. return int64(v)
  1575. } else if v, ok := para.(int64); ok {
  1576. return v
  1577. }
  1578. return 0
  1579. }
  1580. func isFloat(para interface{}) bool {
  1581. switch para.(type) {
  1582. case float32:
  1583. return true
  1584. case float64:
  1585. return true
  1586. }
  1587. return false
  1588. }
  1589. func toFloat64(para interface{}) float64 {
  1590. if v, ok := para.(float32); ok {
  1591. return float64(v)
  1592. } else if v, ok := para.(float64); ok {
  1593. return v
  1594. }
  1595. return 0
  1596. }