rt_statements.go 13 KB

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