Join the DZone community and get the full member experience.Join For Free
Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.
With both strategies, the original source needs to be parsed first. This can be easily carried out using a parser. After that, what happens to the produced syntax tree depends on the chosen approach, as summarized by the following diagram.
In the case of non-destructive modification, we use the location information of the syntax nodes and/or tokens to find out what needs to be tweaked. An obvious example is when we want to change string literal quotes, from single quotes to double quotes (or the other way around). By locating every string literal, we know where the quotes are and thus we can just perform in-place replacement for the quotes (note that additional escaping might be necessary, since this is about strings).
Simple syntax transpilation is also another typical use case. For example, if we want to use ECMASCript 6 block scope feature today, we need to transform the code (e.g. using defs.js) to run in an ECMAScript 5 environment. This is about converting
var (taken into account the proper scoping of course).
The advantage of non-destructive transformation is that we do not lose many important parts of the original source which do not affect the syntax and execution. For example, converting double quotes to single quotes means that the existing indentation, comments, etc are not touched at all. The modification tool only changes stuff it is interested in, it should ignore everything else.
If we are building a tool which does not care about the original source, the obviously it is easier to just regenerate the source from the syntax tree. For example, a minifier reproduces a new source which is semantically equivalent to the syntax tree, but without the extra white spaces. In many cases, the minifier may also shorten variables names, remove unused code, and many other tweaks to the syntax nodes. This way, the code becomes shorter (in term of bytes) but it does not affect its execution. Such a minifier will not care about the original indentation and comments.
Of course, nothing stops us from composing two or more tools using these two different techniques!
Published at DZone with permission of Ariya Hidayat , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.