Macros

Preprocessing code through macros is not a new idea. It was, and probably still is, very popular for C and C++. In fact, if you take a look at some of the source code for the Gnu utilities for Linux they are written almost entirely in macros. Macros are notorious for being hard to understand and debug. For a time, newly-created languages like Java and C# did not support macros for exactly this reason.

That being said, even more recent languages like Rust and Julia have brought the idea of macros back. These languages were influenced by the macros from the Scheme language, a dialect of Lisp. The difference between C macros and Lisp/Scheme macros is that the C versions are textual while the Lisp/Scheme ones are structural. This means that C macros are just glorified find/replace tools while Scheme macros are aware of the abstract syntax tree (AST) around them, allowing them to be much more powerful.

The AST for Scheme is a far simpler construct than that of JavaScript. Nonetheless, there is a very interesting project called Sweet.js that tries to create structural macros for JavaScript.

Sweet.js plugs into the JavaScript build pipeline and modified JavaScript source code using one or more macros. There are a number of fully-fledged JavaScript transpilers, that is compilers that emit JavaScript. These compilers are problematic for sharing code between multiple projects. Their code is so different that there is no real way to share it. Sweet.js supports multiple macros being expanded in a single step. This allows for much better code sharing. The reusable bits are a smaller size and more easy to run together.

A simple example of Sweet.js is as follows:

let var = macro {
  rule { [$var (,) ...] = $obj:expr } => {
    var i = 0;
    var arr = $obj;
    $(var $var = arr[i++]) (;) ...
  }

  rule { $id } => {
    var $id
  }
}

The macro here provides ECMAScript-2015-style deconstructors that split an array into tree fields. The macro matches an array assignment and also regular assignment. For regular assignment the macro simply returns the identity, while for assignment of an array it will explode the text and replace it.

For instance, if you run it over the following:

var [foo, bar, baz] = arr;

Then, the result will be the following:

var i = 0;
var arr$2 = arr;
var foo = arr$2[i++];
var bar = arr$2[i++];
var baz = arr$2[i++];

This is just one example macro. The power of macros is really quite spectacular. Macros can create an entirely new language or change very minor things. They can be easily plugged in to fit any sided requirement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset