vm.go 24 KB

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