Browse files

Rewrite `try` special form as a macro.

- Add try, catch, finally macros.
- Implement clojrue like try / catch / finally API.
  • Loading branch information...
1 parent abd8ba5 commit 5920a7155ca4f43109c17a42639184948e0f2d28 @Gozala committed Jul 31, 2012
Showing with 20 additions and 10 deletions.
  1. +0 −10 lib/ls.js
  2. +20 −0 src/macros.ls
View
10 lib/ls.js
@@ -25,7 +25,6 @@ var _LS = {},
keywords = {},
macros = {},
templates = {};
-templates["try"] = _.template("(function () {\n<%= indent %><%= indent %>try {\n<%= indent %><%= trypart %>\n<%= indent %><%= indent %>} catch (e) {\n<%= indent %><%= indent %><%= indent %>return (<%= catchpart %>)(e);\n<%= indent %><%= indent %>}\n<%= indent %>})()");
templates["str"] = _.template("[<%= elems %>].join('')");
templates[".invoke"] = _.template("(<%= target %>).<%= method %>");
templates[".field"] = _.template("(<%= target %>).<%= field %>");
@@ -306,15 +305,6 @@ keywords["js*"] = function(form) {
return result.substr(1, result.length - 2);
};
-keywords["try"] = function(arr) {
- if (arr.length < 3) throw handleError(0, arr._line, arr._filename);
- var c = arr.pop();
- return templates["try"]({
- trypart: handleExpressions(arr.slice(1)),
- catchpart: _.isArray(c) ? handleExpression(c) : c,
- indent: " ".repeat(indent)});
-};
-
keywords["symbol"] = function(arr) {
if (arr.length < 2) throw handleError(0, arr._line, arr._filename);
return arr[1].substr(1, arr[1].length - 2)
View
20 src/macros.ls
@@ -76,6 +76,26 @@
"The expression is evaluated and thrown."
[expression]
`((function [] (js* "throw ~{}" ~expression))))
+
+(defmacro try
+ ([expression]
+ `(try ~expression (catch 'ignore (void))))
+ ([expression catch-clause]
+ `((fn-scope
+ (js* "try {\n ~{}\n} ~{}" (expressions ~expression) ~catch-clause))))
+ ([expression catch-clause finally-clause]
+ `((fn-scope
+ (js* "try {\n ~{}\n} ~{} ~{}"
+ (expressions ~expression) ~catch-clause ~finally-clause)))))
+
+(defmacro catch
+ ([type error & body]
+ `(js* "catch (~{}) {\n ~{}\n}"
+ ~error (expressions ~@body))))
+
+(defmacro finally [& body]
+ `(js* "finally {\n ~{}\n}" (statements ~@body)))
+
(defmacro dispatch
([body] `(js* "/~{}/" (symbol ~body))))

0 comments on commit 5920a71

Please sign in to comment.