meta-declarations.lisp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. (import test ())
  2. (import tests/compiler/codegen/codegen-helpers ())
  3. (import tests/compiler/compiler-helpers ())
  4. (import urn/backend/lua/emit lua)
  5. (import urn/backend/writer writer)
  6. (defun affirm-native (meta expected-src)
  7. (with (out (writer/create))
  8. (lua/compile-native out nil meta)
  9. (with (res (string/trim (string/gsub (writer/->string out) "\t" " ")))
  10. (when (/= res expected-src)
  11. (with (out '())
  12. (push! out (.. "Unexpected result compiling " (pretty meta)))
  13. (diff-lines (string/split expected-src "\n") (string/split res "\n") out)
  14. (fail! (concat out "\n")))))))
  15. (describe "The codegen"
  16. (section "will compile operators"
  17. (it "which are left associative"
  18. (affirm-codegen
  19. '((+ 2 3 4))
  20. "return 2 + 3 + 4")
  21. (affirm-codegen
  22. '((+ 2 3 (- 4 5)))
  23. "return 2 + 3 + (4 - 5)"))
  24. (it "which are right associative"
  25. (affirm-codegen
  26. '((.. "x" "y" "z"))
  27. "return \"x\" .. \"y\" .. \"z\"")
  28. (affirm-codegen
  29. '((.. "x" "y" (.. "a" "b")))
  30. "return \"x\" .. \"y\" .. (\"a\" .. \"b\")"))
  31. (it "which are not associative"
  32. (affirm-codegen
  33. '((get-idx foo "x"))
  34. "return foo[\"x\"]")
  35. (affirm-codegen
  36. '((get-idx (get-idx foo "x") "y"))
  37. "return foo[\"x\"][\"y\"]"))
  38. (section "which are variadic"
  39. (it "and have insufficient arguments"
  40. (affirm-codegen
  41. '((+ 2))
  42. "return _2b_(2)"))
  43. (pending "and have variadic returns"
  44. (affirm-codegen
  45. '((+ 2 (foo)))
  46. "return _2b_(2, foo)")))
  47. (it "which have the incorrect number of arguments"
  48. (affirm-codegen
  49. '((get-idx 1))
  50. "return getIdx(1)")
  51. (affirm-codegen
  52. '((get-idx 1 2 3))
  53. "return getIdx(1, 2, 3)")))
  54. (section "will compile operator functions"
  55. (it "which are left associative"
  56. (affirm-native
  57. (native-expr { :contents '(1 " + " 2) :count 2 :fold "left" })
  58. "function(x, ...) local t = x + ... for i = 2, _select('#', ...) do t = t + _select(i, ...) end return t end"))
  59. (it "which are right associative"
  60. (affirm-native
  61. (native-expr { :contents '(1 " .. " 2) :count 2 :fold "right" })
  62. "function(x, ...) local n = _select('#', ...) local t = _select(n, ...) for i = n - 1, 1, -1 do t = _select(i, ...) .. t end return x .. t end"))
  63. (it "which are not associative"
  64. (affirm-native
  65. (native-expr { :contents '(1 "[" 2 "]") :count 2 })
  66. "function(v1, v2) return v1[v2] end")))
  67. (it "will compile native variables"
  68. (affirm-native
  69. (native-var "foo")
  70. "foo")))