vm.go 23 KB

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