rt_statements.go 13 KB

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