Skip to content

Commit

Permalink
Fix issue where the strict mode was not detected when a comment was b…
Browse files Browse the repository at this point in the history
…efore "strict mode";

Fixes #54
  • Loading branch information
jhnns committed Apr 27, 2015
1 parent 7cd73d4 commit bbbd05c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
20 changes: 18 additions & 2 deletions lib/detectStrictMode.js
@@ -1,3 +1,7 @@
var multiLineComment = /^\s*\/\*.*?\*\//;
var singleLineComment = /^\s*\/\/.*?[\r\n]/;
var strictMode = /^\s*(?:"use strict"|'use strict')[ \t]*(?:[\r\n]|;)/;

/**
* Returns true if the source code is intended to run in strict mode. Does not detect
* "use strict" if it occurs in a nested function.
Expand All @@ -6,7 +10,19 @@
* @return {Boolean}
*/
function detectStrictMode(src) {
return (/^\s*(?:"use strict"|'use strict')[ \t]*(?:[\r\n]|;)/g).test(src);
var singleLine;
var multiLine;

while ((singleLine = singleLineComment.test(src)) || (multiLine = multiLineComment.test(src))) {
if (singleLine) {
src = src.replace(singleLineComment, "");
}
if (multiLine) {
src = src.replace(multiLineComment, "");
}
}

return strictMode.test(src);
}

module.exports = detectStrictMode;
module.exports = detectStrictMode;
12 changes: 11 additions & 1 deletion test/detectStrictMode.test.js
Expand Up @@ -2,6 +2,7 @@ var expect = require("expect.js"),
detectStrictMode = require("../lib/detectStrictMode.js");

describe("detectStrictMode", function () {

it("should detect all valid uses of \"use strict\";", function () {
expect(detectStrictMode('"use strict";')).to.be(true);
expect(detectStrictMode("'use strict';")).to.be(true);
Expand All @@ -11,13 +12,22 @@ describe("detectStrictMode", function () {
expect(detectStrictMode('"use strict"\r\n')).to.be(true);
expect(detectStrictMode('"use strict" ; test();')).to.be(true);
});

it("should be allowed to place comments before \"use strict\";", function () {
expect(detectStrictMode('// some comment\n"use strict";')).to.be(true);
expect(detectStrictMode('/* yo! */"use strict"; /* another comment */')).to.be(true);
expect(detectStrictMode(' // yes yo\r\n\r\n\r\n /*oh yoh*/\r\n//oh snap!\r /* yoh! */"use strict";')).to.be(true);
});

it("should not detect invalid uses of \"use strict\";", function () {
expect(detectStrictMode('" use strict ";')).to.be(false);
expect(detectStrictMode('"use strict".replace("use", "fail");')).to.be(false);
expect(detectStrictMode('"use strict" .replace("use", "fail");')).to.be(false);
expect(detectStrictMode(';"use strict";')).to.be(false);
});

it("should not detect \"use strict\"; if it occurs in some nested function", function () {
expect(detectStrictMode('function () {"use strict";}')).to.be(false);
});
});

});

0 comments on commit bbbd05c

Please sign in to comment.