vm.go 22 KB

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