vm.go 24 KB

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