问题
With Crockford's JSLINT, after calling JSLINT()
to parse some JavaScript source, it provides access to the parse tree via JSLINT.tree
It would be really powerful to be able to analyse the tree, make structural changes to it based on the analysis and then generate new JavaScript from the modified tree.
Is there an open source project that builds on JSLINT by providing a conversion from a parse tree back to JavaScript?
(Is this even possible, i.e. does JSLINT keep complete enough information from the parse to round-trip everything significant?)
回答1:
I dont know if JSLint can do it (looking at some of the forum postings, it doesnt look like maintaining the tree is their goal but its a by-product for doing the linting process).
The uglifyjs project may help with generating an AST from javascript and re-converting a AST to code. See this method for AST to javascript.
回答2:
Not open source, but does exactly what OP requests: our JavaScript Front End.
This front end is based on our DMS Software Reengineering Toolkit, which is general purpose customizable compiler technology useful for building arbitrary code analyzers and transformers. DMS has many front ends available for many languages (COBOL, Java, C++, ...)
In particular, DMS-based parsers (including its JavaScript one), collect complete information for regenerating the source tree, including column-start and end information for tokens, radix of numeric literals, differences in string quoting conventions, etc. to enable it to do fidelity printing where no transformations have been applied. DMS also provides many other useful services for tree processing such as visitors, symbol table construction support, flow analysis support, pattern matching, as well as source-to-source transformations.
It can provide all these services because the cost of engineering it has been amortized across many, many languages and applications.
We did it because as Daniel said, "the possibilities are limitless". He gives an example of instrumenting the code to watch for runtime failures; this kind of instrumentation is a very useful idea and we build test coverage tools based on exactly this thought.
来源:https://stackoverflow.com/questions/9139768/generating-javascript-from-a-jslint-parse-tree