rt_statements.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. var iterator func() (interface{}, error)
  189. var val interface{}
  190. it := rt.node.Children[0].Children[1]
  191. val, err = it.Runtime.Eval(vs, is, tid)
  192. // Create an iterator object
  193. if rterr, ok := err.(*util.RuntimeError); ok && rterr.Type == util.ErrIsIterator {
  194. // We got an iterator - all subsequent calls will return values
  195. iterator = func() (interface{}, error) {
  196. return it.Runtime.Eval(vs, is, tid)
  197. }
  198. err = nil
  199. } else {
  200. // We got a value over which we need to iterate
  201. if valList, isList := val.([]interface{}); isList {
  202. index := -1
  203. end := len(valList)
  204. iterator = func() (interface{}, error) {
  205. index++
  206. if index >= end {
  207. return nil, rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  208. }
  209. return valList[index], nil
  210. }
  211. } else if valMap, isMap := val.(map[interface{}]interface{}); isMap {
  212. var keys []interface{}
  213. index := -1
  214. for k := range valMap {
  215. keys = append(keys, k)
  216. }
  217. end := len(keys)
  218. // Try to sort according to string value
  219. sortutil.InterfaceStrings(keys)
  220. iterator = func() (interface{}, error) {
  221. index++
  222. if index >= end {
  223. return nil, rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  224. }
  225. key := keys[index]
  226. return []interface{}{key, valMap[key]}, nil
  227. }
  228. } else {
  229. // A single value will do exactly one iteration
  230. index := -1
  231. iterator = func() (interface{}, error) {
  232. index++
  233. if index > 0 {
  234. return nil, rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  235. }
  236. return val, nil
  237. }
  238. }
  239. }
  240. vars := rt.leftInVarName
  241. for err == nil {
  242. var res interface{}
  243. res, err = iterator()
  244. if err != nil {
  245. if eoi, ok := err.(*util.RuntimeError); ok {
  246. if eoi.Type == util.ErrIsIterator {
  247. err = nil
  248. }
  249. }
  250. }
  251. if err == nil {
  252. if len(vars) == 1 {
  253. err = vs.SetValue(vars[0], res)
  254. } else if resList, ok := res.([]interface{}); ok {
  255. if len(vars) != len(resList) {
  256. err = fmt.Errorf("Assigned number of variables is different to "+
  257. "number of values (%v variables vs %v values)",
  258. len(vars), len(resList))
  259. }
  260. if err == nil {
  261. for i, v := range vars {
  262. if err == nil {
  263. err = vs.SetValue(v, resList[i])
  264. }
  265. }
  266. }
  267. } else {
  268. err = fmt.Errorf("Result for loop variable is not a list (value is %v)", res)
  269. }
  270. if err != nil {
  271. return nil, rt.erp.NewRuntimeError(util.ErrRuntimeError,
  272. err.Error(), rt.node)
  273. }
  274. // Execute block
  275. _, err = rt.node.Children[1].Runtime.Eval(vs, is, tid)
  276. }
  277. // Check for continue
  278. if err != nil {
  279. if eoi, ok := err.(*util.RuntimeError); ok {
  280. if eoi.Type == util.ErrContinueIteration {
  281. err = nil
  282. }
  283. }
  284. }
  285. }
  286. // Check for end of iteration error
  287. if eoi, ok := err.(*util.RuntimeError); ok {
  288. if eoi.Type == util.ErrEndOfIteration {
  289. err = nil
  290. }
  291. }
  292. }
  293. }
  294. return nil, err
  295. }
  296. // Break statement
  297. // ===============
  298. /*
  299. breakRuntime is the runtime for the break statement.
  300. */
  301. type breakRuntime struct {
  302. *baseRuntime
  303. }
  304. /*
  305. breakRuntimeInst returns a new runtime component instance.
  306. */
  307. func breakRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  308. return &breakRuntime{newBaseRuntime(erp, node)}
  309. }
  310. /*
  311. Eval evaluate this runtime component.
  312. */
  313. func (rt *breakRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  314. _, err := rt.baseRuntime.Eval(vs, is, tid)
  315. if err == nil {
  316. err = rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  317. }
  318. return nil, err
  319. }
  320. // Continue statement
  321. // ==================
  322. /*
  323. continueRuntime is the runtime for the continue statement.
  324. */
  325. type continueRuntime struct {
  326. *baseRuntime
  327. }
  328. /*
  329. continueRuntimeInst returns a new runtime component instance.
  330. */
  331. func continueRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  332. return &continueRuntime{newBaseRuntime(erp, node)}
  333. }
  334. /*
  335. Eval evaluate this runtime component.
  336. */
  337. func (rt *continueRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  338. _, err := rt.baseRuntime.Eval(vs, is, tid)
  339. if err == nil {
  340. err = rt.erp.NewRuntimeError(util.ErrContinueIteration, "", rt.node)
  341. }
  342. return nil, err
  343. }
  344. // Try Runtime
  345. // ===========
  346. /*
  347. tryRuntime is the runtime for try blocks.
  348. */
  349. type tryRuntime struct {
  350. *baseRuntime
  351. }
  352. /*
  353. tryRuntimeInst returns a new runtime component instance.
  354. */
  355. func tryRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  356. return &tryRuntime{newBaseRuntime(erp, node)}
  357. }
  358. /*
  359. Eval evaluate this runtime component.
  360. */
  361. func (rt *tryRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  362. var res interface{}
  363. evalExcept := func(errObj map[interface{}]interface{}, except *parser.ASTNode) bool {
  364. ret := false
  365. if len(except.Children) == 1 {
  366. // We only have statements - any exception is handled here
  367. evs := vs.NewChild(scope.NameFromASTNode(except))
  368. except.Children[0].Runtime.Eval(evs, is, tid)
  369. ret = true
  370. } else if len(except.Children) == 2 {
  371. // We have statements and the error object is available - any exception is handled here
  372. evs := vs.NewChild(scope.NameFromASTNode(except))
  373. evs.SetValue(except.Children[0].Token.Val, errObj)
  374. except.Children[1].Runtime.Eval(evs, is, tid)
  375. ret = true
  376. } else {
  377. errorVar := ""
  378. for i := 0; i < len(except.Children); i++ {
  379. child := except.Children[i]
  380. if !ret && child.Name == parser.NodeSTRING {
  381. exceptError, evalErr := child.Runtime.Eval(vs, is, tid)
  382. // If we fail evaluating the string we panic as otherwise
  383. // we would need to generate a new error while trying to handle another error
  384. errorutil.AssertOk(evalErr)
  385. ret = exceptError == fmt.Sprint(errObj["type"])
  386. } else if ret && child.Name == parser.NodeAS {
  387. errorVar = child.Children[0].Token.Val
  388. } else if ret && child.Name == parser.NodeSTATEMENTS {
  389. evs := vs.NewChild(scope.NameFromASTNode(except))
  390. if errorVar != "" {
  391. evs.SetValue(errorVar, errObj)
  392. }
  393. child.Runtime.Eval(evs, is, tid)
  394. }
  395. }
  396. }
  397. return ret
  398. }
  399. // Make sure the finally block is executed in any case
  400. if finally := rt.node.Children[len(rt.node.Children)-1]; finally.Name == parser.NodeFINALLY {
  401. fvs := vs.NewChild(scope.NameFromASTNode(finally))
  402. defer finally.Children[0].Runtime.Eval(fvs, is, tid)
  403. }
  404. _, err := rt.baseRuntime.Eval(vs, is, tid)
  405. if err == nil {
  406. tvs := vs.NewChild(scope.NameFromASTNode(rt.node))
  407. res, err = rt.node.Children[0].Runtime.Eval(tvs, is, tid)
  408. // Evaluate except clauses
  409. if err != nil {
  410. errObj := map[interface{}]interface{}{
  411. "type": "UnexpectedError",
  412. "error": err.Error(),
  413. }
  414. if rtError, ok := err.(*util.RuntimeError); ok {
  415. errObj["type"] = rtError.Type.Error()
  416. errObj["detail"] = rtError.Detail
  417. errObj["pos"] = rtError.Pos
  418. errObj["line"] = rtError.Line
  419. errObj["source"] = rtError.Source
  420. } else if rtError, ok := err.(*util.RuntimeErrorWithDetail); ok {
  421. errObj["type"] = rtError.Type.Error()
  422. errObj["detail"] = rtError.Detail
  423. errObj["pos"] = rtError.Pos
  424. errObj["line"] = rtError.Line
  425. errObj["source"] = rtError.Source
  426. errObj["data"] = rtError.Data
  427. }
  428. if te, ok := err.(util.TraceableRuntimeError); ok {
  429. if ts := te.GetTraceString(); ts != nil {
  430. errObj["trace"] = ts
  431. }
  432. }
  433. res = nil
  434. for i := 1; i < len(rt.node.Children); i++ {
  435. if child := rt.node.Children[i]; child.Name == parser.NodeEXCEPT {
  436. if evalExcept(errObj, child) {
  437. err = nil
  438. break
  439. }
  440. }
  441. }
  442. }
  443. }
  444. return res, err
  445. }
  446. // Mutex Runtime
  447. // =============
  448. /*
  449. mutexRuntime is the runtime for mutex blocks.
  450. */
  451. type mutexRuntime struct {
  452. *baseRuntime
  453. }
  454. /*
  455. mutexRuntimeInst returns a new runtime component instance.
  456. */
  457. func mutexRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  458. return &mutexRuntime{newBaseRuntime(erp, node)}
  459. }
  460. /*
  461. Eval evaluate this runtime component.
  462. */
  463. func (rt *mutexRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {
  464. var res interface{}
  465. _, err := rt.baseRuntime.Eval(vs, is, tid)
  466. if err == nil {
  467. // Get the name of the mutex
  468. name := rt.node.Children[0].Token.Val
  469. mutex, ok := rt.erp.Mutexes[name]
  470. if !ok {
  471. mutex = &sync.Mutex{}
  472. rt.erp.Mutexes[name] = mutex
  473. }
  474. tvs := vs.NewChild(scope.NameFromASTNode(rt.node))
  475. mutex.Lock()
  476. defer mutex.Unlock()
  477. res, err = rt.node.Children[0].Runtime.Eval(tvs, is, tid)
  478. }
  479. return res, err
  480. }