vm.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 Caller interface
  10. type Caller interface {
  11. Call(vm *VM, arguments ...Value) []Value
  12. }
  13. // A helper Value has a help text available.
  14. // This help text can be set as well.
  15. type Helper interface {
  16. Help() string
  17. SetHelp(string) string
  18. }
  19. // Callable value types
  20. type CallableValue struct {
  21. // Name of the callable
  22. Name string
  23. // Help string for the callable.
  24. HelpText string
  25. }
  26. // Implement Helper interface
  27. func (val CallableValue) Help() string {
  28. return val.HelpText
  29. }
  30. // Implement Helper interface
  31. func (val * CallableValue) SetHelp(help string) string {
  32. val.HelpText = help
  33. return val.HelpText
  34. }
  35. // AppendHelp appends help to an existing helper.
  36. func AppendHelp(helper Helper, extra string) string {
  37. return helper.SetHelp( helper.Help() + extra)
  38. }
  39. // ClearHelp rresets the help text to an empty string.
  40. func ClearHelp(helper Helper, extra string) string {
  41. return helper.SetHelp("")
  42. }
  43. func (val CallableValue) String() string {
  44. return val.Name
  45. }
  46. func (val CallableValue) Type() TypeValue {
  47. return TypeValue("Callable")
  48. }
  49. func (from CallableValue) Convert(to interface{}) error {
  50. return NewErrorValuef("Cannot convert the callable value %v to %v", from, to)
  51. }
  52. func (val *CallableValue) Call(vm *VM, arguments ...Value) []Value {
  53. panic("Not implemented")
  54. }
  55. // A struct to store a built in function
  56. type BuiltinValue struct {
  57. CallableValue
  58. Handler
  59. }
  60. func NewCallableValue(name string) CallableValue {
  61. return CallableValue{name, ""}
  62. }
  63. func NewBuiltinValue(name string, handler Handler) *BuiltinValue {
  64. result := &BuiltinValue{}
  65. result.Name = name
  66. result.Handler = handler
  67. return result
  68. }
  69. func (builtin *BuiltinValue) Call(vm *VM, arguments ...Value) []Value {
  70. return vm.CallBuiltin(builtin.Handler, arguments...)
  71. }
  72. // A block in a script.
  73. type BlockValue struct {
  74. CallableValue
  75. Ast *Ast
  76. }
  77. func NewBlockValue(definition *Ast) *BlockValue {
  78. result := &BlockValue{}
  79. result.Name = fmt.Sprintf("<block:%s>", definition.String())
  80. result.Ast = definition
  81. return result
  82. }
  83. func (block *BlockValue) Call(vm *VM, arguments ...Value) []Value {
  84. res := vm.CallBlock(block.Ast, arguments...)
  85. return res
  86. }
  87. /* Parameters for a defined value */
  88. type Parameter struct {
  89. Name WordValue
  90. Type TypeValue
  91. }
  92. // A script defined function
  93. type DefinedValue struct {
  94. CallableValue
  95. Body *BlockValue
  96. Parameters []*Parameter
  97. }
  98. func NewDefinedValue(name string, params []*Parameter, body *BlockValue) *DefinedValue {
  99. result := &DefinedValue{}
  100. result.Name = name
  101. result.Body = body
  102. result.Parameters = params
  103. return result
  104. }
  105. func (defined *DefinedValue) Call(vm *VM, arguments ...Value) []Value {
  106. defer vm.PopFrame()
  107. defer vm.PopScope()
  108. vm.PushNewFrame()
  109. vm.PushNewScope()
  110. for i , arg := range arguments {
  111. if i >= len(defined.Parameters) {
  112. break
  113. }
  114. param := defined.Parameters[i]
  115. expectedType := param.Type
  116. if !expectedType.IsMatch(arg.Type()) {
  117. return Fail(NewErrorValuef("Argument %d type mismatch: %s<->%s", i, expectedType, arg.Type()))
  118. }
  119. vm.Register(param.Name.String(), arg)
  120. }
  121. res := defined.Body.Call(vm, arguments...)
  122. return res
  123. }
  124. /*
  125. Amount of types that will be considered inside a signature.
  126. Limited mosty to allow hashability.
  127. */
  128. const TypesInSignature = 8
  129. /* A signature describes the desired types of an overloaded function call. */
  130. type Signature struct {
  131. Types [TypesInSignature]TypeValue
  132. }
  133. func CalculateSignature(arguments ...Value) Signature {
  134. signature := Signature{}
  135. for i := 0; i < len(signature.Types); i++ {
  136. if i < len(arguments) {
  137. signature.Types[i] = arguments[i].Type()
  138. } else {
  139. signature.Types[i] = AnyTypeValue
  140. }
  141. }
  142. return signature
  143. }
  144. func (tv TypeValue) IsMatch(other TypeValue) bool {
  145. if tv == AnyTypeValue || other == AnyTypeValue {
  146. return true
  147. }
  148. if tv == ZeroTypeValue || other == ZeroTypeValue {
  149. return true
  150. }
  151. return tv == other
  152. }
  153. func (signature Signature) IsMatch(other Signature) bool {
  154. for i, kind := range signature.Types {
  155. t1 := kind
  156. t2 := other.Types[i]
  157. if !t1.IsMatch(t2) {
  158. return false
  159. }
  160. }
  161. return true
  162. }
  163. /* An overload is an overloaded value that can be called. */
  164. type Overload struct {
  165. Caller
  166. }
  167. /* A cover is a callable that dispatches to other callables depending on
  168. the types of the arguments, in particular the first one. The individual
  169. callable functions are the overloads
  170. */
  171. type CoverValue struct {
  172. CallableValue
  173. Overloads map[Signature]Overload
  174. }
  175. func (cv CoverValue) String() string {
  176. res := fmt.Sprintf("cover %s [ ", cv.Name)
  177. for k, v := range cv.Overloads {
  178. res = fmt.Sprintf("%s [%v] %v", res, k, v.Caller)
  179. }
  180. res = fmt.Sprintf("%s].", res)
  181. return res;
  182. }
  183. func NewCoverValue(name string) *CoverValue {
  184. result := &CoverValue{}
  185. result.Name = name
  186. result.Overloads = make(map[Signature]Overload)
  187. return result
  188. }
  189. func (cover *CoverValue) Call(vm *VM, arguments ...Value) []Value {
  190. signature := CalculateSignature(arguments...)
  191. if overload, ok := cover.Overloads[signature]; ok {
  192. return overload.Call(vm, arguments...)
  193. } else {
  194. for overloadSignature, overload := range cover.Overloads {
  195. if signature.IsMatch(overloadSignature) {
  196. return overload.Call(vm, arguments...)
  197. }
  198. }
  199. }
  200. vm.Fail()
  201. return Fail(NewErrorValuef("Could not match cover %s with arguments: %s<->%v", cover.String(), signature))
  202. }
  203. const (
  204. CoverTypeValue = TypeValue("Cover")
  205. BuiltinTypeValue = TypeValue("Builtin")
  206. DefinedTypeValue = TypeValue("Defined")
  207. BlockTypeValue = TypeValue("Block")
  208. )
  209. func (v CoverValue) Type() TypeValue { return CoverTypeValue }
  210. func (v BuiltinValue) Type() TypeValue { return BuiltinTypeValue }
  211. func (v DefinedValue) Type() TypeValue { return DefinedTypeValue }
  212. func (v BlockValue) Type() TypeValue { return BlockTypeValue }
  213. func (from CoverValue) Convert(to interface{}) error {
  214. return NewErrorValuef("Cannot convert the cover value %v to %v", from, to)
  215. }
  216. func (from BuiltinValue) Convert(to interface{}) error {
  217. return NewErrorValuef("Cannot convert the builtin value %v to %v", from, to)
  218. }
  219. func (from DefinedValue) Convert(to interface{}) error {
  220. return NewErrorValuef("Cannot convert the defined value %v to %v", from, to)
  221. }
  222. func (from BlockValue) Convert(to interface{}) error {
  223. if toValue, isOk := to.(*BlockValue) ; isOk {
  224. (*toValue) = from
  225. return nil
  226. }
  227. return NewErrorValuef("Cannot convert the block value %v to %v", from, to)
  228. }
  229. func (cv * CoverValue) AddOverload(callable Caller, tv ... TypeValue) error {
  230. // fmt.Printf("AddOverload: %v\n", tv)
  231. signature := Signature{}
  232. length := len(tv)
  233. if length > len(signature.Types) {
  234. length = len(signature.Types)
  235. }
  236. for i := 0; i < length; i++ {
  237. signature.Types[i] = tv[i]
  238. }
  239. cv.Overloads[signature] = Overload { callable }
  240. // fmt.Printf("Overloads: %v\n", cv.Overloads)
  241. return nil
  242. }
  243. func (vm * VM) AddOverload(from, target string, tv... TypeValue) error {
  244. var cover *CoverValue
  245. var callable Caller
  246. var ok bool
  247. lookup := vm.Lookup(from)
  248. if lookup == nil {
  249. cover = vm.RegisterCover(from)
  250. } else if cover, ok = lookup.(*CoverValue) ; !ok {
  251. return fmt.Errorf("%s exists and is not a cover value", from)
  252. }
  253. // fmt.Printf("AddOverload: %v %v\n", lookup, cover)
  254. lookup = vm.Lookup(target)
  255. if lookup == nil {
  256. return fmt.Errorf("target %s is not defined", target)
  257. }
  258. // fmt.Printf("AddOverload lookup: %v\n", lookup)
  259. if callable, ok = lookup.(Caller) ; !ok {
  260. return fmt.Errorf("%s is not a callable value", target)
  261. }
  262. res := cover.AddOverload(callable, tv...)
  263. // fmt.Printf("AddOverload: %v %v\n", lookup, cover)
  264. return res
  265. }
  266. func (vm * VM) SetHelp(target, help string) error {
  267. var helper Helper
  268. var ok bool
  269. lookup := vm.Lookup(target)
  270. if lookup == nil {
  271. return fmt.Errorf("%s not found", target)
  272. } else if helper, ok = lookup.(Helper) ; !ok {
  273. return fmt.Errorf("%s exists but cannot set help text.", target)
  274. }
  275. helper.SetHelp(help)
  276. return nil
  277. }
  278. // Scope of symbols defined in the VM, hierarchical
  279. type Scope struct {
  280. parent *Scope
  281. children []*Scope
  282. symbols map[string]Value
  283. }
  284. func NewScope(parent *Scope) *Scope {
  285. return &Scope{parent, make([]*Scope, 0), make(map[string]Value)}
  286. }
  287. func (scope *Scope) Parent(level int) *Scope {
  288. if level < 1 {
  289. return scope
  290. }
  291. parent := scope.parent
  292. for parent != nil && level > 1 {
  293. level--
  294. parent = parent.parent
  295. }
  296. return parent
  297. }
  298. func (scope *Scope) Lookup(name string) Value {
  299. value, ok := scope.symbols[name]
  300. if ok {
  301. return value
  302. }
  303. if scope.parent != nil {
  304. return scope.parent.Lookup(name)
  305. }
  306. return NilValue
  307. }
  308. func (scope *Scope) Register(name string, value Value) Value {
  309. scope.symbols[name] = value
  310. return value
  311. }
  312. // Frame of execution of a function
  313. type Frame struct {
  314. parent *Frame
  315. arguments []Value
  316. results []Value
  317. failed bool
  318. }
  319. func NewFrame(parent *Frame) *Frame {
  320. return &Frame{parent, EmptyValueArray(), EmptyValueArray(), false}
  321. }
  322. type Tracer interface {
  323. Trace(vm VM, ast Ast, values ...Value) bool
  324. }
  325. // Virtual machine
  326. type VM struct {
  327. TopScope *Scope // Top level scope
  328. TopFrame *Frame // Top level scope
  329. *Scope // Current Scope
  330. *Frame // Current frame
  331. Tracer // Tracer to emit tracing info to, could be used for logging or debugging
  332. ExitStatus int
  333. }
  334. func NewVM() *VM {
  335. vm := &VM{NewScope(nil), NewFrame(nil), nil, nil, nil, 0}
  336. vm.Scope = vm.TopScope
  337. vm.Frame = vm.TopFrame
  338. return vm
  339. }
  340. func (vm *VM) PushNewFrame() *Frame {
  341. frame := NewFrame(vm.Frame)
  342. vm.Frame = frame
  343. return frame
  344. }
  345. func (vm *VM) PushNewScope() *Scope {
  346. scope := NewScope(vm.Scope)
  347. vm.Scope = scope
  348. return scope
  349. }
  350. func (vm *VM) PopFrame() *Frame {
  351. if (vm.Frame != vm.TopFrame) && (vm.Frame.parent != nil) {
  352. frame := vm.Frame
  353. vm.Frame = frame.parent
  354. return frame
  355. }
  356. return nil
  357. }
  358. func (vm *VM) PopScope() *Scope {
  359. if (vm.Scope != vm.TopScope) && (vm.Scope.parent != nil) {
  360. scope := vm.Scope
  361. vm.Scope = scope.parent
  362. return scope
  363. }
  364. return nil
  365. }
  366. func (vm *VM) CallDefined(ast *Ast, arguments ...Value) []Value {
  367. arr := ast.Run(vm, NewListValue(arguments...))
  368. return arr
  369. }
  370. func (vm *VM) CallBlock(ast *Ast, arguments ...Value) []Value {
  371. arr := vm.RunChildren(*ast, arguments...)
  372. return arr
  373. }
  374. func (vm *VM) CallBuiltin(handler Handler, arguments ...Value) []Value {
  375. return handler.Call(vm, arguments...)
  376. }
  377. func (vm *VM) CallCover(cover * CoverValue, arguments ...Value) []Value {
  378. return cover.Call(vm, arguments...)
  379. }
  380. func (vm *VM) CallNamed(name string, arguments ...Value) []Value {
  381. value := vm.Lookup(name)
  382. switch toCall := value.(type) {
  383. case *BuiltinValue:
  384. return vm.CallBuiltin(toCall.Handler, arguments...)
  385. case *DefinedValue:
  386. return vm.CallDefined(toCall.Body.Ast, arguments...)
  387. case *CoverValue:
  388. return vm.CallCover(toCall, arguments...)
  389. case *BlockValue:
  390. return vm.CallBlock(toCall.Ast, arguments...)
  391. default:
  392. return ReturnError(NewErrorValuef("Cannot call %s: %v", name, value))
  393. }
  394. }
  395. /*
  396. func (vm * VM) CallNamedFramed(name string, arguments ...) []Value {
  397. frame := vm.PushNewFrame()
  398. }
  399. */
  400. func (vm *VM) Register(name string, value Value) Value {
  401. return vm.Scope.Register(name, value)
  402. }
  403. func (vm *VM) RegisterCover(name string) *CoverValue {
  404. value := NewCoverValue(name)
  405. vm.Register(name, value)
  406. return value
  407. }
  408. func (vm *VM) RegisterBuiltin(name string, handler Handler) Value {
  409. value := NewBuiltinValue(name, handler)
  410. return vm.Register(name, value)
  411. }
  412. func (vm *VM) RegisterDefined(name string, params []*Parameter, block *BlockValue) Value {
  413. value := NewDefinedValue(name, params, block)
  414. return vm.Register(name, value)
  415. }
  416. // RegisterBuiltinWithHelp
  417. func (vm *VM) RegisterBuiltinWithHelp(name string, handler Handler, help string) Value {
  418. res := vm.RegisterBuiltin(name, handler)
  419. vm.SetHelp(name, help)
  420. return res
  421. }
  422. func (vm *VM) Fail() {
  423. vm.Frame.failed = true
  424. }
  425. func (vm *VM) RunChildren(ast Ast, args ...Value) []Value {
  426. if ast.CountChildren() < 1 {
  427. return ReturnEmpty()
  428. }
  429. /* if ast.CountChildren() == 1 {
  430. return ast.Child(0).Run(vm, args)
  431. }
  432. */
  433. result := []Value{}
  434. for _, child := range ast.Children() {
  435. val := child.Run(vm, args...)
  436. // skip empty results
  437. if len(val) < 1 {
  438. continue
  439. }
  440. first := val[0]
  441. if _, isEmpty := first.(EmptyValue); isEmpty {
  442. continue
  443. }
  444. last := val[len(val) -1]
  445. // errors in the results at the last position take precendence and are propagated upwards.
  446. if _, isErr := last.(ErrorValue); isErr {
  447. return val
  448. }
  449. result = append(result, val...)
  450. }
  451. return result
  452. }
  453. func (vm *VM) RunChildrenLastResult(ast Ast, args ...Value) Value {
  454. var result Value = EmptyValue{}
  455. for _, child := range ast.Children() {
  456. val := child.Run(vm, args...)
  457. // skip empty results
  458. if len(val) < 1 {
  459. continue
  460. }
  461. first := val[0]
  462. if _, isEmpty := first.(EmptyValue); isEmpty {
  463. continue
  464. }
  465. last := val[len(val) -1]
  466. // errors in the results at the last position take precendence and are propagated upwards.
  467. if _, isErr := last.(ErrorValue); isErr {
  468. return last
  469. }
  470. result = last
  471. }
  472. // The last non empty result is the result of this function.
  473. return result
  474. }
  475. func (vm *VM) RunChildrenFirstResult(ast Ast, args ...Value) Value {
  476. var result Value = EmptyValue{}
  477. for _, child := range ast.Children() {
  478. val := child.Run(vm, args...)
  479. // skip empty results
  480. if len(val) < 1 {
  481. continue
  482. }
  483. first := val[0]
  484. if _, isEmpty := first.(EmptyValue); isEmpty {
  485. continue
  486. }
  487. // otherwise if non empty return the result.
  488. return first
  489. }
  490. return result
  491. }
  492. func (vm *VM) RunAst(ast Ast, args ...Value) []Value {
  493. return ast.Run(vm, args...)
  494. }
  495. /*
  496. func (vm *VM) RunProgram(ast *BasicAst) ListValue {
  497. return vm.RunChildren(ast, (*VM).RunStatements)
  498. }
  499. func (vm *VM) RunStatements(ast *BasicAst) ListValue {
  500. return vm.RunChildren(ast, (*VM).RunStatement)
  501. }
  502. func (vm *VM) RunStatement(ast *BasicAst) ListValue {
  503. return NewListValue()
  504. }
  505. func (vm *VM) RunSet(ast *BasicAst) ListValue { return NewListValue() }
  506. func (vm *VM) RunGet(ast *BasicAst) ListValue { return NewListValue() }
  507. func (vm *VM) RunTarget(ast *BasicAst) ListValue { return NewListValue() }
  508. func (vm *VM) RunCommand(ast *BasicAst) ListValue { return NewListValue() }
  509. func (vm *VM) RunArguments(ast *BasicAst) ListValue { return NewListValue() }
  510. func (vm *VM) RunArgument(ast *BasicAst) ListValue { return NewListValue() }
  511. func (vm *VM) RunExpression(ast *BasicAst) ListValue { return NewListValue() }
  512. func (vm *VM) RunBlock(ast *BasicAst) ListValue { return NewListValue() }
  513. func (vm *VM) RunParenthesis(ast *BasicAst) ListValue { return NewListValue() }
  514. func (vm *VM) RunList(ast *BasicAst) ListValue { return NewListValue() }
  515. func (vm *VM) RunCapture(ast *BasicAst) ListValue { return NewListValue() }
  516. func (vm *VM) RunWordValue(ast *BasicAst) ListValue { return NewListValue() }
  517. func (vm *VM) RunWord(ast *BasicAst) ListValue { return NewListValue() }
  518. func (vm *VM) RunType(ast *BasicAst) ListValue { return NewListValue() }
  519. func (vm *VM) RunValue(ast *BasicAst) ListValue { return NewListValue() }
  520. func (vm *VM) RunEnd(ast *BasicAst) ListValue { return NewListValue() }
  521. func (vm *VM) RunError(ast *BasicAst) ListValue { return NewListValue() }
  522. func (vm *VM) Run(ast *BasicAst) ListValue {
  523. switch ast.AstKind {
  524. case AstKindProgram:
  525. return vm.RunProgram(ast)
  526. case AstKindStatements:
  527. return vm.RunStatements(ast)
  528. case AstKindStatement:
  529. return vm.RunStatement(ast)
  530. case AstKindSet:
  531. return vm.RunSet(ast)
  532. case AstKindGet:
  533. return vm.RunGet(ast)
  534. case AstKindTarget:
  535. return vm.RunTarget(ast)
  536. case AstKindCommand:
  537. return vm.RunCommand(ast)
  538. case AstKindArguments:
  539. return vm.RunArguments(ast)
  540. case AstKindArgument:
  541. return vm.RunArgument(ast)
  542. case AstKindExpression:
  543. return vm.RunExpression(ast)
  544. case AstKindBlock:
  545. return vm.RunBlock(ast)
  546. case AstKindParenthesis:
  547. return vm.RunParenthesis(ast)
  548. case AstKindList:
  549. return vm.RunList(ast)
  550. case AstKindCapture:
  551. return vm.RunCapture(ast)
  552. case AstKindWordValue:
  553. return vm.RunWordValue(ast)
  554. case AstKindWord:
  555. return vm.RunWord(ast)
  556. case AstKindType:
  557. return vm.RunType(ast)
  558. case AstKindValue:
  559. return vm.RunValue(ast)
  560. case AstKindEnd:
  561. return vm.RunEnd(ast)
  562. case AstKindError:
  563. return vm.RunError(ast)
  564. default:
  565. return ListValue{[]Value{NewErrorValuef("Unknown ast node type: %d", ast.AstKind)}}
  566. }
  567. }
  568. */