Fix #10758 Add compiler option to parse in strict mode

* add unit test to ensure "use strict" is not added twice
 * fix code
This commit is contained in:
Slawomir Sadziak 2016-10-10 12:15:34 +02:00
parent 29a85e02ab
commit ea808f52fe
6 changed files with 66 additions and 8 deletions

View file

@ -2235,6 +2235,36 @@ namespace ts {
return statementOffset;
}
/**
* Ensures "use strict" directive is added
*
* @param node source file
*/
export function ensureUseStrict(node: SourceFile): SourceFile {
let foundUseStrict = false;
let statementOffset = 0;
const numStatements = node.statements.length;
while (statementOffset < numStatements) {
const statement = node.statements[statementOffset];
if (isPrologueDirective(statement)) {
if (isUseStrictPrologue(statement as ExpressionStatement)) {
foundUseStrict = true;
}
}
else {
break;
}
statementOffset++;
}
if (!foundUseStrict) {
const statements: Statement[] = [];
statements.push(startOnNewLine(createStatement(createLiteral("use strict"))));
// add "use strict" as the first statement
return updateSourceFileNode(node, statements.concat(node.statements));
}
return node;
}
/**
* Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
* order of operations.

View file

@ -438,7 +438,7 @@ namespace ts {
// ensure "use strict"" is emitted in all scenarios in alwaysStrict mode
if (compilerOptions.alwaysStrict) {
node = emitUseStrict(node);
node = ensureUseStrict(node);
}
// If the source file requires any helpers and is an external module, and
@ -477,13 +477,6 @@ namespace ts {
return node;
}
function emitUseStrict(node: SourceFile): SourceFile {
const statements: Statement[] = [];
statements.push(startOnNewLine(createStatement(createLiteral("use strict"))));
// add "use strict" as the first statement
return updateSourceFileNode(node, statements.concat(node.statements));
}
/**
* Tests whether we should emit a __decorate call for a class declaration.
*/

View file

@ -0,0 +1,11 @@
//// [alwaysStrictAlreadyUseStrict.ts]
"use strict"
function f() {
var a = [];
}
//// [alwaysStrictAlreadyUseStrict.js]
"use strict";
function f() {
var a = [];
}

View file

@ -0,0 +1,8 @@
=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts ===
"use strict"
function f() {
>f : Symbol(f, Decl(alwaysStrictAlreadyUseStrict.ts, 0, 12))
var a = [];
>a : Symbol(a, Decl(alwaysStrictAlreadyUseStrict.ts, 2, 7))
}

View file

@ -0,0 +1,11 @@
=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts ===
"use strict"
>"use strict" : "use strict"
function f() {
>f : () => void
var a = [];
>a : any[]
>[] : undefined[]
}

View file

@ -0,0 +1,5 @@
// @alwaysStrict: true
"use strict"
function f() {
var a = [];
}