rt_statements.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package interpreter
  11. import (
  12. "fmt"
  13. "sync"
  14. "devt.de/krotik/common/errorutil"
  15. "devt.de/krotik/common/sortutil"
  16. "devt.de/krotik/ecal/parser"
  17. "devt.de/krotik/ecal/scope"
  18. "devt.de/krotik/ecal/util"
  19. )
  20. // Statements Runtime
  21. // ==================
  22. /*
  23. statementsRuntime is the runtime component for sequences of statements.
  24. */
  25. type statementsRuntime struct {
  26. *baseRuntime
  27. }
  28. /*
  29. statementsRuntimeInst returns a new runtime component instance.
  30. */
  31. func statementsRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  32. return &statementsRuntime{newBaseRuntime(erp, node)}
  33. }
  34. /*
  35. Eval evaluate this runtime component.
  36. */
  37. func (rt *statementsRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  38. var res interface{}
  39. _, err := rt.baseRuntime.Eval(vs, is, tid)
  40. if err == nil {
  41. for _, child := range rt.node.Children {
  42. if res, err = child.Runtime.Eval(vs, is, tid); err != nil {
  43. return nil, err
  44. }
  45. }
  46. }
  47. return res, err
  48. }
  49. // Condition statement
  50. // ===================
  51. /*
  52. ifRuntime is the runtime for the if condition statement.
  53. */
  54. type ifRuntime struct {
  55. *baseRuntime
  56. }
  57. /*
  58. ifRuntimeInst returns a new runtime component instance.
  59. */
  60. func ifRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  61. return &ifRuntime{newBaseRuntime(erp, node)}
  62. }
  63. /*
  64. Eval evaluate this runtime component.
  65. */
  66. func (rt *ifRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  67. _, err := rt.baseRuntime.Eval(vs, is, tid)
  68. if err == nil {
  69. // Create a new variable scope
  70. vs = vs.NewChild(scope.NameFromASTNode(rt.node))
  71. for offset := 0; offset < len(rt.node.Children); offset += 2 {
  72. var guardres interface{}
  73. // Evaluate guard
  74. if err == nil {
  75. guardres, err = rt.node.Children[offset].Runtime.Eval(vs, is, tid)
  76. if err == nil && guardres.(bool) {
  77. // The guard holds true so we execture its statements
  78. return rt.node.Children[offset+1].Runtime.Eval(vs, is, tid)
  79. }
  80. }
  81. }
  82. }
  83. return nil, err
  84. }
  85. // Guard Runtime
  86. // =============
  87. /*
  88. guardRuntime is the runtime for any guard condition (used in if, for, etc...).
  89. */
  90. type guardRuntime struct {
  91. *baseRuntime
  92. }
  93. /*
  94. guardRuntimeInst returns a new runtime component instance.
  95. */
  96. func guardRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  97. return &guardRuntime{newBaseRuntime(erp, node)}
  98. }
  99. /*
  100. Eval evaluate this runtime component.
  101. */
  102. func (rt *guardRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  103. var res interface{}
  104. _, err := rt.baseRuntime.Eval(vs, is, tid)
  105. if err == nil {
  106. var ret interface{}
  107. // Evaluate the condition
  108. ret, err = rt.node.Children[0].Runtime.Eval(vs, is, tid)
  109. // Guard returns always a boolean
  110. res = ret != nil && ret != false && ret != 0
  111. }
  112. return res, err
  113. }
  114. // Loop statement
  115. // ==============
  116. /*
  117. loopRuntime is the runtime for the loop statement (for).
  118. */
  119. type loopRuntime struct {
  120. *baseRuntime
  121. leftInVarName []string
  122. }
  123. /*
  124. loopRuntimeInst returns a new runtime component instance.
  125. */
  126. func loopRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  127. return &loopRuntime{newBaseRuntime(erp, node), nil}
  128. }
  129. /*
  130. Validate this node and all its child nodes.
  131. */
  132. func (rt *loopRuntime) Validate() error {
  133. err := rt.baseRuntime.Validate()
  134. if err == nil {
  135. if rt.node.Children[0].Name == parser.NodeIN {
  136. inVar := rt.node.Children[0].Children[0]
  137. if inVar.Name == parser.NodeIDENTIFIER {
  138. if len(inVar.Children) != 0 {
  139. return rt.erp.NewRuntimeError(util.ErrInvalidConstruct,
  140. "Must have a simple variable on the left side of the In expression", rt.node)
  141. }
  142. rt.leftInVarName = []string{inVar.Token.Val}
  143. } else if inVar.Name == parser.NodeLIST {
  144. rt.leftInVarName = make([]string, 0, len(inVar.Children))
  145. for _, child := range inVar.Children {
  146. if child.Name != parser.NodeIDENTIFIER || len(child.Children) != 0 {
  147. return rt.erp.NewRuntimeError(util.ErrInvalidConstruct,
  148. "Must have a list of simple variables on the left side of the In expression", rt.node)
  149. }
  150. rt.leftInVarName = append(rt.leftInVarName, child.Token.Val)
  151. }
  152. }
  153. }
  154. }
  155. return err
  156. }
  157. /*
  158. Eval evaluate this runtime component.
  159. */
  160. func (rt *loopRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  161. _, err := rt.baseRuntime.Eval(vs, is, tid)
  162. if err == nil {
  163. var guardres interface{}
  164. // Create a new variable scope
  165. vs = vs.NewChild(scope.NameFromASTNode(rt.node))
  166. // Create a new instance scope - elements in each loop iteration start from scratch
  167. is = make(map[string]interface{})
  168. if rt.node.Children[0].Name == parser.NodeGUARD {
  169. // Evaluate guard
  170. guardres, err = rt.node.Children[0].Runtime.Eval(vs, is, tid)
  171. for err == nil && guardres.(bool) {
  172. // Execute block
  173. _, err = rt.node.Children[1].Runtime.Eval(vs, is, tid)
  174. // Check for continue
  175. if err != nil {
  176. if eoi, ok := err.(*util.RuntimeError); ok {
  177. if eoi.Type == util.ErrContinueIteration {
  178. err = nil
  179. }
  180. }
  181. }
  182. if err == nil {
  183. // Evaluate guard
  184. guardres, err = rt.node.Children[0].Runtime.Eval(vs, is, tid)
  185. }
  186. }
  187. } else if rt.node.Children[0].Name == parser.NodeIN {
  188. err = rt.handleIterator(vs, is, tid)
  189. }
  190. }
  191. return nil, err
  192. }
  193. /*
  194. handleIterator handles iterator functions for loops.
  195. */
  196. func (rt *loopRuntime) handleIterator(vs parser.Scope, is map[string]interface{}, tid uint64) error {
  197. var res interface{}
  198. iterator, err := rt.getIterator(vs, is, tid)
  199. vars := rt.leftInVarName
  200. for err == nil {
  201. if res, err = rt.getIteratorValue(iterator); err == nil {
  202. if len(vars) == 1 {
  203. err = vs.SetValue(vars[0], res)
  204. } else if resList, ok := res.([]interface{}); ok {
  205. if len(vars) != len(resList) {
  206. err = fmt.Errorf("Assigned number of variables is different to "+
  207. "number of values (%v variables vs %v values)",
  208. len(vars), len(resList))
  209. }
  210. if err == nil {
  211. for i, v := range vars {
  212. if err == nil {
  213. err = vs.SetValue(v, resList[i])
  214. }
  215. }
  216. }
  217. } else {
  218. err = fmt.Errorf("Result for loop variable is not a list (value is %v)", res)
  219. }
  220. if err != nil {
  221. return rt.erp.NewRuntimeError(util.ErrRuntimeError,
  222. err.Error(), rt.node)
  223. }
  224. // Execute block
  225. _, err = rt.node.Children[1].Runtime.Eval(vs, is, tid)
  226. }
  227. // Check for continue
  228. if err != nil {
  229. if eoi, ok := err.(*util.RuntimeError); ok {
  230. if eoi.Type == util.ErrContinueIteration {
  231. err = nil
  232. }
  233. }
  234. }
  235. }
  236. // Check for end of iteration error
  237. if eoi, ok := err.(*util.RuntimeError); ok {
  238. if eoi.Type == util.ErrEndOfIteration {
  239. err = nil
  240. }
  241. }
  242. return err
  243. }
  244. /*
  245. getIteratorValue gets the next iterator value.
  246. */
  247. func (rt *loopRuntime) getIteratorValue(iterator func() (interface{}, error)) (interface{}, error) {
  248. var err error
  249. var res interface{}
  250. if res, err = iterator(); err != nil {
  251. if eoi, ok := err.(*util.RuntimeError); ok {
  252. if eoi.Type == util.ErrIsIterator {
  253. err = nil
  254. }
  255. }
  256. }
  257. return res, err
  258. }
  259. /*
  260. getIterator create an iterator object.
  261. */
  262. func (rt *loopRuntime) getIterator(vs parser.Scope, is map[string]interface{}, tid uint64) (func() (interface{}, error), error) {
  263. var iterator func() (interface{}, error)
  264. it := rt.node.Children[0].Children[1]
  265. val, err := it.Runtime.Eval(vs, is, tid)
  266. // Create an iterator object
  267. if rterr, ok := err.(*util.RuntimeError); ok && rterr.Type == util.ErrIsIterator {
  268. // We got an iterator - all subsequent calls will return values
  269. iterator = func() (interface{}, error) {
  270. return it.Runtime.Eval(vs, is, tid)
  271. }
  272. err = nil
  273. } else {
  274. // We got a value over which we need to iterate
  275. if valList, isList := val.([]interface{}); isList {
  276. index := -1
  277. end := len(valList)
  278. iterator = func() (interface{}, error) {
  279. index++
  280. if index >= end {
  281. return nil, rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  282. }
  283. return valList[index], nil
  284. }
  285. } else if valMap, isMap := val.(map[interface{}]interface{}); isMap {
  286. var keys []interface{}
  287. index := -1
  288. for k := range valMap {
  289. keys = append(keys, k)
  290. }
  291. end := len(keys)
  292. // Try to sort according to string value
  293. sortutil.InterfaceStrings(keys)
  294. iterator = func() (interface{}, error) {
  295. index++
  296. if index >= end {
  297. return nil, rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  298. }
  299. key := keys[index]
  300. return []interface{}{key, valMap[key]}, nil
  301. }
  302. } else {
  303. // A single value will do exactly one iteration
  304. index := -1
  305. iterator = func() (interface{}, error) {
  306. index++
  307. if index > 0 {
  308. return nil, rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  309. }
  310. return val, nil
  311. }
  312. }
  313. }
  314. return iterator, err
  315. }
  316. // Break statement
  317. // ===============
  318. /*
  319. breakRuntime is the runtime for the break statement.
  320. */
  321. type breakRuntime struct {
  322. *baseRuntime
  323. }
  324. /*
  325. breakRuntimeInst returns a new runtime component instance.
  326. */
  327. func breakRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  328. return &breakRuntime{newBaseRuntime(erp, node)}
  329. }
  330. /*
  331. Eval evaluate this runtime component.
  332. */
  333. func (rt *breakRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  334. _, err := rt.baseRuntime.Eval(vs, is, tid)
  335. if err == nil {
  336. err = rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  337. }
  338. return nil, err
  339. }
  340. // Continue statement
  341. // ==================
  342. /*
  343. continueRuntime is the runtime for the continue statement.
  344. */
  345. type continueRuntime struct {
  346. *baseRuntime
  347. }
  348. /*
  349. continueRuntimeInst returns a new runtime component instance.
  350. */
  351. func continueRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  352. return &continueRuntime{newBaseRuntime(erp, node)}
  353. }
  354. /*
  355. Eval evaluate this runtime component.
  356. */
  357. func (rt *continueRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  358. _, err := rt.baseRuntime.Eval(vs, is, tid)
  359. if err == nil {
  360. err = rt.erp.NewRuntimeError(util.ErrContinueIteration, "", rt.node)
  361. }
  362. return nil, err
  363. }
  364. // Try Runtime
  365. // ===========
  366. /*
  367. tryRuntime is the runtime for try blocks.
  368. */
  369. type tryRuntime struct {
  370. *baseRuntime
  371. }
  372. /*
  373. tryRuntimeInst returns a new runtime component instance.
  374. */
  375. func tryRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  376. return &tryRuntime{newBaseRuntime(erp, node)}
  377. }
  378. /*
  379. Eval evaluate this runtime component.
  380. */
  381. func (rt *tryRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  382. var res interface{}
  383. // Make sure the finally block is executed in any case
  384. if finally := rt.node.Children[len(rt.node.Children)-1]; finally.Name == parser.NodeFINALLY {
  385. fvs := vs.NewChild(scope.NameFromASTNode(finally))
  386. defer finally.Children[0].Runtime.Eval(fvs, is, tid)
  387. }
  388. _, err := rt.baseRuntime.Eval(vs, is, tid)
  389. if err == nil {
  390. tvs := vs.NewChild(scope.NameFromASTNode(rt.node))
  391. res, err = rt.node.Children[0].Runtime.Eval(tvs, is, tid)
  392. // Evaluate except clauses
  393. if err != nil {
  394. errObj := map[interface{}]interface{}{
  395. "type": "UnexpectedError",
  396. "error": err.Error(),
  397. }
  398. if rtError, ok := err.(*util.RuntimeError); ok {
  399. errObj["type"] = rtError.Type.Error()
  400. errObj["detail"] = rtError.Detail
  401. errObj["pos"] = rtError.Pos
  402. errObj["line"] = rtError.Line
  403. errObj["source"] = rtError.Source
  404. } else if rtError, ok := err.(*util.RuntimeErrorWithDetail); ok {
  405. errObj["type"] = rtError.Type.Error()
  406. errObj["detail"] = rtError.Detail
  407. errObj["pos"] = rtError.Pos
  408. errObj["line"] = rtError.Line
  409. errObj["source"] = rtError.Source
  410. errObj["data"] = rtError.Data
  411. }
  412. if te, ok := err.(util.TraceableRuntimeError); ok {
  413. if ts := te.GetTraceString(); ts != nil {
  414. errObj["trace"] = ts
  415. }
  416. }
  417. res = nil
  418. for i := 1; i < len(rt.node.Children); i++ {
  419. if child := rt.node.Children[i]; child.Name == parser.NodeEXCEPT {
  420. if ok, newerror := rt.evalExcept(vs, is, tid, errObj, child); ok {
  421. err = newerror
  422. break
  423. }
  424. }
  425. }
  426. } else {
  427. // Evaluate otherwise clause
  428. for i := 1; i < len(rt.node.Children); i++ {
  429. if child := rt.node.Children[i]; child.Name == parser.NodeOTHERWISE {
  430. ovs := vs.NewChild(scope.NameFromASTNode(child))
  431. _, err = child.Children[0].Runtime.Eval(ovs, is, tid)
  432. break
  433. }
  434. }
  435. }
  436. }
  437. return res, err
  438. }
  439. func (rt *tryRuntime) evalExcept(vs parser.Scope, is map[string]interface{},
  440. tid uint64, errObj map[interface{}]interface{}, except *parser.ASTNode) (bool, error) {
  441. var newerror error
  442. ret := false
  443. if len(except.Children) == 1 {
  444. // We only have statements - any exception is handled here
  445. evs := vs.NewChild(scope.NameFromASTNode(except))
  446. _, newerror = except.Children[0].Runtime.Eval(evs, is, tid)
  447. ret = true
  448. } else if len(except.Children) == 2 {
  449. // We have statements and the error object is available - any exception is handled here
  450. evs := vs.NewChild(scope.NameFromASTNode(except))
  451. evs.SetValue(except.Children[0].Token.Val, errObj)
  452. _, newerror = except.Children[1].Runtime.Eval(evs, is, tid)
  453. ret = true
  454. } else {
  455. errorVar := ""
  456. for i := 0; i < len(except.Children); i++ {
  457. child := except.Children[i]
  458. if !ret && child.Name == parser.NodeSTRING {
  459. exceptError, evalErr := child.Runtime.Eval(vs, is, tid)
  460. // If we fail evaluating the string we panic as otherwise
  461. // we would need to generate a new error while trying to handle another error
  462. errorutil.AssertOk(evalErr)
  463. ret = exceptError == fmt.Sprint(errObj["type"])
  464. } else if ret && child.Name == parser.NodeAS {
  465. errorVar = child.Children[0].Token.Val
  466. } else if ret && child.Name == parser.NodeSTATEMENTS {
  467. evs := vs.NewChild(scope.NameFromASTNode(except))
  468. if errorVar != "" {
  469. evs.SetValue(errorVar, errObj)
  470. }
  471. _, newerror = child.Runtime.Eval(evs, is, tid)
  472. }
  473. }
  474. }
  475. return ret, newerror
  476. }
  477. // Mutex Runtime
  478. // =============
  479. /*
  480. mutexRuntime is the runtime for mutex blocks.
  481. */
  482. type mutexRuntime struct {
  483. *baseRuntime
  484. }
  485. /*
  486. mutexRuntimeInst returns a new runtime component instance.
  487. */
  488. func mutexRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  489. return &mutexRuntime{newBaseRuntime(erp, node)}
  490. }
  491. /*
  492. Eval evaluate this runtime component.
  493. */
  494. func (rt *mutexRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  495. var res interface{}
  496. _, err := rt.baseRuntime.Eval(vs, is, tid)
  497. if err == nil {
  498. // Get the name of the mutex
  499. name := rt.node.Children[0].Token.Val
  500. mutex, ok := rt.erp.Mutexes[name]
  501. if !ok {
  502. mutex = &sync.Mutex{}
  503. rt.erp.Mutexes[name] = mutex
  504. }
  505. tvs := vs.NewChild(scope.NameFromASTNode(rt.node))
  506. mutex.Lock()
  507. defer mutex.Unlock()
  508. res, err = rt.node.Children[0].Runtime.Eval(tvs, is, tid)
  509. }
  510. return res, err
  511. }