2 Simple linter, based on the Acorn [1] parser module
4 All of the existing linters either cramp my style or have huge
5 dependencies (Closure). So here's a very simple, non-invasive one
8 - missing semicolons and trailing commas
9 - variables or properties that are reserved words
10 - assigning to a variable you didn't declare
12 [1]: https://github.com/marijnh/acorn/
15 var fs = require("fs"), acorn = require("./acorn.js"), walk = require("./walk.js");
17 var scopePasser = walk.make({
18 ScopeBody: function(node, prev, c) { c(node, node.scope); }
21 function checkFile(fileName) {
22 var file = fs.readFileSync(fileName, "utf8"), notAllowed;
23 if (notAllowed = file.match(/[\x00-\x08\x0b\x0c\x0e-\x19\uFEFF\t]|[ \t]\n/)) {
25 if (notAllowed[0] == "\t") msg = "Found tab character";
26 else if (notAllowed[0].indexOf("\n") > -1) msg = "Trailing whitespace";
27 else msg = "Undesirable character " + notAllowed[0].charCodeAt(0);
28 var info = acorn.getLineInfo(file, notAllowed.index);
29 fail(msg + " at line " + info.line + ", column " + info.column, {source: fileName});
33 var parsed = acorn.parse(file, {
36 strictSemicolons: true,
37 allowTrailingCommas: false,
42 fail(e.message, {source: fileName});
49 ScopeBody: function(node, scope) {
53 }, walk.scopeVisitor, {vars: Object.create(null)});
55 var ignoredGlobals = Object.create(null);
57 function inScope(name, scope) {
58 for (var cur = scope; cur; cur = cur.prev)
59 if (name in cur.vars) return true;
61 function checkLHS(node, scope) {
62 if (node.type == "Identifier" && !(node.name in ignoredGlobals) &&
63 !inScope(node.name, scope)) {
64 ignoredGlobals[node.name] = true;
65 fail("Assignment to global variable", node.loc);
70 UpdateExpression: function(node, scope) {checkLHS(node.argument, scope);},
71 AssignmentExpression: function(node, scope) {checkLHS(node.left, scope);},
72 Identifier: function(node, scope) {
73 // Mark used identifiers
74 for (var cur = scope; cur; cur = cur.prev)
75 if (node.name in cur.vars) {
76 cur.vars[node.name].used = true;
80 FunctionExpression: function(node) {
81 if (node.id) fail("Named function expression", node.loc);
85 for (var i = 0; i < scopes.length; ++i) {
86 var scope = scopes[i];
87 for (var name in scope.vars) {
88 var info = scope.vars[name];
89 if (!info.used && info.type != "catch clause" && info.type != "function name" && name.charAt(0) != "_")
90 fail("Unused " + info.type + " " + name, info.node.loc);
96 function fail(msg, pos) {
97 if (pos.start) msg += " (" + pos.start.line + ":" + pos.start.column + ")";
98 console.log(pos.source + ": " + msg);
102 function checkDir(dir) {
103 fs.readdirSync(dir).forEach(function(file) {
104 var fname = dir + "/" + file;
105 if (/\.js$/.test(file)) checkFile(fname);
106 else if (file != "dep" && fs.lstatSync(fname).isDirectory()) checkDir(fname);
110 exports.checkDir = checkDir;
111 exports.checkFile = checkFile;
112 exports.success = function() { return !failed; };