lint.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /*
  2. Simple linter, based on the Acorn [1] parser module
  3. All of the existing linters either cramp my style or have huge
  4. dependencies (Closure). So here's a very simple, non-invasive one
  5. that only spots
  6. - missing semicolons and trailing commas
  7. - variables or properties that are reserved words
  8. - assigning to a variable you didn't declare
  9. - access to non-whitelisted globals
  10. (use a '// declare global: foo, bar' comment to declare extra
  11. globals in a file)
  12. [1]: https://github.com/marijnh/acorn/
  13. */
  14. var topAllowedGlobals = Object.create(null);
  15. ("Error RegExp Number String Array Function Object Math Date undefined " +
  16. "parseInt parseFloat Infinity NaN isNaN " +
  17. "window document navigator prompt alert confirm console " +
  18. "screen FileReader Worker postMessage importScripts " +
  19. "setInterval clearInterval setTimeout clearTimeout " +
  20. "CodeMirror " +
  21. "test exports require module define")
  22. .split(" ").forEach(function(n) { topAllowedGlobals[n] = true; });
  23. var fs = require("fs"), acorn = require("./acorn.js"), walk = require("./walk.js");
  24. var scopePasser = walk.make({
  25. ScopeBody: function(node, prev, c) { c(node, node.scope); }
  26. });
  27. var cBlob = /^\/\/ CodeMirror, copyright \(c\) by Marijn Haverbeke and others\n\/\/ Distributed under an MIT license: http:\/\/codemirror.net\/LICENSE\n\n/;
  28. function checkFile(fileName) {
  29. var file = fs.readFileSync(fileName, "utf8"), notAllowed;
  30. if (notAllowed = file.match(/[\x00-\x08\x0b\x0c\x0e-\x19\uFEFF\t]|[ \t]\n/)) {
  31. var msg;
  32. if (notAllowed[0] == "\t") msg = "Found tab character";
  33. else if (notAllowed[0].indexOf("\n") > -1) msg = "Trailing whitespace";
  34. else msg = "Undesirable character " + notAllowed[0].charCodeAt(0);
  35. var info = acorn.getLineInfo(file, notAllowed.index);
  36. fail(msg + " at line " + info.line + ", column " + info.column, {source: fileName});
  37. }
  38. if (!cBlob.test(file))
  39. fail("Missing license blob", {source: fileName});
  40. var globalsSeen = Object.create(null);
  41. try {
  42. var parsed = acorn.parse(file, {
  43. locations: true,
  44. ecmaVersion: 3,
  45. strictSemicolons: true,
  46. allowTrailingCommas: false,
  47. forbidReserved: "everywhere",
  48. sourceFile: fileName
  49. });
  50. } catch (e) {
  51. fail(e.message, {source: fileName});
  52. return;
  53. }
  54. var scopes = [];
  55. walk.simple(parsed, {
  56. ScopeBody: function(node, scope) {
  57. node.scope = scope;
  58. scopes.push(scope);
  59. }
  60. }, walk.scopeVisitor, {vars: Object.create(null)});
  61. var ignoredGlobals = Object.create(null);
  62. function inScope(name, scope) {
  63. for (var cur = scope; cur; cur = cur.prev)
  64. if (name in cur.vars) return true;
  65. }
  66. function checkLHS(node, scope) {
  67. if (node.type == "Identifier" && !(node.name in ignoredGlobals) &&
  68. !inScope(node.name, scope)) {
  69. ignoredGlobals[node.name] = true;
  70. fail("Assignment to global variable", node.loc);
  71. }
  72. }
  73. walk.simple(parsed, {
  74. UpdateExpression: function(node, scope) {checkLHS(node.argument, scope);},
  75. AssignmentExpression: function(node, scope) {checkLHS(node.left, scope);},
  76. Identifier: function(node, scope) {
  77. if (node.name == "arguments") return;
  78. // Mark used identifiers
  79. for (var cur = scope; cur; cur = cur.prev)
  80. if (node.name in cur.vars) {
  81. cur.vars[node.name].used = true;
  82. return;
  83. }
  84. globalsSeen[node.name] = node.loc;
  85. },
  86. FunctionExpression: function(node) {
  87. if (node.id) fail("Named function expression", node.loc);
  88. },
  89. ForStatement: function(node) {
  90. checkReusedIndex(node);
  91. },
  92. MemberExpression: function(node) {
  93. if (node.object.type == "Identifier" && node.object.name == "console" && !node.computed)
  94. fail("Found console." + node.property.name, node.loc);
  95. },
  96. DebuggerStatement: function(node) {
  97. fail("Found debugger statement", node.loc);
  98. }
  99. }, scopePasser);
  100. function checkReusedIndex(node) {
  101. if (!node.init || node.init.type != "VariableDeclaration") return;
  102. var name = node.init.declarations[0].id.name;
  103. walk.recursive(node.body, null, {
  104. Function: function() {},
  105. VariableDeclaration: function(node, st, c) {
  106. for (var i = 0; i < node.declarations.length; i++)
  107. if (node.declarations[i].id.name == name)
  108. fail("redefined loop variable", node.declarations[i].id.loc);
  109. walk.base.VariableDeclaration(node, st, c);
  110. }
  111. });
  112. }
  113. var allowedGlobals = Object.create(topAllowedGlobals), m;
  114. if (m = file.match(/\/\/ declare global:\s+(.*)/))
  115. m[1].split(/,\s*/g).forEach(function(n) { allowedGlobals[n] = true; });
  116. for (var glob in globalsSeen)
  117. if (!(glob in allowedGlobals))
  118. fail("Access to global variable " + glob + ". Add a '// declare global: " + glob +
  119. "' comment or add this variable in test/lint/lint.js.", globalsSeen[glob]);
  120. for (var i = 0; i < scopes.length; ++i) {
  121. var scope = scopes[i];
  122. for (var name in scope.vars) {
  123. var info = scope.vars[name];
  124. if (!info.used && info.type != "catch clause" && info.type != "function name" && name.charAt(0) != "_")
  125. fail("Unused " + info.type + " " + name, info.node.loc);
  126. }
  127. }
  128. }
  129. var failed = false;
  130. function fail(msg, pos) {
  131. if (pos.start) msg += " (" + pos.start.line + ":" + pos.start.column + ")";
  132. console.log(pos.source + ": " + msg);
  133. failed = true;
  134. }
  135. function checkDir(dir) {
  136. fs.readdirSync(dir).forEach(function(file) {
  137. var fname = dir + "/" + file;
  138. if (/\.js$/.test(file)) checkFile(fname);
  139. else if (fs.lstatSync(fname).isDirectory()) checkDir(fname);
  140. });
  141. }
  142. exports.checkDir = checkDir;
  143. exports.checkFile = checkFile;
  144. exports.success = function() { return !failed; };