Checking if code is valid JavaScript without actually evaluating it - javascript

Is there a function to test if a snippet is valid JavaScript without actually evaluating it? That is, the equivalent of
function validate(code){
try { eval(code); }
catch(err) { return false; }
return true;
};
without side effects.

Yes, there is.
new Function(code);
throws a SyntaxError if code isn't valid Javascript. (ECMA-262, edition 5.1, ยง15.3.2.1 guarantees that it will throw an exception if code isn't parsable).
Notice: this snippet only checks syntax validity. Code can still throw exceptions because of undefined references, for example. It is a way harder to check it: you either should evaluate code (and get all its side effects) or parse code and emulate its execution (that is write a JS virtual machine in JS).

You could use esprima.
Esprima (esprima.org) is a high performance, standard-compliant ECMAScript parser written in ECMAScript (also popularly known as JavaScript).
Features
Full support for ECMAScript 5.1 (ECMA-262)
Sensible syntax tree format, compatible with Mozilla Parser AST
Heavily tested (> 550 unit tests with solid 100% statement coverage)
Optional tracking of syntax node location (index-based and line-column)
Experimental support for ES6/Harmony (module, class, destructuring, ...)
You can use the online syntax validator or install it as npm package and run it locally from the command line. There are two commands: esparse and esvalidate. esvalidate yields (given the example from the online syntax validator above):
$ esvalidate foo.js
foo.js:1: Illegal return statement
foo.js:7: Octal literals are not allowed in strict mode.
foo.js:10: Duplicate data property in object literal not allowed in strict mode
foo.js:10: Strict mode code may not include a with statement
For the sake of completeness esparse produces an AST.

Related

Is there a way to assign an ES5.1 class an anonym function?

I was trying to implement ANTLR4 for a project that i'm working on and I created a Python3 parser for JavaScript by using the ANTLR4 tool. The problem is that when I try to run the code, the following error is raised:
TypeError: Assignment to constant variable.
TypeError: Assignment to constant variable.
The piece of code is the following:
Assignment
let old_lexer = Python3Lexer;
Python3Lexer = function () {
old_lexer.apply(this, arguments);
this.reset.call(this);
}
Python3Lexer is a class.
I am using ANTLR 4.9.2 and ECMAScript 5.1 (but I don't really know if this one is running, maybe it is the default version).
I don't really understand what does that assignment mean and also I don't really know if it can be written on some other way.
Thanks in advance.
Using ANTLR 4.9.x, the JavaScript target generates EcmaScript 6 source code and must be transpiled to EcmaScript 5 (Documentation for the JavaScript target recommends using WebPack and has instructions for using it.) The JavaScript runtime has a webpack.config.js to help out. This is necessary for output that will run under an EcmaScript 5.x runtime. (class, let, etc. are all ES6 specific).

Using regexp namespace from EXSLT in browser console causes a SyntaxError

I want to use regexp namespace in my XPath expressions when searching elements in browser console, but get SyntaxError: The expression is not a legal expression. trying to do so.
I followed http://help.dottoro.com/ljspsvcs.php as a tutorial for creating a namespace resolver.
Here's my code:
function nsResolver (nsPrefix) {
if (nsPrefix == "regexp") {
return "http://exslt.org/regular-expressions";
}
return null;
}
document.evaluate('//a[regexp:test(#href, "qwerty-[\d]+$")]', document.documentElement, nsResolver, XPathResult.ANY_TYPE, null);
What am I doing wrong here?
The fact that someone has defined a set of extension functions in a particular namespace does not mean that every XSLT processor supports those functions. What is wrong here is that you are using an ancient XSLT processor that has not been upgraded in years (because the browser vendors lost interest in the XML user community).
Consider installing Saxon-JS, which provides XSLT 3.0 running in the browser, with built-in regular expression support according to W3C specifications. (Disclaimer: it's my company's product).

Using String.raw() with Node JS

I'm working on a Node.js app with and I would like to use String.raw() which is part of the ES 6 standard.
However, when using it as in the documentation:
text = String.raw`Hi\n${2+3}!` + text.slice(2);
It returns SyntaxError: Unexpected token ILLEGAL for the character after String.raw.
I think that there is a problem because String.raw() is a new technology only available for Chrome and Firefox yet. However, can I use it in Node.js and how?
The grave character after raw denotes template strings, which is a feature in ES6 Harmony. You can invoke node with --harmony flag, but this feature is not yet implemented. This is the reason of the syntax error. Raw strings are unsupported too.
If you want experimenting with this feature in server side, check out io.js, which is a fork of node, but with many ES6 features implemented and enabled by default.

Why does antlr4 choke on LT!*

I'm trying to use a JavaScript grammar with antlr4 (copyright 2008 by Chris Lambrou, retrieved from http://www.antlr3.org/grammar/1206736738015/JavaScript.g). The script contains many instances of "LT!*", which I understand as a regex expression meaning zero or more line terminators and don't include the tokens in the generated AST (from answer to stackoverflow question ANTLR 3, what does LT!* mean?).
antlr4 throws a syntax error for each instance of "LT!*" so I assume the most recent version doesn't handle that construct. What can be used to replace "LT!*" that will work in antlr4?
[edit] Note that the syntax error is on the "!"
ANTLR 4 does not produce AST. Therefore, the ! (and ->) inside parser rules is not allowed.
See: How can I build an AST using ANTLR4?

static/compile time check for javascript with jquery?

I know javascript (or at least a version of it) can be compiled into .NET provided certain conditions are met. How can i do a compile time or static syntax check on javascript i am writing? The catch is, it must support jquery
Cause someone will ask, to compile (with ms .net) is
C:\Windows\Microsoft.NET\Framework\v2.0.50727\jsc thefile.js
writing package thenamespace { class ClassName{ around where necessary. Then you can add this as a normal reference. From experience the references are not always compatible with mono.
I'm not sure if there are any static analyzers which can check the validity of jQuery code in depth, but for the Javascript syntax itself, there are non-web versions of Javascript Lint and JSLint you could use.
If you're using Visual Studio, you could also give JSLint.VS a try for better integration.
UPDATE: Since I wrote this, JSHint and ESLint have taken over as the most popular members of the JSLint family.
Also, TypeScript is gaining popularity. It's a superset of JavaScript with optional static types which compiles to plain JavaScript. (For those who have used MyPy for Python, it's similar. Valid JavaScript is also valid TypeScript, but you can incrementally add type annotations and the compiler will use them to catch bugs.)

Categories