builtin.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package muesli
  2. import "fmt"
  3. import "log"
  4. import "runtime"
  5. import "strings"
  6. import "sort"
  7. type LogTracer struct {
  8. }
  9. func (t LogTracer) Trace(vm VM, fmt string, args ... interface{}) bool {
  10. args = append([]interface{}{vm.BackTrace()}, args...)
  11. log.Printf("%s: " + fmt, args...)
  12. return false
  13. }
  14. type FmtTracer struct {
  15. }
  16. func (t FmtTracer) Trace(vm VM, fm string, args ... interface{}) bool {
  17. args = append([]interface{}{vm.BackTrace()}, args...)
  18. fmt.Printf("%s: " + fm + "\n", args...)
  19. return false
  20. }
  21. func printf(vm *VM, args ...Value) []Value {
  22. var format string
  23. rest, err := ParseArgs(args, &format)
  24. if err != nil {
  25. return Fail(err)
  26. }
  27. extra := ListFromList(rest)
  28. fmt.Printf(format, extra...)
  29. return None()
  30. }
  31. func println(vm *VM, args ...Value) []Value {
  32. var msg string
  33. _, err := ParseArgs(args, &msg)
  34. if err != nil {
  35. return Fail(err)
  36. } else {
  37. fmt.Println(msg)
  38. }
  39. return None()
  40. }
  41. func p(vm *VM, args ...Value) []Value {
  42. for _, arg := range args {
  43. fmt.Printf("%v\n", arg)
  44. }
  45. return None()
  46. }
  47. func trace(vm *VM, args ...Value) []Value {
  48. var b bool = true
  49. fmt.Printf("command trace: %v\n", args)
  50. _, err := ParseArgs(args, &b)
  51. if err != nil {
  52. fmt.Printf("Error: %s\n", err.Error())
  53. return Fail(err)
  54. }
  55. fmt.Printf("command trace: bool: %v\n", b)
  56. if b {
  57. vm.Tracer = FmtTracer{}
  58. } else {
  59. vm.Tracer = nil
  60. }
  61. return Ok(BoolValue(b))
  62. }
  63. func sumi(vm *VM, args ...Value) []Value {
  64. slice, err := ParseArgsToIntSlice(args)
  65. if err != nil {
  66. fmt.Printf("Error: %s\n", err.Error())
  67. return Fail(err)
  68. }
  69. res := int(0)
  70. for _, val := range slice {
  71. res += val
  72. }
  73. return IntOk(res)
  74. }
  75. func sumf(vm *VM, args ...Value) []Value {
  76. slice, err := ParseArgsToFloat64Slice(args)
  77. if err != nil {
  78. fmt.Printf("Error: %s\n", err.Error())
  79. return Fail(err)
  80. }
  81. res := float64(0)
  82. for _, val := range slice {
  83. res += val
  84. }
  85. return FloatOk(res)
  86. }
  87. func addi(vm *VM, args ...Value) []Value {
  88. var v1, v2 int
  89. _, err := ParseArgs(args, &v1, &v2)
  90. if err != nil {
  91. return Fail(err)
  92. }
  93. return IntOk(v1 + v2)
  94. }
  95. func addf(vm *VM, args ...Value) []Value {
  96. var v1, v2 float64
  97. _, err := ParseArgs(args, &v1, &v2)
  98. if err != nil {
  99. return Fail(err)
  100. }
  101. return FloatOk(v1 + v2)
  102. }
  103. func subi(vm *VM, args ...Value) []Value {
  104. var v1, v2 int
  105. _, err := ParseArgs(args, &v1, &v2)
  106. if err != nil {
  107. return Fail(err)
  108. }
  109. return IntOk(v1 - v2)
  110. }
  111. func subf(vm *VM, args ...Value) []Value {
  112. var v1, v2 float64
  113. _, err := ParseArgs(args, &v1, &v2)
  114. if err != nil {
  115. return Fail(err)
  116. }
  117. return FloatOk(v1 - v2)
  118. }
  119. func muli(vm *VM, args ...Value) []Value {
  120. var v1, v2 int
  121. _, err := ParseArgs(args, &v1, &v2)
  122. if err != nil {
  123. return Fail(err)
  124. }
  125. return IntOk(v1 * v2)
  126. }
  127. func mulf(vm *VM, args ...Value) []Value {
  128. var v1, v2 float64
  129. _, err := ParseArgs(args, &v1, &v2)
  130. if err != nil {
  131. return Fail(err)
  132. }
  133. return FloatOk(v1 * v2)
  134. }
  135. func divi(vm *VM, args ...Value) []Value {
  136. var v1, v2 int
  137. _, err := ParseArgs(args, &v1, &v2)
  138. if err != nil {
  139. return Fail(err)
  140. }
  141. return IntOk(v1 / v2)
  142. }
  143. func divf(vm *VM, args ...Value) []Value {
  144. var v1, v2 float64
  145. _, err := ParseArgs(args, &v1, &v2)
  146. if err != nil {
  147. return Fail(err)
  148. }
  149. return FloatOk(v1 / v2)
  150. }
  151. func andb(vm * VM, args ...Value) []Value {
  152. var v1, v2 bool
  153. _, err := ParseArgs(args, &v1, &v2)
  154. if err != nil {
  155. return Fail(err)
  156. }
  157. return BoolOk(v1 && v2)
  158. }
  159. func orb(vm * VM, args ...Value) []Value {
  160. var v1, v2 bool
  161. _, err := ParseArgs(args, &v1, &v2)
  162. if err != nil {
  163. return Fail(err)
  164. }
  165. return BoolOk(v1 || v2)
  166. }
  167. func val(vm *VM, args ...Value) []Value {
  168. if len(args) < 1 {
  169. return []Value{NewErrorValuef("val requres at least one argument.")}
  170. }
  171. return args
  172. }
  173. func builtin_return(vm *VM, args ...Value) []Value {
  174. vm.Frame.returned = true
  175. vm.Frame.results = args
  176. vm.Trace("Returning... %v", vm.Frame)
  177. return args
  178. }
  179. func to(vm *VM, args ...Value) []Value {
  180. var name string
  181. rest, err := ParseArgs(args, &name)
  182. if err != nil {
  183. return Fail(err)
  184. }
  185. if len(rest) < 1 {
  186. return Fail(NewErrorValuef("Need at least 2 arguments: %v", args))
  187. }
  188. last := rest[len(rest)-1]
  189. block, isBlock := last.(*BlockValue)
  190. if ! isBlock {
  191. return Fail(NewErrorValuef("Not a block: %v", last))
  192. }
  193. param := rest[0:len(rest)-1]
  194. defpars := []*Parameter{}
  195. for i := 1 ; i < len(param) ; i += 2 {
  196. par := &Parameter{}
  197. name := param[i-1]
  198. typ := param[i]
  199. var ok bool
  200. if par.Name, ok = name.(WordValue); !ok {
  201. return Fail(NewErrorValuef("Not a word value: %v", name))
  202. }
  203. if par.Type, ok = typ.(TypeValue); !ok {
  204. return Fail(NewErrorValuef("Not a type value: %v", typ))
  205. }
  206. defpars = append(defpars, par)
  207. }
  208. // To must register one level up.
  209. return Ok(vm.RegisterDefined(name, defpars, block, 1))
  210. }
  211. func cover(vm *VM, args ...Value) []Value {
  212. var name, target string
  213. rest, err := ParseArgs(args, &name, &target)
  214. if err != nil {
  215. return Fail(err)
  216. }
  217. types := []TypeValue{}
  218. for i, arg := range rest {
  219. if typ, ok := arg.(TypeValue) ; ok {
  220. types = append(types, typ)
  221. } else {
  222. return Fail(NewErrorValuef("Argument %d: not a type: %v %s", i+2, arg, arg.String()))
  223. }
  224. }
  225. // Overload must be defined one scope up.
  226. err = vm.AddOverload(name, target, 1, types...)
  227. if err != nil {
  228. return Fail(err)
  229. }
  230. return Ok()
  231. }
  232. func types(vm *VM, args ...Value) []Value {
  233. result := []Value{}
  234. for i, arg := range args {
  235. typ := arg.Type()
  236. result = append(result, typ)
  237. fmt.Printf("Type %d: %s\n", i, typ.String())
  238. }
  239. return Ok(NewListValue(result...))
  240. }
  241. func set(vm *VM, val ...Value) []Value {
  242. if len(val) < 2 {
  243. return Fail(fmt.Errorf("set needs at least 2 arguments: received %v", val))
  244. }
  245. target := val[0].String()
  246. value := val[1]
  247. if target == "(" || target == "$" {
  248. if len(val) < 3 {
  249. return Fail(fmt.Errorf("indirect get needs results: received %v", val))
  250. }
  251. target = val[1].String()
  252. value = val[2]
  253. }
  254. vm.RegisterUp(target, value, 1)
  255. return Ok(value)
  256. }
  257. func get(vm *VM, val ...Value) []Value {
  258. if len(val) < 1 {
  259. return Fail(fmt.Errorf("get needs at least 1 argument"))
  260. }
  261. target := val[0].String()
  262. if target == "(" || target == "$" {
  263. if len(val) < 2 {
  264. return Fail(fmt.Errorf("indirect get needs results: received %v", val))
  265. }
  266. target = val[1].String()
  267. }
  268. return Ok(vm.Lookup(target))
  269. }
  270. func fetchl(vm *VM, args ...Value) []Value {
  271. var index int
  272. var list *ListValue
  273. _, err := ParseArgs(args, &list, &index)
  274. if err != nil {
  275. return Fail(err)
  276. }
  277. return Ok(list.List[index])
  278. }
  279. func storel(vm *VM, args ...Value) []Value {
  280. var index int
  281. var list *ListValue
  282. rest, err := ParseArgs(args, &list, &index)
  283. if err != nil {
  284. return Fail(err)
  285. }
  286. if len (rest) < 1 {
  287. return Fail(fmt.Errorf("fetch: need 3 arguments"))
  288. }
  289. list.List[index] = rest[0]
  290. return Ok(list.List[index])
  291. }
  292. func fetchm(vm *VM, args ...Value) []Value {
  293. var index Value
  294. var hmap *MapValue
  295. _, err := ParseArgs(args, &hmap, &index)
  296. if err != nil {
  297. return Fail(err)
  298. }
  299. return Ok(hmap.Map[index])
  300. }
  301. func storem(vm *VM, args ...Value) []Value {
  302. var index Value
  303. var hmap *MapValue
  304. rest, err := ParseArgs(args, &hmap, &index)
  305. if err != nil {
  306. return Fail(err)
  307. }
  308. if len (rest) < 1 {
  309. return Fail(fmt.Errorf("fetch: need 3 arguments"))
  310. }
  311. hmap.Map[index] = rest[0]
  312. return Ok(hmap.Map[index])
  313. }
  314. func newmap(vm *VM, args ...Value) []Value {
  315. result := make(map[Value] Value)
  316. for i := 1; i < len(args) ; i+=2 {
  317. result[args[i-1]] = args[i]
  318. }
  319. return Ok(NewMapValue(result))
  320. }
  321. func help(vm *VM, val ...Value) [] Value {
  322. if len(val) < 1 {
  323. fmt.Printf("help <callable> will display help on the callable\n\nThe following commands are available:\n")
  324. helpers := vm.DefinedHelpers()
  325. sort.SliceStable(helpers, func(i, j int) bool {
  326. return helpers[i].HelperName() < helpers[j].HelperName()
  327. })
  328. for _, helper := range helpers {
  329. fl := strings.SplitN(helper.Help(),"\n", 2)
  330. fmt.Printf("%s %s: \n", helper.HelperName(), fl[0])
  331. }
  332. return Ok()
  333. }
  334. targetName := val[0].String()
  335. target := vm.Lookup(targetName)
  336. if target == nil {
  337. fmt.Printf("help: %s not found.\n", targetName)
  338. }
  339. if helper, isHelper := target.(Helper) ; isHelper {
  340. help := helper.Help()
  341. fmt.Printf("%s: %s.\n", targetName, help)
  342. return Ok(StringValue(help))
  343. }
  344. return Ok()
  345. }
  346. func explain(vm *VM, val ...Value) [] Value {
  347. var target, help string
  348. _, err := ParseArgs(val, &target, &help)
  349. if err != nil {
  350. return Fail(err)
  351. }
  352. err = vm.SetHelp(target, help)
  353. if err != nil {
  354. return Fail(err)
  355. }
  356. return Ok(StringValue(help))
  357. }
  358. func exit(vm *VM, val ...Value) [] Value {
  359. var code int
  360. _, err := ParseArgs(val, &code)
  361. if err != nil {
  362. runtime.Goexit()
  363. }
  364. vm.ExitStatus = code
  365. runtime.Goexit()
  366. return Ok()
  367. }
  368. type Door struct {
  369. name string
  370. locked bool
  371. opened bool
  372. }
  373. // Implement callable ...
  374. func (door * Door) Position() *Position {
  375. return &Position{"builtin.go", 427, 8}
  376. }
  377. type CallableValue interface {
  378. Callable
  379. Value
  380. }
  381. func Redispatch(from CallableValue, vm *VM, args...Value) []Value {
  382. if len(args) < 1 {
  383. return EmptyValueArray()
  384. }
  385. var word WordValue
  386. _, err := ParseOptArgs(args, 1, &word)
  387. if err != nil {
  388. return Fail(err)
  389. }
  390. args[0] = from
  391. return vm.CallNamed(string(word), args...)
  392. }
  393. func (door * Door) Call(vm *VM, args...Value) []Value {
  394. return Redispatch(door, vm, args...)
  395. }
  396. var doorSignature = NewSignature(WordTypeValue)
  397. func (door * Door) Signature() Signature {
  398. return doorSignature
  399. }
  400. var _ Callable = &Door{}
  401. const DoorType = TypeValue("Door")
  402. func (door * Door) String() string {
  403. return fmt.Sprintf("Door: %s %v %v", door.name, door.locked, door.opened)
  404. }
  405. func (*Door) Type() TypeValue {
  406. return DoorType
  407. }
  408. func (from * Door) Convert(to interface{}) error {
  409. switch toPtr := to.(type) {
  410. case **Door:
  411. (*toPtr) = from
  412. case *Door:
  413. (*toPtr) = *from
  414. case *Value:
  415. (*toPtr) = from
  416. default:
  417. return NewErrorValuef("Cannot convert DoorValue value %v to %v", from, to)
  418. }
  419. return nil
  420. }
  421. func door(vm *VM, val ...Value) [] Value {
  422. var name string
  423. var locked bool
  424. _, err := ParseOptArgs(val, 1, &name, &locked)
  425. if err != nil {
  426. return Fail(err)
  427. }
  428. return Ok(&Door{name: name, locked: locked, opened:false})
  429. }
  430. func (door * Door) Open() {
  431. door.opened = true
  432. }
  433. func openDoor(vm *VM, val ...Value) [] Value {
  434. var door *Door
  435. _, err := ParseArgs(val, &door)
  436. if err != nil {
  437. return Fail(err)
  438. }
  439. if door == nil {
  440. return Fail(NewErrorValuef("Door may not be nil."))
  441. }
  442. fmt.Printf("Door: %v %s", door, door)
  443. door.Open()
  444. return Ok(door)
  445. }
  446. func (vm *VM) RegisterBuiltins() {
  447. vm.RegisterBuiltinWithHelp("addi", addi, `[Int Int] -> Int: adds two integers together`)
  448. vm.RegisterBuiltinWithHelp("addf", addf, `[Int Int] -> Int: adds two floats together`)
  449. vm.RegisterBuiltinWithHelp("andb", andb, `[Bool Bool] -> Bool: returns true if all it's arguments are true`)
  450. vm.RegisterBuiltin("cover", cover)
  451. vm.RegisterBuiltin("fetchl", fetchl)
  452. vm.RegisterBuiltin("fetchm", fetchm)
  453. vm.RegisterBuiltin("sumi", sumi)
  454. vm.RegisterBuiltin("sumf", sumf)
  455. vm.RegisterBuiltin("subi", subi)
  456. vm.RegisterBuiltin("subf", subf)
  457. vm.RegisterBuiltin("divi", divi)
  458. vm.RegisterBuiltin("divf", divf)
  459. vm.RegisterBuiltin("map", newmap)
  460. vm.RegisterBuiltin("muli", muli)
  461. vm.RegisterBuiltin("mulf", mulf)
  462. vm.RegisterBuiltinWithHelp("orb", orb, `[Bool Bool] -> Bool: returns true if on of it's arguments is true`)
  463. // vm.RegisterCover("add")
  464. vm.RegisterBuiltin("p", p)
  465. vm.RegisterBuiltin("println", println)
  466. vm.RegisterBuiltin("printf", printf)
  467. vm.RegisterBuiltin("storel", storel)
  468. vm.RegisterBuiltin("storem", storem)
  469. vm.RegisterBuiltin("trace", trace)
  470. vm.RegisterBuiltin("to", to)
  471. vm.RegisterBuiltin("types", types)
  472. vm.RegisterBuiltin("return", builtin_return)
  473. vm.RegisterBuiltin("val", val)
  474. vm.RegisterBuiltin("set", set)
  475. vm.RegisterBuiltin("get", get)
  476. vm.RegisterBuiltin("help", help)
  477. vm.RegisterBuiltin("explain", explain)
  478. vm.RegisterBuiltin("exit", exit)
  479. vm.RegisterBuiltin("door", door)
  480. vm.RegisterBuiltin("openDoor", openDoor)
  481. vm.Register("Door", DoorType)
  482. vm.AddOverloads("open", Over("openDoor", 0, DoorType))
  483. vm.AddOverloads("mul",
  484. Over("mulf", 0, FloatTypeValue, FloatTypeValue),
  485. Over("muli", 0, IntTypeValue, IntTypeValue),
  486. Over("mulf", 0, FloatTypeValue, IntTypeValue),
  487. Over("mulf", 0, FloatTypeValue, IntTypeValue))
  488. vm.SetHelp("mul", " Num: Multiplies two numbers. Cover for muli and mulf.")
  489. vm.AddOverloads("fetch",
  490. Over("fetchl", 0, ListTypeValue, IntTypeValue),
  491. Over("fetchm", 0, MapTypeValue, AnyTypeValue),
  492. )
  493. vm.SetHelp("fetch", " storage, index. Fetch value in storage at given index.")
  494. /*
  495. vm.AddOverloads("store",
  496. Over("storel", ListTypeValue, IntTypeValue, AnyTypeValue),
  497. Over("storem", MapTypeValue, AnyTypeValue, AnyTypeValue),
  498. )
  499. vm.SetHelp("store", " storage, index, value. Store value in storage at given index.")
  500. */
  501. }