vm.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. // vm, the virtual low level machine that runs MUESLI.
  2. package muesli
  3. import (
  4. "fmt"
  5. "strings"
  6. )
  7. // Handler function
  8. type Handler func(vm *VM, arguments ...Value) []Value
  9. func (handler *Handler) Call(vm *VM, arguments ...Value) []Value {
  10. return (*handler)(vm, arguments...)
  11. }
  12. // A callable Value must implement the Callable interface
  13. type Callable interface {
  14. // Callable can be called
  15. Call(vm *VM, arguments ...Value) []Value
  16. // Position is the source code position where it was defined. Needed for tracebacks.
  17. Position() *Position
  18. // Signature are the types of the parameters of this function.
  19. Signature() Signature
  20. }
  21. // A helper Value has a help text available.
  22. // This help text can be set as well.
  23. type Helper interface {
  24. HelperName() string
  25. Help() string
  26. SetHelp(string) string
  27. }
  28. // BasicCallable is an embeddable struct that makes it easier to
  29. // implement the Caller and Helper interface.
  30. type BasicCallable struct {
  31. // Name of the callable
  32. Name string
  33. // Help string for the callable.
  34. HelpText string
  35. // Signature of the callable for type checking.
  36. signature Signature
  37. // Position where the callable is defined.
  38. position Position
  39. }
  40. func (val BasicCallable) Signature() Signature {
  41. return val.signature
  42. }
  43. // Implement Helper interface
  44. func (val BasicCallable) Help() string {
  45. return val.HelpText
  46. }
  47. // Implement Helper interface
  48. func (val * BasicCallable) SetHelp(help string) string {
  49. val.HelpText = help
  50. return val.HelpText
  51. }
  52. // Implement Helper interface
  53. func (val BasicCallable) HelperName() string {
  54. return val.Name
  55. }
  56. // AppendHelp appends help to an existing helper.
  57. func AppendHelp(helper Helper, extra string) string {
  58. return helper.SetHelp( helper.Help() + extra)
  59. }
  60. // ClearHelp rresets the help text to an empty string.
  61. func ClearHelp(helper Helper, extra string) string {
  62. return helper.SetHelp("")
  63. }
  64. func (bc * BasicCallable) Takes(arguments ...TypeValue) *BasicCallable {
  65. bc.signature.SetParameters(arguments...)
  66. return bc
  67. }
  68. func (bc * BasicCallable) Returns(arguments ...TypeValue) *BasicCallable {
  69. bc.signature.SetReturns(arguments...)
  70. return bc
  71. }
  72. func (val BasicCallable) String() string {
  73. return val.Name
  74. }
  75. func (val BasicCallable) Type() TypeValue {
  76. return TypeValue("Callable")
  77. }
  78. func (from BasicCallable) Convert(to interface{}) error {
  79. return NewErrorValuef("Cannot convert the callable value %v to %v: Not implemented.", from, to)
  80. }
  81. func (val *BasicCallable) Call(vm *VM, arguments ...Value) []Value {
  82. panic("Not implemented")
  83. }
  84. // A struct to store a built in function
  85. type BuiltinValue struct {
  86. BasicCallable
  87. Handler
  88. }
  89. func NewBasicCallable(name string) BasicCallable {
  90. return BasicCallable{name, "", NoSignature(), Position{name, 1, 1}}
  91. }
  92. func NewBuiltinValue(name string, handler Handler) *BuiltinValue {
  93. result := &BuiltinValue{}
  94. result.Name = name
  95. result.Handler = handler
  96. return result
  97. }
  98. // A block in a script.
  99. type BlockValue struct {
  100. BasicCallable
  101. Ast *Ast
  102. }
  103. func NewBlockValue(definition *Ast) *BlockValue {
  104. result := &BlockValue{}
  105. result.Name = fmt.Sprintf("<block:%s>", definition.String())
  106. result.Ast = definition
  107. return result
  108. }
  109. func (block * BlockValue) Position() *Position {
  110. if block == nil {
  111. return nil
  112. }
  113. if block.Ast == nil {
  114. return nil
  115. }
  116. pos := block.Ast.Token().Position
  117. return &pos
  118. }
  119. func (defined * DefinedValue) Position() *Position {
  120. if defined == nil {
  121. return nil
  122. }
  123. if defined.Body == nil {
  124. return nil
  125. }
  126. return defined.Body.Position()
  127. }
  128. func (cv BasicCallable) Position() *Position {
  129. return &cv.position
  130. }
  131. // A script defined function
  132. type DefinedValue struct {
  133. BasicCallable
  134. Body *BlockValue
  135. }
  136. func NewDefinedValue(name string, signature Signature, body *BlockValue) *DefinedValue {
  137. result := &DefinedValue{}
  138. result.Name = name
  139. result.Body = body
  140. result.signature = signature
  141. return result
  142. }
  143. func (defined *DefinedValue) Call(vm *VM, arguments ...Value) []Value {
  144. vm.Trace("Call defined value: %v %v %v", defined, defined.signature, arguments)
  145. for i , arg := range arguments {
  146. if i >= len(defined.signature.Parameters) {
  147. break
  148. }
  149. param := defined.signature.Parameters[i]
  150. expectedType := param.Type
  151. vm.Trace("Signature check: %d %v", i, param)
  152. if !expectedType.IsMatch(arg.Type()) {
  153. return Fail(NewErrorValuef("Argument %d type mismatch: %s<->%s", i, expectedType, arg.Type()))
  154. }
  155. vm.Register(param.Name.String(), arg)
  156. vm.Trace("DefinedValue.Call: vm.Register: %v %v", param.Name.String(), arg)
  157. }
  158. res := defined.Body.Call(vm, arguments...)
  159. return res
  160. }
  161. func (defined *DefinedValue) Help() string {
  162. help := defined.BasicCallable.Help()
  163. extra := "["
  164. for _, parameter := range defined.signature.Parameters {
  165. extra = fmt.Sprintf("%s %s %s", extra, parameter.Name, parameter.Type)
  166. }
  167. extra = extra + "]:"
  168. return extra + help
  169. }
  170. // Assert that DefinedValue is callable.
  171. var _ Callable = &DefinedValue{}
  172. const (
  173. CoverTypeValue = TypeValue("Cover")
  174. BuiltinTypeValue = TypeValue("Builtin")
  175. DefinedTypeValue = TypeValue("Defined")
  176. BlockTypeValue = TypeValue("Block")
  177. )
  178. func (v CoverValue) Type() TypeValue { return CoverTypeValue }
  179. func (v BuiltinValue) Type() TypeValue { return BuiltinTypeValue }
  180. func (v DefinedValue) Type() TypeValue { return DefinedTypeValue }
  181. func (v BlockValue) Type() TypeValue { return BlockTypeValue }
  182. func (from CoverValue) Convert(to interface{}) error {
  183. return NewErrorValuef("Cannot convert the cover value %v to %v", from, to)
  184. }
  185. func (from BuiltinValue) Convert(to interface{}) error {
  186. return NewErrorValuef("Cannot convert the builtin value %v to %v", from, to)
  187. }
  188. func (from DefinedValue) Convert(to interface{}) error {
  189. return NewErrorValuef("Cannot convert the defined value %v to %v", from, to)
  190. }
  191. func (from BlockValue) Convert(to interface{}) error {
  192. if toValue, isOk := to.(*BlockValue) ; isOk {
  193. (*toValue) = from
  194. return nil
  195. }
  196. return NewErrorValuef("Cannot convert the block value %v to %v", from, to)
  197. }
  198. func (cv * CoverValue) AddOverloadWithSignature(name string, callable Callable, signature Signature) Overload {
  199. ov := Overload { Name: name, Callable: callable }
  200. cv.Overloads[signature] = ov
  201. return ov
  202. }
  203. func (cv * CoverValue) AddOverloadCallable(name string, callable Callable) Overload {
  204. return cv.AddOverloadWithSignature(name, callable, callable.Signature())
  205. }
  206. func (cv * CoverValue) AddOverload(name string, callable Callable, tv ... TypeValue) error {
  207. signature := Signature{}
  208. length := len(tv)
  209. if length > len(signature.Parameters) {
  210. length = len(signature.Parameters)
  211. }
  212. for i := 0; i < length; i++ {
  213. signature.Parameters[i].Type = tv[i]
  214. }
  215. cv.AddOverloadWithSignature(name, callable, signature)
  216. return nil
  217. }
  218. func (vm * VM) Errorf(format string, args...interface{}) error {
  219. return fmt.Errorf(format, args...)
  220. }
  221. func (vm * VM) AddOverloadCallable(from, target string, level int, callable Callable) error {
  222. var cover *CoverValue
  223. var ok bool
  224. lookup := vm.Lookup(from)
  225. if lookup == nil {
  226. cover = vm.RegisterCover(from, level)
  227. } else if cover, ok = lookup.(*CoverValue) ; !ok {
  228. return fmt.Errorf("%s exists and is not a cover value", from)
  229. }
  230. cover.AddOverloadCallable(target, callable)
  231. return nil
  232. }
  233. func (vm *VM) LookupCallable(target string) (Callable, error) {
  234. var callable Callable
  235. var ok bool
  236. lookup := vm.Lookup(target)
  237. if lookup == nil {
  238. return nil, fmt.Errorf("%s is not defined", target)
  239. }
  240. if callable, ok = lookup.(Callable) ; !ok {
  241. return nil, fmt.Errorf("%s is not a callable value", target)
  242. }
  243. return callable, nil
  244. }
  245. // AddOverloadByName overloads the from command to call the target command
  246. // if the argument list matches the signature based on the given type values
  247. func (vm * VM) AddOverload(from, target string, level int, tv... TypeValue) error {
  248. var cover *CoverValue
  249. var callable Callable
  250. var ok bool
  251. var err error
  252. lookup := vm.Lookup(from)
  253. if lookup == nil {
  254. cover = vm.RegisterCover(from, level)
  255. } else if cover, ok = lookup.(*CoverValue) ; !ok {
  256. return fmt.Errorf("%s exists and is not a cover value", from)
  257. }
  258. callable, err = vm.LookupCallable(target)
  259. if err != nil {
  260. return err
  261. }
  262. return cover.AddOverload(target, callable, tv...)
  263. }
  264. // AddOverloadByName overloads the from command to call the target command
  265. // if the argment lists matches the signature of the target command.
  266. func (vm * VM) AddOverloadByName(from, target string, level int) error {
  267. callable, err := vm.LookupCallable(target)
  268. if err != nil {
  269. return err
  270. }
  271. return vm.AddOverloadCallable(from, target, level, callable)
  272. }
  273. type OverloadDescription struct {
  274. Target string
  275. Types []TypeValue
  276. Level int
  277. }
  278. func (vm * VM) AddOverloads(from string, descriptions ... OverloadDescription) error {
  279. for _, od := range descriptions {
  280. err := vm.AddOverload(from, od.Target, od.Level, od.Types...)
  281. if err != nil {
  282. panic(fmt.Errorf("internal error: could not register overloads: %s", err))
  283. }
  284. }
  285. return nil
  286. }
  287. func Over(target string, level int, types ... TypeValue) OverloadDescription {
  288. return OverloadDescription { Target: target, Level: level, Types: types}
  289. }
  290. func (vm * VM) SetHelp(target, help string) error {
  291. var helper Helper
  292. var ok bool
  293. lookup := vm.Lookup(target)
  294. if lookup == nil {
  295. return fmt.Errorf("%s not found", target)
  296. } else if helper, ok = lookup.(Helper) ; !ok {
  297. return fmt.Errorf("%s exists but cannot set help text.", target)
  298. }
  299. helper.SetHelp(help)
  300. return nil
  301. }
  302. type Tracer interface {
  303. Trace(vm VM, fmt string, args ... interface{}) bool
  304. }
  305. // Virtual machine
  306. type VM struct {
  307. TopScope *Scope // Top level scope
  308. TopFrame *Frame // Top level scope
  309. *Scope // Current Scope
  310. *Frame // Current frame
  311. Tracer // Tracer to emit tracing info to, could be used for logging or debugging
  312. *Console // every VM has it's own virtual console.
  313. ExitStatus int
  314. }
  315. func NewVM() *VM {
  316. vm := &VM{NewScope(nil), NewFrame(nil, nil), nil, nil, nil, NewStdConsole(), 0}
  317. vm.Scope = vm.TopScope
  318. vm.Frame = vm.TopFrame
  319. return vm
  320. }
  321. func (vm *VM) Trace(fm string, args ... interface{}) {
  322. if vm.Tracer != nil {
  323. vm.Tracer.Trace(*vm, fm, args...)
  324. }
  325. }
  326. func (vm *VM) PushNewFrame(position *Position) *Frame {
  327. frame := NewFrame(vm.Frame, position)
  328. vm.Trace("PushFrame %v->%v\n", vm.Frame, frame)
  329. vm.Frame = frame
  330. return frame
  331. }
  332. func (vm *VM) PushNewScope() *Scope {
  333. scope := NewScope(vm.Scope)
  334. vm.Scope = scope
  335. return scope
  336. }
  337. func (vm *VM) Return(results ...Value) []Value {
  338. return results
  339. }
  340. func (vm *VM) PopFrame() *Frame {
  341. oldFrame := vm.Frame
  342. vm.Trace("PopFrame %v->%v\n", vm.Frame, vm.Frame.parent)
  343. if (vm.Frame != vm.TopFrame) && (vm.Frame.parent != nil) {
  344. frame := vm.Frame
  345. vm.Frame = frame.parent
  346. // Copy frame results up.
  347. vm.Frame.returned = oldFrame.returned
  348. vm.Frame.failed = oldFrame.failed
  349. vm.Frame.results = oldFrame.results
  350. return frame
  351. }
  352. return nil
  353. }
  354. func (vm *VM) PopScope() *Scope {
  355. if (vm.Scope != vm.TopScope) && (vm.Scope.parent != nil) {
  356. scope := vm.Scope
  357. vm.Scope = scope.parent
  358. return scope
  359. }
  360. return nil
  361. }
  362. func (block * BlockValue) Call(vm *VM, arguments ...Value) []Value {
  363. ast := block.Ast
  364. // Now, don't run the block itself but the Statements node
  365. // that should be in it.
  366. children := ast.Children()
  367. if len(children) < 1 {
  368. return Fail(fmt.Errorf("Block has no statements."))
  369. }
  370. if len(children) > 1 {
  371. return Fail(fmt.Errorf("Block has too many statements."))
  372. }
  373. statements := children[0]
  374. arr := vm.RunAst(*statements, arguments...)
  375. return arr
  376. }
  377. func (builtin * BuiltinValue) Call(vm *VM, arguments ...Value) []Value {
  378. err := builtin.signature.TypeCheck(arguments...)
  379. if err != nil {
  380. return Fail(ErrorValue{err})
  381. }
  382. handler := builtin.Handler
  383. return handler.Call(vm, arguments...)
  384. }
  385. func (vm *VM) AddTrace(err error) error {
  386. res := ""
  387. for frame := vm.Frame; frame != nil; frame = frame.parent {
  388. if frame.position == nil {
  389. res = fmt.Sprintf("%s\nIn frame %v", res, frame)
  390. } else {
  391. res = fmt.Sprintf("%s\nIn %s", res, frame.position.String())
  392. }
  393. }
  394. return fmt.Errorf("%s: %s", res, err)
  395. }
  396. func (vm *VM) CallCallable(callable Callable, arguments ...Value) []Value {
  397. defer vm.PopScope()
  398. defer vm.PopFrame()
  399. vm.PushNewFrame(callable.Position())
  400. vm.PushNewScope()
  401. result := callable.Call(vm, arguments...)
  402. return result
  403. }
  404. func (vm *VM) CallNamed(name string, arguments ...Value) []Value {
  405. value := vm.Lookup(name)
  406. if value == nil {
  407. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: not found.", name)))
  408. }
  409. if callable, ok := value.(Callable) ; ok {
  410. return vm.CallCallable(callable, arguments...)
  411. } else {
  412. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: %v. Not callable", name, value)))
  413. }
  414. }
  415. /*
  416. func (vm * VM) CallNamedFramed(name string, arguments ...) []Value {
  417. frame := vm.PushNewFrame()
  418. }
  419. */
  420. // ScopeUp Returns the levelth scope up from the current one where 0 is the
  421. // current scope. Returns the toplevel scope if l is greater than the current
  422. // scope stack depth.
  423. func (vm * VM) ScopeUp(level int) *Scope {
  424. scope := vm.Scope
  425. for now := 0; now < level; now++ {
  426. if scope.parent == nil {
  427. return scope
  428. }
  429. scope = scope.parent
  430. }
  431. return scope
  432. }
  433. // RegisterTop registers a value at top level scope.
  434. func (vm *VM) RegisterTop(name string, value Value) Value {
  435. scope := vm.TopScope
  436. return scope.Register(name, value)
  437. }
  438. // RegisterUp registers in level scopes up from the current scope,
  439. // or at toplevel if the level is greater than the total depth
  440. func (vm *VM) RegisterUp(name string, value Value, level int) Value {
  441. scope := vm.ScopeUp(level)
  442. return scope.Register(name, value)
  443. }
  444. func (vm *VM) Register(name string, value Value) Value {
  445. return vm.Scope.Register(name, value)
  446. }
  447. func (vm *VM) RegisterCover(name string, level int) *CoverValue {
  448. value := NewCoverValue(name)
  449. vm.RegisterUp(name, value, level)
  450. return value
  451. }
  452. func (vm *VM) RegisterBuiltin(name string, handler Handler) *BuiltinValue {
  453. value := NewBuiltinValue(name, handler)
  454. vm.Register(name, value)
  455. return value
  456. }
  457. func (vm *VM) RegisterDefined(name string, signature Signature, block *BlockValue, level int) *DefinedValue {
  458. value := NewDefinedValue(name, signature, block)
  459. vm.RegisterUp(name, value, level)
  460. return value
  461. }
  462. // RegisterBuiltinWithHelp
  463. func (vm *VM) RegisterBuiltinWithHelp(name string, handler Handler, help string) *BuiltinValue {
  464. res := vm.RegisterBuiltin(name, handler)
  465. vm.SetHelp(name, help)
  466. return res
  467. }
  468. func (vm *VM) Fail() {
  469. vm.Frame.failed = true
  470. }
  471. func (vm *VM) RunAst(ast Ast, args ...Value) []Value {
  472. var result []Value
  473. /*pos := ast.Token().Position
  474. vm.PushNewFrame(&pos)
  475. defer vm.PopFrame()
  476. */
  477. // vm.Logf("RunAst: %s\n", ast.Kind().String())
  478. // Leaf nodes, both declared and in practice are self evaluating.
  479. if ast.Kind().IsLeaf() || ast.CountChildren() < 1 {
  480. result = ast.Eval(vm)
  481. if vm.Frame.returned || vm.Frame.failed {
  482. result = vm.Frame.results
  483. vm.Frame.returned = false
  484. vm.Frame.failed = false
  485. }
  486. } else {
  487. var subResult = []Value{}
  488. // Depth first recursion.
  489. for i, child := range ast.Children() {
  490. sub := vm.RunAst(*child)
  491. subResult = append(subResult, sub...)
  492. vm.Trace("RunAst: %d %v %v %v\n", i, child, sub, vm.Frame)
  493. /*
  494. if frame.failed && frame.parent != nil {
  495. // XXX failures are like panics and propagate up the call tree
  496. * // Or should they?
  497. frame.parent.failed = true
  498. frame.parent.results = frame.results
  499. }
  500. */
  501. if vm.Frame.returned || vm.Frame.failed {
  502. subResult = vm.Frame.results
  503. vm.Frame.returned = false
  504. vm.Frame.failed = false
  505. break;
  506. }
  507. }
  508. // vm.Logf("RunAst subResult: %v\n", subResult)
  509. result = ast.Eval(vm, subResult...)
  510. }
  511. // vm.Logf("RunAst result: %v\n", result)
  512. return result
  513. }
  514. func (vm *VM) DefinedHelpers() []Helper {
  515. return vm.Scope.DefinedHelpers()
  516. }
  517. func (vm * VM) BackTraceFrames() []*Frame {
  518. bt := []*Frame{}
  519. for frame := vm.Frame ; frame.parent != nil ; frame = frame.parent {
  520. bt = append(bt, frame)
  521. }
  522. return bt
  523. }
  524. func (vm * VM) BackTracePositions() []*Position {
  525. bt := []*Position{}
  526. for frame := vm.Frame ; frame.parent != nil ; frame = frame.parent {
  527. bt = append(bt, frame.position)
  528. }
  529. return bt
  530. }
  531. func (vm * VM) BackTraceStrings() []string {
  532. bt := []string{}
  533. for frame := vm.Frame ; frame.parent != nil ; frame = frame.parent {
  534. bt = append(bt, frame.position.String())
  535. }
  536. return bt
  537. }
  538. func (vm * VM) BackTrace() string {
  539. return strings.Join(vm.BackTraceStrings(), "\n")
  540. }