vm.go 22 KB

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