vm.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. // vm, the virtual low level machine that runs MUESLI.
  2. package muesli
  3. import "fmt"
  4. // Handler function
  5. type Handler func(vm *VM, arguments ...Value) []Value
  6. func (handler *Handler) Call(vm *VM, arguments ...Value) []Value {
  7. return (*handler)(vm, arguments...)
  8. }
  9. // A callable Value must implement the Callable interface
  10. type Callable interface {
  11. // Callable can be called
  12. Call(vm *VM, arguments ...Value) []Value
  13. // Callable has a position here it was defined. Needed for tracebacks.
  14. Position() *Position
  15. }
  16. // A helper Value has a help text available.
  17. // This help text can be set as well.
  18. type Helper interface {
  19. HelperName() string
  20. Help() string
  21. SetHelp(string) string
  22. }
  23. // Callable value types
  24. type CallableValue struct {
  25. // Name of the callable
  26. Name string
  27. // Help string for the callable.
  28. HelpText string
  29. }
  30. // Implement Helper interface
  31. func (val CallableValue) Help() string {
  32. return val.HelpText
  33. }
  34. // Implement Helper interface
  35. func (val * CallableValue) SetHelp(help string) string {
  36. val.HelpText = help
  37. return val.HelpText
  38. }
  39. // Implement Helper interface
  40. func (val CallableValue) HelperName() string {
  41. return val.Name
  42. }
  43. // AppendHelp appends help to an existing helper.
  44. func AppendHelp(helper Helper, extra string) string {
  45. return helper.SetHelp( helper.Help() + extra)
  46. }
  47. // ClearHelp rresets the help text to an empty string.
  48. func ClearHelp(helper Helper, extra string) string {
  49. return helper.SetHelp("")
  50. }
  51. func (val CallableValue) String() string {
  52. return val.Name
  53. }
  54. func (val CallableValue) Type() TypeValue {
  55. return TypeValue("Callable")
  56. }
  57. func (from CallableValue) Convert(to interface{}) error {
  58. return NewErrorValuef("Cannot convert the callable value %v to %v", from, to)
  59. }
  60. func (val *CallableValue) Call(vm *VM, arguments ...Value) []Value {
  61. panic("Not implemented")
  62. }
  63. // A struct to store a built in function
  64. type BuiltinValue struct {
  65. CallableValue
  66. Handler
  67. }
  68. func NewCallableValue(name string) CallableValue {
  69. return CallableValue{name, ""}
  70. }
  71. func NewBuiltinValue(name string, handler Handler) *BuiltinValue {
  72. result := &BuiltinValue{}
  73. result.Name = name
  74. result.Handler = handler
  75. return result
  76. }
  77. // A block in a script.
  78. type BlockValue struct {
  79. CallableValue
  80. Ast *Ast
  81. }
  82. func NewBlockValue(definition *Ast) *BlockValue {
  83. result := &BlockValue{}
  84. result.Name = fmt.Sprintf("<block:%s>", definition.String())
  85. result.Ast = definition
  86. return result
  87. }
  88. func (block * BlockValue) Position() *Position {
  89. if block == nil {
  90. return nil
  91. }
  92. if block.Ast == nil {
  93. return nil
  94. }
  95. pos := block.Ast.Token().Position
  96. return &pos
  97. }
  98. func (defined * DefinedValue) Position() *Position {
  99. if defined == nil {
  100. return nil
  101. }
  102. if defined.Body == nil {
  103. return nil
  104. }
  105. return defined.Body.Position()
  106. }
  107. func (cv CallableValue) Position() *Position {
  108. pos := Position{cv.Name, 1, 1}
  109. return &pos
  110. }
  111. /* Parameters for a defined value */
  112. type Parameter struct {
  113. Name WordValue
  114. Type TypeValue
  115. }
  116. // A script defined function
  117. type DefinedValue struct {
  118. CallableValue
  119. Body *BlockValue
  120. Parameters []*Parameter
  121. }
  122. func NewDefinedValue(name string, params []*Parameter, body *BlockValue) *DefinedValue {
  123. result := &DefinedValue{}
  124. result.Name = name
  125. result.Body = body
  126. result.Parameters = params
  127. return result
  128. }
  129. func (defined *DefinedValue) Call(vm *VM, arguments ...Value) []Value {
  130. for i , arg := range arguments {
  131. if i >= len(defined.Parameters) {
  132. break
  133. }
  134. param := defined.Parameters[i]
  135. expectedType := param.Type
  136. if !expectedType.IsMatch(arg.Type()) {
  137. return Fail(NewErrorValuef("Argument %d type mismatch: %s<->%s", i, expectedType, arg.Type()))
  138. }
  139. vm.Register(param.Name.String(), arg)
  140. }
  141. res := defined.Body.Call(vm, arguments...)
  142. return res
  143. }
  144. func (defined *DefinedValue) Help() string {
  145. help := defined.CallableValue.Help()
  146. extra := "["
  147. for _, parameter := range defined.Parameters {
  148. extra = fmt.Sprintf("%s %s %s", extra, parameter.Name, parameter.Type)
  149. }
  150. extra = extra + "]:"
  151. return extra + help
  152. }
  153. /*
  154. Amount of types that will be considered inside a signature.
  155. Limited mosty to allow hashability, that is, Signature is a map key.
  156. */
  157. const TypesInSignature = 32
  158. /* A signature describes the desired types of an overloaded function call. */
  159. type Signature struct {
  160. Types [TypesInSignature]TypeValue
  161. }
  162. func (s Signature) String() string {
  163. res := "["
  164. sep := ""
  165. for _, typ := range s.Types {
  166. if typ != ZeroTypeValue {
  167. res = res + sep + typ.String()
  168. sep = " "
  169. }
  170. }
  171. res = res + "]"
  172. return res
  173. }
  174. func CalculateSignature(arguments ...Value) Signature {
  175. signature := Signature{}
  176. for i := 0; i < len(signature.Types); i++ {
  177. if i < len(arguments) {
  178. signature.Types[i] = arguments[i].Type()
  179. } else {
  180. signature.Types[i] = AnyTypeValue
  181. }
  182. }
  183. return signature
  184. }
  185. func (tv TypeValue) IsMatch(other TypeValue) bool {
  186. if tv == AnyTypeValue || other == AnyTypeValue {
  187. return true
  188. }
  189. if tv == ZeroTypeValue || other == ZeroTypeValue {
  190. return true
  191. }
  192. return tv == other
  193. }
  194. func (signature Signature) IsMatch(other Signature) bool {
  195. for i, kind := range signature.Types {
  196. t1 := kind
  197. t2 := other.Types[i]
  198. if !t1.IsMatch(t2) {
  199. return false
  200. }
  201. }
  202. return true
  203. }
  204. /* An overload is an overloaded value that can be called. */
  205. type Overload struct {
  206. Name string
  207. Callable
  208. }
  209. /* A cover is a callable that dispatches to other callables depending on
  210. the types of the arguments, in particular the first one. The individual
  211. callable functions are the overloads
  212. */
  213. type CoverValue struct {
  214. CallableValue
  215. Overloads map[Signature]Overload
  216. }
  217. func (cv CoverValue) String() string {
  218. res := fmt.Sprintf("cover %s [ ", cv.Name)
  219. for k, v := range cv.Overloads {
  220. res = fmt.Sprintf("%s [%v] %s", res, k, v.Name)
  221. }
  222. res = fmt.Sprintf("%s].", res)
  223. return res;
  224. }
  225. func NewCoverValue(name string) *CoverValue {
  226. result := &CoverValue{}
  227. result.Name = name
  228. result.Overloads = make(map[Signature]Overload)
  229. return result
  230. }
  231. func (cover *CoverValue) Help() string {
  232. help := cover.CallableValue.Help()
  233. extra := "\n"
  234. for signature, overload := range cover.Overloads {
  235. // fmt.Printf("overload: %v", signature)
  236. extra = extra + fmt.Sprintf("* %v -> %s\n", signature.String(), overload.Name)
  237. }
  238. return help + extra
  239. }
  240. func (cover *CoverValue) Call(vm *VM, arguments ...Value) []Value {
  241. signature := CalculateSignature(arguments...)
  242. if overload, ok := cover.Overloads[signature]; ok {
  243. return overload.Call(vm, arguments...)
  244. } else {
  245. for overloadSignature, overload := range cover.Overloads {
  246. if signature.IsMatch(overloadSignature) {
  247. return overload.Call(vm, arguments...)
  248. }
  249. }
  250. }
  251. vm.Fail()
  252. return Fail(NewErrorValuef("Could not match cover %s with arguments: %s<->%v", cover.String(), signature, arguments))
  253. }
  254. const (
  255. CoverTypeValue = TypeValue("Cover")
  256. BuiltinTypeValue = TypeValue("Builtin")
  257. DefinedTypeValue = TypeValue("Defined")
  258. BlockTypeValue = TypeValue("Block")
  259. )
  260. func (v CoverValue) Type() TypeValue { return CoverTypeValue }
  261. func (v BuiltinValue) Type() TypeValue { return BuiltinTypeValue }
  262. func (v DefinedValue) Type() TypeValue { return DefinedTypeValue }
  263. func (v BlockValue) Type() TypeValue { return BlockTypeValue }
  264. func (from CoverValue) Convert(to interface{}) error {
  265. return NewErrorValuef("Cannot convert the cover value %v to %v", from, to)
  266. }
  267. func (from BuiltinValue) Convert(to interface{}) error {
  268. return NewErrorValuef("Cannot convert the builtin value %v to %v", from, to)
  269. }
  270. func (from DefinedValue) Convert(to interface{}) error {
  271. return NewErrorValuef("Cannot convert the defined value %v to %v", from, to)
  272. }
  273. func (from BlockValue) Convert(to interface{}) error {
  274. if toValue, isOk := to.(*BlockValue) ; isOk {
  275. (*toValue) = from
  276. return nil
  277. }
  278. return NewErrorValuef("Cannot convert the block value %v to %v", from, to)
  279. }
  280. func (cv * CoverValue) AddOverload(name string, callable Callable, tv ... TypeValue) error {
  281. // fmt.Printf("AddOverload: %v\n", tv)
  282. signature := Signature{}
  283. length := len(tv)
  284. if length > len(signature.Types) {
  285. length = len(signature.Types)
  286. }
  287. for i := 0; i < length; i++ {
  288. signature.Types[i] = tv[i]
  289. }
  290. cv.Overloads[signature] = Overload { Name: name, Callable: callable }
  291. // fmt.Printf("Overloads: %v\n", cv.Overloads)
  292. return nil
  293. }
  294. func (vm * VM) AddOverload(from, target string, level int, tv... TypeValue) error {
  295. var cover *CoverValue
  296. var callable Callable
  297. var ok bool
  298. lookup := vm.Lookup(from)
  299. if lookup == nil {
  300. cover = vm.RegisterCover(from, level)
  301. } else if cover, ok = lookup.(*CoverValue) ; !ok {
  302. return fmt.Errorf("%s exists and is not a cover value", from)
  303. }
  304. // fmt.Printf("AddOverload: %v %v\n", lookup, cover)
  305. lookup = vm.Lookup(target)
  306. if lookup == nil {
  307. return fmt.Errorf("target %s is not defined", target)
  308. }
  309. // fmt.Printf("AddOverload lookup: %v\n", lookup)
  310. if callable, ok = lookup.(Callable) ; !ok {
  311. return fmt.Errorf("%s is not a callable value", target)
  312. }
  313. res := cover.AddOverload(target, callable, tv...)
  314. // fmt.Printf("AddOverload: %v %v\n", lookup, cover)
  315. return res
  316. }
  317. type OverloadDescription struct {
  318. Target string
  319. Types []TypeValue
  320. Level int
  321. }
  322. func (vm * VM) AddOverloads(from string, descriptions ... OverloadDescription) error {
  323. for _, od := range descriptions {
  324. err := vm.AddOverload(from, od.Target, od.Level, od.Types...)
  325. if err != nil {
  326. panic(fmt.Errorf("internal error: could not register overloads: %s", err))
  327. }
  328. }
  329. return nil
  330. }
  331. func Over(target string, level int, types ... TypeValue) OverloadDescription {
  332. return OverloadDescription { Target: target, Level: level, Types: types}
  333. }
  334. func (vm * VM) SetHelp(target, help string) error {
  335. var helper Helper
  336. var ok bool
  337. lookup := vm.Lookup(target)
  338. if lookup == nil {
  339. return fmt.Errorf("%s not found", target)
  340. } else if helper, ok = lookup.(Helper) ; !ok {
  341. return fmt.Errorf("%s exists but cannot set help text.", target)
  342. }
  343. helper.SetHelp(help)
  344. return nil
  345. }
  346. // Scope of symbols defined in the VM, hierarchical
  347. type Scope struct {
  348. parent *Scope
  349. children []*Scope
  350. symbols map[string]Value
  351. }
  352. func NewScope(parent *Scope) *Scope {
  353. return &Scope{parent, make([]*Scope, 0), make(map[string]Value)}
  354. }
  355. func (scope *Scope) Lookup(name string) Value {
  356. value, ok := scope.symbols[name]
  357. if ok {
  358. return value
  359. }
  360. if scope.parent != nil {
  361. return scope.parent.Lookup(name)
  362. }
  363. return NilValue
  364. }
  365. func (scope *Scope) Register(name string, value Value) Value {
  366. scope.symbols[name] = value
  367. return value
  368. }
  369. func (scope * Scope) Known(filter func(string, Value) bool) map[string]Value {
  370. res := make(map[string]Value)
  371. if scope.parent != nil {
  372. res = scope.parent.Known(filter)
  373. }
  374. for k, v := range scope.symbols {
  375. if (filter == nil) || filter(k, v) {
  376. res[k] = v
  377. }
  378. }
  379. return res
  380. }
  381. func (scope * Scope) ForEachDefined(do func(string, Value) (bool, error)) (bool, error) {
  382. var res bool = true
  383. var err error
  384. if (do == nil) {
  385. return false, fmt.Errorf("do may not be nil")
  386. }
  387. if scope.parent != nil {
  388. res, err = scope.parent.ForEachDefined(do)
  389. }
  390. if res == false || err != nil {
  391. return res, err
  392. }
  393. for k, v := range scope.symbols {
  394. res, err = do(k, v)
  395. if res == false || err != nil {
  396. return res, err
  397. }
  398. }
  399. return res, err
  400. }
  401. func (scope* Scope) DefinedHelpers() []Helper {
  402. res := []Helper{}
  403. scope.ForEachDefined(func (k string, v Value) (bool, error) {
  404. helper, hok := v.(Helper)
  405. if hok {
  406. res = append(res, helper)
  407. }
  408. return true, nil
  409. })
  410. return res
  411. }
  412. // Frame of execution of a function
  413. type Frame struct {
  414. parent *Frame
  415. arguments []Value
  416. results []Value
  417. failed bool
  418. returned bool
  419. position *Position
  420. }
  421. func NewFrame(parent *Frame, position *Position) *Frame {
  422. return &Frame{parent, EmptyValueArray(), EmptyValueArray(), false, false, position}
  423. }
  424. type Tracer interface {
  425. Trace(vm VM, ast Ast, values ...Value) bool
  426. }
  427. // Virtual machine
  428. type VM struct {
  429. TopScope *Scope // Top level scope
  430. TopFrame *Frame // Top level scope
  431. *Scope // Current Scope
  432. *Frame // Current frame
  433. Tracer // Tracer to emit tracing info to, could be used for logging or debugging
  434. ExitStatus int
  435. }
  436. func NewVM() *VM {
  437. vm := &VM{NewScope(nil), NewFrame(nil, nil), nil, nil, nil, 0}
  438. vm.Scope = vm.TopScope
  439. vm.Frame = vm.TopFrame
  440. return vm
  441. }
  442. func (vm *VM) PushNewFrame(position *Position) *Frame {
  443. frame := NewFrame(vm.Frame, position)
  444. vm.Frame = frame
  445. return frame
  446. }
  447. func (vm *VM) PushNewScope() *Scope {
  448. scope := NewScope(vm.Scope)
  449. vm.Scope = scope
  450. return scope
  451. }
  452. func (vm *VM) Return(results ...Value) []Value {
  453. return results
  454. }
  455. func (vm *VM) PopFrame() *Frame {
  456. if (vm.Frame != vm.TopFrame) && (vm.Frame.parent != nil) {
  457. frame := vm.Frame
  458. if frame.returned || frame.failed {
  459. }
  460. vm.Frame = frame.parent
  461. vm.Frame.returned = frame.returned
  462. vm.Frame.failed = frame.failed
  463. vm.Frame.results = frame.results
  464. return frame
  465. }
  466. return nil
  467. }
  468. func (vm *VM) PopScope() *Scope {
  469. if (vm.Scope != vm.TopScope) && (vm.Scope.parent != nil) {
  470. scope := vm.Scope
  471. vm.Scope = scope.parent
  472. return scope
  473. }
  474. return nil
  475. }
  476. func (block * BlockValue) Call(vm *VM, arguments ...Value) []Value {
  477. ast := block.Ast
  478. arr := vm.RunChildren(*ast, arguments...)
  479. return arr
  480. }
  481. func (builtin * BuiltinValue) Call(vm *VM, arguments ...Value) []Value {
  482. handler := builtin.Handler
  483. return handler.Call(vm, arguments...)
  484. }
  485. /*
  486. func (vm *VM) CallDefined(ast *Ast, arguments ...Value) []Value {
  487. arr := vm.RunChildren(*ast, arguments...)
  488. return arr
  489. }
  490. func (vm *VM) CallBlock(ast *Ast, arguments ...Value) []Value {
  491. arr := vm.RunChildren(*ast, arguments...)
  492. return arr
  493. }
  494. func (vm *VM) CallBuiltin(handler Handler, arguments ...Value) []Value {
  495. return handler.Call(vm, arguments...)
  496. }
  497. func (vm *VM) CallCover(cover * CoverValue, arguments ...Value) []Value {
  498. return cover.Call(vm, arguments...)
  499. }
  500. */
  501. func (vm *VM) AddTrace(err error) error {
  502. res := ""
  503. for frame := vm.Frame; frame != nil; frame = frame.parent {
  504. if frame.position == nil {
  505. res = fmt.Sprintf("%s\nIn frame %v", res, frame)
  506. } else {
  507. res = fmt.Sprintf("%s\nIn %s", res, frame.position.String())
  508. }
  509. }
  510. return fmt.Errorf("%s: %s", res, err)
  511. }
  512. func (vm *VM) CallCallable(callable Callable, arguments ...Value) []Value {
  513. defer vm.PopFrame()
  514. defer vm.PopScope()
  515. vm.PushNewFrame(callable.Position())
  516. vm.PushNewScope()
  517. return callable.Call(vm, arguments...)
  518. }
  519. func (vm *VM) CallNamed(name string, arguments ...Value) []Value {
  520. value := vm.Lookup(name)
  521. if value == nil {
  522. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: not found.", name)))
  523. }
  524. if callable, ok := value.(Callable) ; ok {
  525. return vm.CallCallable(callable, arguments...)
  526. } else {
  527. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: %v. Not callable", name, value)))
  528. }
  529. /*
  530. value := vm.Lookup(name)
  531. switch toCall := value.(type) {
  532. case *BuiltinValue:
  533. return vm.CallBuiltin(toCall.Handler, arguments...)
  534. case *DefinedValue:
  535. return vm.CallDefined(toCall.Body.Ast, arguments...)
  536. case *CoverValue:
  537. return vm.CallCover(toCall, arguments...)
  538. case *BlockValue:
  539. return vm.CallBlock(toCall.Ast, arguments...)
  540. default:
  541. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: %v. Not callable", name, value)))
  542. }
  543. */
  544. }
  545. /*
  546. func (vm * VM) CallNamedFramed(name string, arguments ...) []Value {
  547. frame := vm.PushNewFrame()
  548. }
  549. */
  550. // ScopeUp Returns the levelth scope up from the current one where 0 is the
  551. // current scope. Returns the toplevel scope if l is greather than the current
  552. // scope stack depth.
  553. func (vm * VM) ScopeUp(level int) *Scope {
  554. scope := vm.Scope
  555. for now := 0; now < level; now++ {
  556. if scope.parent == nil {
  557. return scope
  558. }
  559. scope = scope.parent
  560. }
  561. return scope
  562. }
  563. // RegisterUp registers in klevel scopes up from the current scope,
  564. // or at toplevel if the level is greater than the total depth
  565. func (vm *VM) RegisterUp(name string, value Value, level int) Value {
  566. scope := vm.ScopeUp(level)
  567. return scope.Register(name, value)
  568. }
  569. func (vm *VM) Register(name string, value Value) Value {
  570. return vm.Scope.Register(name, value)
  571. }
  572. func (vm *VM) RegisterCover(name string, level int) *CoverValue {
  573. value := NewCoverValue(name)
  574. vm.RegisterUp(name, value, level)
  575. return value
  576. }
  577. func (vm *VM) RegisterBuiltin(name string, handler Handler) Value {
  578. value := NewBuiltinValue(name, handler)
  579. return vm.Register(name, value)
  580. }
  581. func (vm *VM) RegisterDefined(name string, params []*Parameter, block *BlockValue, level int) Value {
  582. value := NewDefinedValue(name, params, block)
  583. return vm.RegisterUp(name, value, level)
  584. }
  585. // RegisterBuiltinWithHelp
  586. func (vm *VM) RegisterBuiltinWithHelp(name string, handler Handler, help string) Value {
  587. res := vm.RegisterBuiltin(name, handler)
  588. vm.SetHelp(name, help)
  589. return res
  590. }
  591. func (vm *VM) Fail() {
  592. vm.Frame.failed = true
  593. }
  594. func (vm *VM) RunChildren(ast Ast, args ...Value) []Value {
  595. if ast.CountChildren() < 1 {
  596. return ReturnEmpty()
  597. }
  598. /* if ast.CountChildren() == 1 {
  599. return ast.Child(0).Run(vm, args)
  600. }
  601. */
  602. result := []Value{}
  603. for _, child := range ast.Children() {
  604. val := child.Run(vm, args...)
  605. if vm.Frame.returned || vm.Frame.failed {
  606. fmt.Printf("Returned.\n")
  607. return vm.Frame.results
  608. }
  609. // skip empty results
  610. if len(val) < 1 {
  611. continue
  612. }
  613. first := val[0]
  614. if _, isEmpty := first.(EmptyValue); isEmpty {
  615. continue
  616. }
  617. last := val[len(val) -1]
  618. // errors in the results at the last position take precendence and are propagated upwards.
  619. if _, isErr := last.(ErrorValue); isErr {
  620. return val
  621. }
  622. result = append(result, val...)
  623. }
  624. return result
  625. }
  626. func (vm *VM) RunChildrenLastResult(ast Ast, args ...Value) Value {
  627. var result Value = EmptyValue{}
  628. for _, child := range ast.Children() {
  629. val := child.Run(vm, args...)
  630. if vm.Frame.returned || vm.Frame.failed {
  631. fmt.Printf("Returned.\n")
  632. res := vm.Frame.results
  633. return res[len(res)-1]
  634. }
  635. // skip empty results
  636. if len(val) < 1 {
  637. continue
  638. }
  639. first := val[0]
  640. if _, isEmpty := first.(EmptyValue); isEmpty {
  641. continue
  642. }
  643. last := val[len(val) -1]
  644. // errors in the results at the last position take precendence and are propagated upwards.
  645. if _, isErr := last.(ErrorValue); isErr {
  646. return last
  647. }
  648. result = last
  649. }
  650. // The last non empty result is the result of this function.
  651. return result
  652. }
  653. func (vm *VM) RunChildrenFirstResult(ast Ast, args ...Value) Value {
  654. var result Value = EmptyValue{}
  655. for _, child := range ast.Children() {
  656. val := child.Run(vm, args...)
  657. if vm.Frame.returned || vm.Frame.failed {
  658. fmt.Printf("Returned.\n")
  659. res := vm.Frame.results
  660. return res[0]
  661. }
  662. // skip empty results
  663. if len(val) < 1 {
  664. continue
  665. }
  666. first := val[0]
  667. if _, isEmpty := first.(EmptyValue); isEmpty {
  668. continue
  669. }
  670. // otherwise if non empty return the result.
  671. return first
  672. }
  673. return result
  674. }
  675. func (vm *VM) RunAst(ast Ast, args ...Value) []Value {
  676. return ast.Run(vm, args...)
  677. }
  678. func (vm *VM) DefinedHelpers() []Helper {
  679. return vm.Scope.DefinedHelpers()
  680. }
  681. /*
  682. func (vm *VM) RunProgram(ast *BasicAst) ListValue {
  683. return vm.RunChildren(ast, (*VM).RunStatements)
  684. }
  685. func (vm *VM) RunStatements(ast *BasicAst) ListValue {
  686. return vm.RunChildren(ast, (*VM).RunStatement)
  687. }
  688. func (vm *VM) RunStatement(ast *BasicAst) ListValue {
  689. return NewListValue()
  690. }
  691. func (vm *VM) RunSet(ast *BasicAst) ListValue { return NewListValue() }
  692. func (vm *VM) RunGet(ast *BasicAst) ListValue { return NewListValue() }
  693. func (vm *VM) RunTarget(ast *BasicAst) ListValue { return NewListValue() }
  694. func (vm *VM) RunCommand(ast *BasicAst) ListValue { return NewListValue() }
  695. func (vm *VM) RunArguments(ast *BasicAst) ListValue { return NewListValue() }
  696. func (vm *VM) RunArgument(ast *BasicAst) ListValue { return NewListValue() }
  697. func (vm *VM) RunExpression(ast *BasicAst) ListValue { return NewListValue() }
  698. func (vm *VM) RunBlock(ast *BasicAst) ListValue { return NewListValue() }
  699. func (vm *VM) RunParenthesis(ast *BasicAst) ListValue { return NewListValue() }
  700. func (vm *VM) RunList(ast *BasicAst) ListValue { return NewListValue() }
  701. func (vm *VM) RunCapture(ast *BasicAst) ListValue { return NewListValue() }
  702. func (vm *VM) RunWordValue(ast *BasicAst) ListValue { return NewListValue() }
  703. func (vm *VM) RunWord(ast *BasicAst) ListValue { return NewListValue() }
  704. func (vm *VM) RunType(ast *BasicAst) ListValue { return NewListValue() }
  705. func (vm *VM) RunValue(ast *BasicAst) ListValue { return NewListValue() }
  706. func (vm *VM) RunEnd(ast *BasicAst) ListValue { return NewListValue() }
  707. func (vm *VM) RunError(ast *BasicAst) ListValue { return NewListValue() }
  708. func (vm *VM) Run(ast *BasicAst) ListValue {
  709. switch ast.AstKind {
  710. case AstKindProgram:
  711. return vm.RunProgram(ast)
  712. case AstKindStatements:
  713. return vm.RunStatements(ast)
  714. case AstKindStatement:
  715. return vm.RunStatement(ast)
  716. case AstKindSet:
  717. return vm.RunSet(ast)
  718. case AstKindGet:
  719. return vm.RunGet(ast)
  720. case AstKindTarget:
  721. return vm.RunTarget(ast)
  722. case AstKindCommand:
  723. return vm.RunCommand(ast)
  724. case AstKindArguments:
  725. return vm.RunArguments(ast)
  726. case AstKindArgument:
  727. return vm.RunArgument(ast)
  728. case AstKindExpression:
  729. return vm.RunExpression(ast)
  730. case AstKindBlock:
  731. return vm.RunBlock(ast)
  732. case AstKindParenthesis:
  733. return vm.RunParenthesis(ast)
  734. case AstKindList:
  735. return vm.RunList(ast)
  736. case AstKindCapture:
  737. return vm.RunCapture(ast)
  738. case AstKindWordValue:
  739. return vm.RunWordValue(ast)
  740. case AstKindWord:
  741. return vm.RunWord(ast)
  742. case AstKindType:
  743. return vm.RunType(ast)
  744. case AstKindValue:
  745. return vm.RunValue(ast)
  746. case AstKindEnd:
  747. return vm.RunEnd(ast)
  748. case AstKindError:
  749. return vm.RunError(ast)
  750. default:
  751. return ListValue{[]Value{NewErrorValuef("Unknown ast node type: %d", ast.AstKind)}}
  752. }
  753. }
  754. */