Macros in JavaScript
fitzgeraldnick.com
fitzgeraldnick.com
Example usage (taken from the mailing list):
1. standard with-foo macro
(with-elements-by-ids (mydiv (other "otherdiv")) (setf mydiv.inner-h-t-m-l other.inner-h-t-m-l))
2. multiple-value return in javascript
(defun divmod (a b) (return (values (/ a b) (% a b))))
(receive (div mod) (divmod 10 3) (debug (+ "div: " div ", mod: " mod)))
Since JS has true closures and a flexible object model (someone wrote a CLOS-y layer for it recently) there is no need to take the JSR way and try and push for a community-accepted broken macro system. Besides, as someone (Jason Dominus?) posted to the perl list, lisp macro's are regular and do not break, unlike every other proposal that uses infix syntax.
I'm sure Douglas Crockford would agree with you and say that JavaScript already has too many nasty and broken features (ie the DOM and "with") but I was just having some fun on my day off from work.
As others have pointed out, the expander can't even survive expansion, and using regexes for code parsing is a poor choice. Maybe, I haven't emphasized it enough, but I was just having some fun and imagining what it would be like to code with real macros in JS. I'm not advocating anyone actually use this code in any of their projects, nor that ECMAscript include simple template style macros in the spec.
That said, I wouldn't mind if someone built real lispy macros into a JavaScript implementation by forking Rhino or Spider Monkey. I'm convinced that this is possible despite the verbose syntax. Check this out: http://javascript.crockford.com/tdop/tdop.html
I would love the hear ideas about how to support user-defined macros.
I notice that the submitted article uses simple string-substitution macros (like the C preprocessor). I think that is too limited and have too many pitfalls. I would prefer lisp-style macros (macros operating on the syntax tree), although I realize it is more complex in a language like JavaScript with a larger grammar.
The most powerful approach would be to allow the user to extend the language grammar however they like. But that is also complicated for the user, because you has to know the grammar of the language pretty well to avoid introducing ambiguities.
A more limited approach would be to allow macro-invocation with a predefined syntax, e.g. macroname ( arguments ) { statements } - the macro could then define transformations for the arguments and statements. This could support much of what you could want without having to mess with the actual language grammar. It would not be able to support the -> and ~> ideas in the post though, so perhaps this is to limited.
"Simple and robust browser side template processing for Ajax based web applications"
While this isn't a macro processor, it actually solves a related problem of management and separation between data (javascript, json) and presentation (html)
Here are the slides: http://google-jstemplate.googlecode.com/svn/slides/jstemplat...