vm.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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) Errf(format string, args...interface{}) {
  219. vm.Console.Errf(format, args...)
  220. }
  221. func (vm * VM) Errorf(format string, args...interface{}) error {
  222. return fmt.Errorf(format, args...)
  223. }
  224. func (vm * VM) AddOverloadCallable(from, target string, level int, callable Callable) error {
  225. var cover *CoverValue
  226. var ok bool
  227. lookup := vm.Lookup(from)
  228. if lookup == nil {
  229. cover = vm.RegisterCover(from, level)
  230. } else if cover, ok = lookup.(*CoverValue) ; !ok {
  231. return fmt.Errorf("%s exists and is not a cover value", from)
  232. }
  233. cover.AddOverloadCallable(target, callable)
  234. return nil
  235. }
  236. func (vm *VM) LookupCallable(target string) (Callable, error) {
  237. var callable Callable
  238. var ok bool
  239. lookup := vm.Lookup(target)
  240. if lookup == nil {
  241. return nil, fmt.Errorf("%s is not defined", target)
  242. }
  243. if callable, ok = lookup.(Callable) ; !ok {
  244. return nil, fmt.Errorf("%s is not a callable value", target)
  245. }
  246. return callable, nil
  247. }
  248. // AddOverloadByName overloads the from command to call the target command
  249. // if the argument list matches the signature based on the given type values
  250. func (vm * VM) AddOverload(from, target string, level int, tv... TypeValue) error {
  251. var cover *CoverValue
  252. var callable Callable
  253. var ok bool
  254. var err error
  255. lookup := vm.Lookup(from)
  256. if lookup == nil {
  257. cover = vm.RegisterCover(from, level)
  258. } else if cover, ok = lookup.(*CoverValue) ; !ok {
  259. return fmt.Errorf("%s exists and is not a cover value", from)
  260. }
  261. callable, err = vm.LookupCallable(target)
  262. if err != nil {
  263. return err
  264. }
  265. return cover.AddOverload(target, callable, tv...)
  266. }
  267. // AddOverloadByName overloads the from command to call the target command
  268. // if the argment lists matches the signature of the target command.
  269. func (vm * VM) AddOverloadByName(from, target string, level int) error {
  270. callable, err := vm.LookupCallable(target)
  271. if err != nil {
  272. return err
  273. }
  274. return vm.AddOverloadCallable(from, target, level, callable)
  275. }
  276. type OverloadDescription struct {
  277. Target string
  278. Types []TypeValue
  279. Level int
  280. }
  281. func (vm * VM) AddOverloads(from string, descriptions ... OverloadDescription) error {
  282. for _, od := range descriptions {
  283. err := vm.AddOverload(from, od.Target, od.Level, od.Types...)
  284. if err != nil {
  285. panic(fmt.Errorf("internal error: could not register overloads: %s", err))
  286. }
  287. }
  288. return nil
  289. }
  290. func Over(target string, level int, types ... TypeValue) OverloadDescription {
  291. return OverloadDescription { Target: target, Level: level, Types: types}
  292. }
  293. func (vm * VM) SetHelp(target, help string) error {
  294. var helper Helper
  295. var ok bool
  296. lookup := vm.Lookup(target)
  297. if lookup == nil {
  298. return fmt.Errorf("%s not found", target)
  299. } else if helper, ok = lookup.(Helper) ; !ok {
  300. return fmt.Errorf("%s exists but cannot set help text.", target)
  301. }
  302. helper.SetHelp(help)
  303. return nil
  304. }
  305. type Tracer interface {
  306. Trace(vm VM, fmt string, args ... interface{}) bool
  307. }
  308. // Virtual machine
  309. type VM struct {
  310. TopScope *Scope // Top level scope
  311. TopFrame *Frame // Top level scope
  312. *Scope // Current Scope
  313. *Frame // Current frame
  314. Tracer // Tracer to emit tracing info to, could be used for logging or debugging
  315. *Console // every VM has it's own virtual console.
  316. ExitStatus int
  317. }
  318. func NewVM() *VM {
  319. vm := &VM{NewScope(nil), NewFrame(nil, nil), nil, nil, nil, NewStdConsole(), 0}
  320. vm.Scope = vm.TopScope
  321. vm.Frame = vm.TopFrame
  322. return vm
  323. }
  324. func (vm *VM) Trace(fm string, args ... interface{}) {
  325. if vm.Tracer != nil {
  326. vm.Tracer.Trace(*vm, fm, args...)
  327. }
  328. }
  329. func (vm *VM) PushNewFrame(position *Position) *Frame {
  330. frame := NewFrame(vm.Frame, position)
  331. vm.Trace("PushFrame %v->%v\n", vm.Frame, frame)
  332. vm.Frame = frame
  333. return frame
  334. }
  335. func (vm *VM) PushNewScope() *Scope {
  336. scope := NewScope(vm.Scope)
  337. vm.Scope = scope
  338. return scope
  339. }
  340. func (vm *VM) Return(results ...Value) []Value {
  341. return results
  342. }
  343. func (vm *VM) PopFrame() *Frame {
  344. oldFrame := vm.Frame
  345. vm.Trace("PopFrame %v->%v\n", vm.Frame, vm.Frame.parent)
  346. if (vm.Frame != vm.TopFrame) && (vm.Frame.parent != nil) {
  347. frame := vm.Frame
  348. vm.Frame = frame.parent
  349. // Copy frame results up.
  350. vm.Frame.returned = oldFrame.returned
  351. vm.Frame.failed = oldFrame.failed
  352. vm.Frame.results = oldFrame.results
  353. return frame
  354. }
  355. return nil
  356. }
  357. func (vm *VM) PopScope() *Scope {
  358. if (vm.Scope != vm.TopScope) && (vm.Scope.parent != nil) {
  359. scope := vm.Scope
  360. vm.Scope = scope.parent
  361. return scope
  362. }
  363. return nil
  364. }
  365. func (block * BlockValue) Call(vm *VM, arguments ...Value) []Value {
  366. ast := block.Ast
  367. // Now, don't run the block itself but the Statements node
  368. // that should be in it.
  369. children := ast.Children()
  370. if len(children) < 1 {
  371. return Fail(fmt.Errorf("Block has no statements."))
  372. }
  373. if len(children) > 1 {
  374. return Fail(fmt.Errorf("Block has too many statements."))
  375. }
  376. statements := children[0]
  377. arr := vm.RunAst(*statements, arguments...)
  378. return arr
  379. }
  380. func (builtin * BuiltinValue) Call(vm *VM, arguments ...Value) []Value {
  381. err := builtin.signature.TypeCheck(arguments...)
  382. if err != nil {
  383. return Fail(ErrorValue{err})
  384. }
  385. handler := builtin.Handler
  386. return handler.Call(vm, arguments...)
  387. }
  388. func (vm *VM) AddTrace(err error) error {
  389. res := ""
  390. for frame := vm.Frame; frame != nil; frame = frame.parent {
  391. if frame.position == nil {
  392. res = fmt.Sprintf("%s\nIn frame %v", res, frame)
  393. } else {
  394. res = fmt.Sprintf("%s\nIn %s", res, frame.position.String())
  395. }
  396. }
  397. return fmt.Errorf("%s: %s", res, err)
  398. }
  399. func (vm *VM) CallCallable(callable Callable, arguments ...Value) []Value {
  400. defer vm.PopScope()
  401. defer vm.PopFrame()
  402. vm.PushNewFrame(callable.Position())
  403. vm.PushNewScope()
  404. result := callable.Call(vm, arguments...)
  405. return result
  406. }
  407. func (vm *VM) CallNamed(name string, arguments ...Value) []Value {
  408. value := vm.Lookup(name)
  409. if value == nil {
  410. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: not found.", name)))
  411. }
  412. if callable, ok := value.(Callable) ; ok {
  413. return vm.CallCallable(callable, arguments...)
  414. } else {
  415. return ReturnError(vm.AddTrace(NewErrorValuef("Cannot call %s: %v. Not callable", name, value)))
  416. }
  417. }
  418. /*
  419. func (vm * VM) CallNamedFramed(name string, arguments ...) []Value {
  420. frame := vm.PushNewFrame()
  421. }
  422. */
  423. // ScopeUp Returns the levelth scope up from the current one where 0 is the
  424. // current scope. Returns the toplevel scope if l is greater than the current
  425. // scope stack depth.
  426. func (vm * VM) ScopeUp(level int) *Scope {
  427. scope := vm.Scope
  428. for now := 0; now < level; now++ {
  429. if scope.parent == nil {
  430. return scope
  431. }
  432. scope = scope.parent
  433. }
  434. return scope
  435. }
  436. // RegisterTop registers a value at top level scope.
  437. func (vm *VM) RegisterTop(name string, value Value) Value {
  438. scope := vm.TopScope
  439. return scope.Register(name, value)
  440. }
  441. // RegisterUp registers in level scopes up from the current scope,
  442. // or at toplevel if the level is greater than the total depth
  443. func (vm *VM) RegisterUp(name string, value Value, level int) Value {
  444. scope := vm.ScopeUp(level)
  445. return scope.Register(name, value)
  446. }
  447. func (vm *VM) Register(name string, value Value) Value {
  448. return vm.Scope.Register(name, value)
  449. }
  450. func (vm *VM) RegisterCover(name string, level int) *CoverValue {
  451. value := NewCoverValue(name)
  452. vm.RegisterUp(name, value, level)
  453. return value
  454. }
  455. func (vm *VM) RegisterBuiltin(name string, handler Handler) *BuiltinValue {
  456. value := NewBuiltinValue(name, handler)
  457. vm.Register(name, value)
  458. return value
  459. }
  460. func (vm *VM) RegisterDefined(name string, signature Signature, block *BlockValue, level int) *DefinedValue {
  461. value := NewDefinedValue(name, signature, block)
  462. vm.RegisterUp(name, value, level)
  463. return value
  464. }
  465. // RegisterBuiltinWithHelp
  466. func (vm *VM) RegisterBuiltinWithHelp(name string, handler Handler, help string) *BuiltinValue {
  467. res := vm.RegisterBuiltin(name, handler)
  468. vm.SetHelp(name, help)
  469. return res
  470. }
  471. func (vm *VM) Fail() {
  472. vm.Frame.failed = true
  473. }
  474. func (vm *VM) RunAst(ast Ast, args ...Value) []Value {
  475. var result []Value
  476. /*pos := ast.Token().Position
  477. vm.PushNewFrame(&pos)
  478. defer vm.PopFrame()
  479. */
  480. // vm.Logf("RunAst: %s\n", ast.Kind().String())
  481. // Leaf nodes, both declared and in practice are self evaluating.
  482. if ast.Kind().IsLeaf() || ast.CountChildren() < 1 {
  483. result = ast.Eval(vm)
  484. if vm.Frame.returned || vm.Frame.failed {
  485. result = vm.Frame.results
  486. vm.Frame.returned = false
  487. vm.Frame.failed = false
  488. }
  489. } else {
  490. var subResult = []Value{}
  491. // Depth first recursion.
  492. for i, child := range ast.Children() {
  493. sub := vm.RunAst(*child)
  494. subResult = append(subResult, sub...)
  495. vm.Trace("RunAst: %d %v %v %v\n", i, child, sub, vm.Frame)
  496. /*
  497. if frame.failed && frame.parent != nil {
  498. // XXX failures are like panics and propagate up the call tree
  499. * // Or should they?
  500. frame.parent.failed = true
  501. frame.parent.results = frame.results
  502. }
  503. */
  504. if vm.Frame.returned || vm.Frame.failed {
  505. subResult = vm.Frame.results
  506. vm.Frame.returned = false
  507. vm.Frame.failed = false
  508. break;
  509. }
  510. }
  511. // vm.Logf("RunAst subResult: %v\n", subResult)
  512. result = ast.Eval(vm, subResult...)
  513. }
  514. // vm.Logf("RunAst result: %v\n", result)
  515. return result
  516. }
  517. func (vm *VM) DefinedHelpers() []Helper {
  518. return vm.Scope.DefinedHelpers()
  519. }
  520. func (vm * VM) BackTraceFrames() []*Frame {
  521. bt := []*Frame{}
  522. for frame := vm.Frame ; frame.parent != nil ; frame = frame.parent {
  523. bt = append(bt, frame)
  524. }
  525. return bt
  526. }
  527. func (vm * VM) BackTracePositions() []*Position {
  528. bt := []*Position{}
  529. for frame := vm.Frame ; frame.parent != nil ; frame = frame.parent {
  530. bt = append(bt, frame.position)
  531. }
  532. return bt
  533. }
  534. func (vm * VM) BackTraceStrings() []string {
  535. bt := []string{}
  536. for frame := vm.Frame ; frame.parent != nil ; frame = frame.parent {
  537. bt = append(bt, frame.position.String())
  538. }
  539. return bt
  540. }
  541. func (vm * VM) BackTrace() string {
  542. return strings.Join(vm.BackTraceStrings(), "\n")
  543. }