vm.go 23 KB

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