rt_statements.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. err = vs.SetValue(vars[0], res)
  253. } else if resList, ok := res.([]interface{}); ok {
  254. if len(vars) != len(resList) {
  255. err = fmt.Errorf("Assigned number of variables is different to "+
  256. "number of values (%v variables vs %v values)",
  257. len(vars), len(resList))
  258. }
  259. if err == nil {
  260. for i, v := range vars {
  261. if err == nil {
  262. err = vs.SetValue(v, resList[i])
  263. }
  264. }
  265. }
  266. } else {
  267. err = fmt.Errorf("Result for loop variable is not a list (value is %v)", res)
  268. }
  269. if err != nil {
  270. return nil, rt.erp.NewRuntimeError(util.ErrRuntimeError,
  271. err.Error(), rt.node)
  272. }
  273. // Execute block
  274. _, err = rt.node.Children[1].Runtime.Eval(vs, is)
  275. }
  276. // Check for continue
  277. if err != nil {
  278. if eoi, ok := err.(*util.RuntimeError); ok {
  279. if eoi.Type == util.ErrContinueIteration {
  280. err = nil
  281. }
  282. }
  283. }
  284. }
  285. // Check for end of iteration error
  286. if eoi, ok := err.(*util.RuntimeError); ok {
  287. if eoi.Type == util.ErrEndOfIteration {
  288. err = nil
  289. }
  290. }
  291. }
  292. }
  293. return nil, err
  294. }
  295. // Break statement
  296. // ===============
  297. /*
  298. breakRuntime is the runtime for the break statement.
  299. */
  300. type breakRuntime struct {
  301. *baseRuntime
  302. }
  303. /*
  304. breakRuntimeInst returns a new runtime component instance.
  305. */
  306. func breakRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  307. return &breakRuntime{newBaseRuntime(erp, node)}
  308. }
  309. /*
  310. Eval evaluate this runtime component.
  311. */
  312. func (rt *breakRuntime) Eval(vs parser.Scope, is map[string]interface{}) (interface{}, error) {
  313. _, err := rt.baseRuntime.Eval(vs, is)
  314. if err == nil {
  315. err = rt.erp.NewRuntimeError(util.ErrEndOfIteration, "", rt.node)
  316. }
  317. return nil, err
  318. }
  319. // Continue statement
  320. // ==================
  321. /*
  322. continueRuntime is the runtime for the continue statement.
  323. */
  324. type continueRuntime struct {
  325. *baseRuntime
  326. }
  327. /*
  328. continueRuntimeInst returns a new runtime component instance.
  329. */
  330. func continueRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  331. return &continueRuntime{newBaseRuntime(erp, node)}
  332. }
  333. /*
  334. Eval evaluate this runtime component.
  335. */
  336. func (rt *continueRuntime) Eval(vs parser.Scope, is map[string]interface{}) (interface{}, error) {
  337. _, err := rt.baseRuntime.Eval(vs, is)
  338. if err == nil {
  339. err = rt.erp.NewRuntimeError(util.ErrContinueIteration, "", rt.node)
  340. }
  341. return nil, err
  342. }
  343. // Try Runtime
  344. // ===========
  345. /*
  346. tryRuntime is the runtime for try blocks.
  347. */
  348. type tryRuntime struct {
  349. *baseRuntime
  350. }
  351. /*
  352. tryRuntimeInst returns a new runtime component instance.
  353. */
  354. func tryRuntimeInst(erp *ECALRuntimeProvider, node *parser.ASTNode) parser.Runtime {
  355. return &tryRuntime{newBaseRuntime(erp, node)}
  356. }
  357. /*
  358. Eval evaluate this runtime component.
  359. */
  360. func (rt *tryRuntime) Eval(vs parser.Scope, is map[string]interface{}) (interface{}, error) {
  361. var res interface{}
  362. evalExcept := func(errObj map[interface{}]interface{}, except *parser.ASTNode) bool {
  363. ret := false
  364. if len(except.Children) == 1 {
  365. // We only have statements - any exception is handled here
  366. evs := vs.NewChild(scope.NameFromASTNode(except))
  367. except.Children[0].Runtime.Eval(evs, is)
  368. ret = true
  369. } else if len(except.Children) == 2 {
  370. // We have statements and the error object is available - any exception is handled here
  371. evs := vs.NewChild(scope.NameFromASTNode(except))
  372. evs.SetValue(except.Children[0].Token.Val, errObj)
  373. except.Children[1].Runtime.Eval(evs, is)
  374. ret = true
  375. } else {
  376. errorVar := ""
  377. for i := 0; i < len(except.Children); i++ {
  378. child := except.Children[i]
  379. if !ret && child.Name == parser.NodeSTRING {
  380. exceptError, evalErr := child.Runtime.Eval(vs, is)
  381. // If we fail evaluating the string we panic as otherwise
  382. // we would need to generate a new error while trying to handle another error
  383. errorutil.AssertOk(evalErr)
  384. ret = exceptError == fmt.Sprint(errObj["type"])
  385. } else if ret && child.Name == parser.NodeAS {
  386. errorVar = child.Children[0].Token.Val
  387. } else if ret && child.Name == parser.NodeSTATEMENTS {
  388. evs := vs.NewChild(scope.NameFromASTNode(except))
  389. if errorVar != "" {
  390. evs.SetValue(errorVar, errObj)
  391. }
  392. child.Runtime.Eval(evs, is)
  393. }
  394. }
  395. }
  396. return ret
  397. }
  398. // Make sure the finally block is executed in any case
  399. if finally := rt.node.Children[len(rt.node.Children)-1]; finally.Name == parser.NodeFINALLY {
  400. fvs := vs.NewChild(scope.NameFromASTNode(finally))
  401. defer finally.Children[0].Runtime.Eval(fvs, is)
  402. }
  403. _, err := rt.baseRuntime.Eval(vs, is)
  404. if err == nil {
  405. tvs := vs.NewChild(scope.NameFromASTNode(rt.node))
  406. res, err = rt.node.Children[0].Runtime.Eval(tvs, is)
  407. // Evaluate except clauses
  408. if err != nil {
  409. errObj := map[interface{}]interface{}{
  410. "type": "UnexpectedError",
  411. "error": err.Error(),
  412. }
  413. if rtError, ok := err.(*util.RuntimeError); ok {
  414. errObj["type"] = rtError.Type.Error()
  415. errObj["detail"] = rtError.Detail
  416. errObj["pos"] = rtError.Pos
  417. errObj["line"] = rtError.Line
  418. errObj["source"] = rtError.Source
  419. } else if rtError, ok := err.(*util.RuntimeErrorWithDetail); ok {
  420. errObj["type"] = rtError.Type.Error()
  421. errObj["detail"] = rtError.Detail
  422. errObj["pos"] = rtError.Pos
  423. errObj["line"] = rtError.Line
  424. errObj["source"] = rtError.Source
  425. errObj["data"] = rtError.Data
  426. }
  427. res = nil
  428. for i := 1; i < len(rt.node.Children); i++ {
  429. if child := rt.node.Children[i]; child.Name == parser.NodeEXCEPT {
  430. if evalExcept(errObj, child) {
  431. err = nil
  432. break
  433. }
  434. }
  435. }
  436. }
  437. }
  438. return res, err
  439. }