vm.go 23 KB

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