vm.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. // Callable value types
  14. type CallableValue struct {
  15. Name string
  16. }
  17. func (val CallableValue) String() string {
  18. return val.Name
  19. }
  20. func (val CallableValue) Type() TypeValue {
  21. return TypeValue("Callable")
  22. }
  23. func (from CallableValue) Convert(to interface{}) error {
  24. return NewErrorValuef("Cannot convert the callable value %v to %v", from, to)
  25. }
  26. func (val *CallableValue) Call(vm *VM, arguments ...Value) Value {
  27. panic("Not implemented")
  28. }
  29. // A struct to store a built in function
  30. type BuiltinValue struct {
  31. CallableValue
  32. Handler
  33. }
  34. func NewCallableValue(name string) CallableValue {
  35. return CallableValue{name}
  36. }
  37. func NewBuiltinValue(name string, handler Handler) BuiltinValue {
  38. result := BuiltinValue{}
  39. result.Name = name
  40. result.Handler = handler
  41. return result
  42. }
  43. func (builtin *BuiltinValue) Call(vm *VM, arguments ...Value) Value {
  44. return vm.CallBuiltin(builtin.Handler, arguments...)
  45. }
  46. // A script defined function
  47. type DefinedValue struct {
  48. CallableValue
  49. Definition *Ast
  50. }
  51. func NewDefinedValue(name string, definition *Ast) DefinedValue {
  52. result := DefinedValue{}
  53. result.Name = name
  54. result.Definition = definition
  55. return result
  56. }
  57. func (defined *DefinedValue) Call(vm *VM, arguments ...Value) Value {
  58. return vm.CallDefined(defined.Definition, arguments...)
  59. }
  60. /*
  61. Amount of types that will be considered inside a signature.
  62. Limited mosty to allow hashability.
  63. */
  64. const TypesInSignature = 8
  65. /* A signature describes the desired types of an overloaded function call. */
  66. type Signature struct {
  67. Types [TypesInSignature]TypeValue
  68. }
  69. func CalculateSignature(arguments ...Value) Signature {
  70. signature := Signature{}
  71. for i := 0; i < cap(signature.Types); i++ {
  72. if i > len(arguments) {
  73. signature.Types[i] = AnyTypeValue
  74. } else {
  75. signature.Types[i] = arguments[i].Type()
  76. }
  77. }
  78. return signature
  79. }
  80. func (signature *Signature) IsMatch(arguments ...Value) bool {
  81. for i, kind := range signature.Types {
  82. if i > len(arguments) || arguments[i] == nil {
  83. return false
  84. }
  85. if kind != arguments[i].Type() && kind != AnyTypeValue {
  86. return false
  87. }
  88. }
  89. return true
  90. }
  91. /* An overload is an overloaded callable value that can be called. */
  92. type Overload struct {
  93. CallableValue
  94. }
  95. /* A cover is a callable that dispatches to other callables depending on
  96. the types of the arguments, in particular the first one. The individual
  97. callable functions are the overloads
  98. */
  99. type CoverValue struct {
  100. CallableValue
  101. Overloads map[Signature]Overload
  102. }
  103. func NewCoverValue(name string) CoverValue {
  104. result := CoverValue{}
  105. result.Name = name
  106. result.Overloads = make(map[Signature]Overload)
  107. return result
  108. }
  109. func (cover *CoverValue) Call(vm *VM, arguments ...Value) Value {
  110. signature := CalculateSignature(arguments...)
  111. if overload, ok := cover.Overloads[signature]; ok {
  112. return overload.Call(vm, arguments...)
  113. } else {
  114. for signature, overload := range cover.Overloads {
  115. if signature.IsMatch(arguments...) {
  116. return overload.Call(vm, arguments...)
  117. }
  118. }
  119. }
  120. vm.Fail()
  121. return NewListValue(NewErrorValuef("Could not match cover %s with arguments.", cover.Name))
  122. }
  123. const (
  124. CoverTypeValue = TypeValue("Cover")
  125. BuiltinTypeValue = TypeValue("Builtin")
  126. DefinedTypeValue = TypeValue("Defined")
  127. )
  128. func (v CoverValue) Type() TypeValue { return CoverTypeValue }
  129. func (v BuiltinValue) Type() TypeValue { return BuiltinTypeValue }
  130. func (v DefinedValue) Type() TypeValue { return DefinedTypeValue }
  131. func (from CoverValue) Convert(to interface{}) error {
  132. return NewErrorValuef("Cannot convert the cover value %v to %v", from, to)
  133. }
  134. func (from BuiltinValue) Convert(to interface{}) error {
  135. return NewErrorValuef("Cannot convert the builtin value %v to %v", from, to)
  136. }
  137. func (from DefinedValue) Convert(to interface{}) error {
  138. return NewErrorValuef("Cannot convert the defined value %v to %v", from, to)
  139. }
  140. // Scope of symbols defined in the VM, hierarchical
  141. type Scope struct {
  142. parent *Scope
  143. children []*Scope
  144. symbols map[string]Value
  145. }
  146. func NewScope(parent *Scope) *Scope {
  147. return &Scope{parent, make([]*Scope, 0), make(map[string]Value)}
  148. }
  149. func (scope *Scope) Parent(level int) *Scope {
  150. if level < 1 {
  151. return scope
  152. }
  153. parent := scope.parent
  154. for parent != nil && level > 1 {
  155. level--
  156. parent = parent.parent
  157. }
  158. return parent
  159. }
  160. func (scope *Scope) Lookup(name string) Value {
  161. value, ok := scope.symbols[name]
  162. if ok {
  163. return value
  164. }
  165. if scope.parent != nil {
  166. return scope.parent.Lookup(name)
  167. }
  168. return NilValue
  169. }
  170. func (scope *Scope) Register(name string, value Value) Value {
  171. scope.symbols[name] = value
  172. return value
  173. }
  174. // Frame of execution of a function
  175. type Frame struct {
  176. parent *Frame
  177. arguments []Value
  178. results []Value
  179. failed bool
  180. }
  181. func NewFrame(parent *Frame) *Frame {
  182. return &Frame{parent, EmptyValueArray(), EmptyValueArray(), false}
  183. }
  184. type Tracer interface {
  185. Trace(vm VM, ast Ast, values ...Value) bool
  186. }
  187. // Virtual machine
  188. type VM struct {
  189. TopScope *Scope // Top level scope
  190. TopFrame *Frame // Top level scope
  191. *Scope // Current Scope
  192. *Frame // Current frame
  193. Tracer // Tracer to emit tracing info to, could be used for logging or debugging
  194. }
  195. func NewVM() *VM {
  196. vm := &VM{NewScope(nil), NewFrame(nil), nil, nil, nil}
  197. vm.Scope = vm.TopScope
  198. vm.Frame = vm.TopFrame
  199. return vm
  200. }
  201. func (vm *VM) PushNewFrame() *Frame {
  202. frame := NewFrame(vm.Frame)
  203. vm.Frame = frame
  204. return frame
  205. }
  206. func (vm *VM) PushNewScope() *Scope {
  207. scope := NewScope(vm.Scope)
  208. vm.Scope = scope
  209. return scope
  210. }
  211. func (vm *VM) PopFrame() *Frame {
  212. if (vm.Frame != vm.TopFrame) && (vm.Frame.parent != nil) {
  213. frame := vm.Frame
  214. vm.Frame = frame.parent
  215. return frame
  216. }
  217. return nil
  218. }
  219. func (vm *VM) PopScope() *Scope {
  220. if (vm.Scope != vm.TopScope) && (vm.Scope.parent != nil) {
  221. scope := vm.Scope
  222. vm.Scope = scope.parent
  223. return scope
  224. }
  225. return nil
  226. }
  227. func (vm *VM) CallDefined(ast *Ast, arguments ...Value) Value {
  228. arr := ast.Run(vm, NewListValue(arguments...))
  229. return arr
  230. }
  231. func (vm *VM) CallBuiltin(handler Handler, arguments ...Value) Value {
  232. return handler.Call(vm, arguments...)
  233. }
  234. func (vm *VM) CallCover(cover CoverValue, arguments ...Value) Value {
  235. return cover.Call(vm, arguments...)
  236. }
  237. func (vm *VM) CallNamed(name string, arguments ...Value) Value {
  238. value := vm.Lookup(name)
  239. switch toCall := value.(type) {
  240. case BuiltinValue:
  241. return vm.CallBuiltin(toCall.Handler, arguments...)
  242. case DefinedValue:
  243. return vm.CallDefined(toCall.Definition, arguments...)
  244. case CoverValue:
  245. return vm.CallCover(toCall, arguments...)
  246. default:
  247. return NewListValue(NewErrorValuef("Cannot call %s: %v", name, value))
  248. }
  249. }
  250. /*
  251. func (vm * VM) CallNamedFramed(name string, arguments ...) []Value {
  252. frame := vm.PushNewFrame()
  253. }
  254. */
  255. func (vm *VM) Register(name string, value Value) Value {
  256. return vm.Scope.Register(name, value)
  257. }
  258. func (vm *VM) RegisterCover(name string) Value {
  259. value := NewCoverValue(name)
  260. return vm.Register(name, value)
  261. }
  262. func (vm *VM) RegisterBuiltin(name string, handler Handler) Value {
  263. value := NewBuiltinValue(name, handler)
  264. return vm.Register(name, value)
  265. }
  266. func (vm *VM) RegisterDefined(name string, ast *Ast) Value {
  267. value := NewDefinedValue(name, ast)
  268. return vm.Register(name, value)
  269. }
  270. func (vm *VM) Fail() {
  271. vm.Frame.failed = true
  272. }
  273. func (vm *VM) RunChildren(ast Ast, args ...Value) Value {
  274. if ast.CountChildren() < 1 {
  275. return EmptyValue{}
  276. }
  277. /* if ast.CountChildren() == 1 {
  278. return ast.Child(0).Run(vm, args)
  279. }
  280. */
  281. result := NewListValue()
  282. for _, child := range ast.Children() {
  283. val := child.Run(vm, args...)
  284. // skip empty results
  285. if _, isEmpty := val.(EmptyValue); isEmpty {
  286. continue
  287. }
  288. // errors in the results take precendence and are propagated upwards.
  289. if err, isErr := val.(ErrorValue); isErr {
  290. return err
  291. }
  292. // Flatten lists
  293. /*
  294. if reslist, isList := val.(ListValue) ; isList && reslist.Length() > 0 {
  295. result.AppendList(reslist)
  296. }
  297. */
  298. result.Append(val)
  299. }
  300. return result
  301. }
  302. func (vm *VM) RunChildrenLastResult(ast Ast, args ...Value) Value {
  303. var result Value = EmptyValue{}
  304. for _, child := range ast.Children() {
  305. val := child.Run(vm, args...)
  306. // skip empty results
  307. if _, isEmpty := val.(EmptyValue); isEmpty {
  308. continue
  309. }
  310. // errors in the results take precendence and are propagated upwards.
  311. if err, isErr := val.(ErrorValue); isErr {
  312. return err
  313. }
  314. result = val
  315. }
  316. // The last non empty result is the result of this function.
  317. return result
  318. }
  319. func (vm *VM) RunChildrenFirstResult(ast Ast, args ...Value) Value {
  320. var result Value = EmptyValue{}
  321. for _, child := range ast.Children() {
  322. val := child.Run(vm, args...)
  323. // skip empty results
  324. if _, isEmpty := val.(EmptyValue); isEmpty {
  325. continue
  326. }
  327. // otherwise if non empty return the result.
  328. return val
  329. }
  330. return result
  331. }
  332. func (vm *VM) RunAst(ast Ast, args ...Value) Value {
  333. return ast.Run(vm, args...)
  334. }
  335. /*
  336. func (vm *VM) RunProgram(ast *BasicAst) ListValue {
  337. return vm.RunChildren(ast, (*VM).RunStatements)
  338. }
  339. func (vm *VM) RunStatements(ast *BasicAst) ListValue {
  340. return vm.RunChildren(ast, (*VM).RunStatement)
  341. }
  342. func (vm *VM) RunStatement(ast *BasicAst) ListValue {
  343. return NewListValue()
  344. }
  345. func (vm *VM) RunSet(ast *BasicAst) ListValue { return NewListValue() }
  346. func (vm *VM) RunGet(ast *BasicAst) ListValue { return NewListValue() }
  347. func (vm *VM) RunTarget(ast *BasicAst) ListValue { return NewListValue() }
  348. func (vm *VM) RunCommand(ast *BasicAst) ListValue { return NewListValue() }
  349. func (vm *VM) RunArguments(ast *BasicAst) ListValue { return NewListValue() }
  350. func (vm *VM) RunArgument(ast *BasicAst) ListValue { return NewListValue() }
  351. func (vm *VM) RunExpression(ast *BasicAst) ListValue { return NewListValue() }
  352. func (vm *VM) RunBlock(ast *BasicAst) ListValue { return NewListValue() }
  353. func (vm *VM) RunParenthesis(ast *BasicAst) ListValue { return NewListValue() }
  354. func (vm *VM) RunList(ast *BasicAst) ListValue { return NewListValue() }
  355. func (vm *VM) RunCapture(ast *BasicAst) ListValue { return NewListValue() }
  356. func (vm *VM) RunWordValue(ast *BasicAst) ListValue { return NewListValue() }
  357. func (vm *VM) RunWord(ast *BasicAst) ListValue { return NewListValue() }
  358. func (vm *VM) RunType(ast *BasicAst) ListValue { return NewListValue() }
  359. func (vm *VM) RunValue(ast *BasicAst) ListValue { return NewListValue() }
  360. func (vm *VM) RunEnd(ast *BasicAst) ListValue { return NewListValue() }
  361. func (vm *VM) RunError(ast *BasicAst) ListValue { return NewListValue() }
  362. func (vm *VM) Run(ast *BasicAst) ListValue {
  363. switch ast.AstKind {
  364. case AstKindProgram:
  365. return vm.RunProgram(ast)
  366. case AstKindStatements:
  367. return vm.RunStatements(ast)
  368. case AstKindStatement:
  369. return vm.RunStatement(ast)
  370. case AstKindSet:
  371. return vm.RunSet(ast)
  372. case AstKindGet:
  373. return vm.RunGet(ast)
  374. case AstKindTarget:
  375. return vm.RunTarget(ast)
  376. case AstKindCommand:
  377. return vm.RunCommand(ast)
  378. case AstKindArguments:
  379. return vm.RunArguments(ast)
  380. case AstKindArgument:
  381. return vm.RunArgument(ast)
  382. case AstKindExpression:
  383. return vm.RunExpression(ast)
  384. case AstKindBlock:
  385. return vm.RunBlock(ast)
  386. case AstKindParenthesis:
  387. return vm.RunParenthesis(ast)
  388. case AstKindList:
  389. return vm.RunList(ast)
  390. case AstKindCapture:
  391. return vm.RunCapture(ast)
  392. case AstKindWordValue:
  393. return vm.RunWordValue(ast)
  394. case AstKindWord:
  395. return vm.RunWord(ast)
  396. case AstKindType:
  397. return vm.RunType(ast)
  398. case AstKindValue:
  399. return vm.RunValue(ast)
  400. case AstKindEnd:
  401. return vm.RunEnd(ast)
  402. case AstKindError:
  403. return vm.RunError(ast)
  404. default:
  405. return ListValue{[]Value{NewErrorValuef("Unknown ast node type: %d", ast.AstKind)}}
  406. }
  407. }
  408. */