builtin.go 11 KB

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