Merge branch 'master' into autohoist-default

This commit is contained in:
Wesley Wigham
2015-11-25 17:52:51 -08:00
1568 changed files with 21024 additions and 16354 deletions
+92 -49
View File
@@ -533,7 +533,7 @@ namespace ts {
}
// Because of module/namespace merging, a module's exports are in scope,
// yet we never want to treat an export specifier as putting a member in scope.
// yet we never want to treat an export specifier as putting a member in scope.
// Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
// Two things to note about this:
// 1. We have to check this without calling getSymbol. The problem with calling getSymbol
@@ -1032,16 +1032,12 @@ namespace ts {
// Module names are escaped in our symbol table. However, string literal values aren't.
// Escape the name in the "require(...)" clause to ensure we find the right symbol.
let moduleName = escapeIdentifier(moduleReferenceLiteral.text);
const moduleName = escapeIdentifier(moduleReferenceLiteral.text);
if (moduleName === undefined) {
return;
}
if (moduleName.indexOf("!") >= 0) {
moduleName = moduleName.substr(0, moduleName.indexOf("!"));
}
const isRelative = isExternalModuleNameRelative(moduleName);
if (!isRelative) {
const symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule);
@@ -3205,7 +3201,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.StringLiteral:
case SyntaxKind.StringLiteralType:
return true;
case SyntaxKind.ArrayType:
return isIndependentType((<ArrayTypeNode>node).elementType);
@@ -3866,7 +3862,7 @@ namespace ts {
paramSymbol = resolvedSymbol;
}
parameters.push(paramSymbol);
if (param.type && param.type.kind === SyntaxKind.StringLiteral) {
if (param.type && param.type.kind === SyntaxKind.StringLiteralType) {
hasStringLiterals = true;
}
@@ -4535,8 +4531,7 @@ namespace ts {
return links.resolvedType;
}
function getStringLiteralType(node: StringLiteral): StringLiteralType {
const text = node.text;
function getStringLiteralTypeForText(text: string): StringLiteralType {
if (hasProperty(stringLiteralTypes, text)) {
return stringLiteralTypes[text];
}
@@ -4546,10 +4541,10 @@ namespace ts {
return type;
}
function getTypeFromStringLiteral(node: StringLiteral): Type {
function getTypeFromStringLiteralTypeNode(node: StringLiteralTypeNode): Type {
const links = getNodeLinks(node);
if (!links.resolvedType) {
links.resolvedType = getStringLiteralType(node);
links.resolvedType = getStringLiteralTypeForText(node.text);
}
return links.resolvedType;
}
@@ -4591,8 +4586,8 @@ namespace ts {
return voidType;
case SyntaxKind.ThisType:
return getTypeFromThisTypeNode(node);
case SyntaxKind.StringLiteral:
return getTypeFromStringLiteral(<StringLiteral>node);
case SyntaxKind.StringLiteralType:
return getTypeFromStringLiteralTypeNode(<StringLiteralTypeNode>node);
case SyntaxKind.TypeReference:
return getTypeFromTypeReference(<TypeReferenceNode>node);
case SyntaxKind.TypePredicate:
@@ -5232,9 +5227,12 @@ namespace ts {
const id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id;
const related = relation[id];
if (related !== undefined) {
// If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate
// errors, we can use the cached value. Otherwise, recompute the relation
if (!elaborateErrors || (related === RelationComparisonResult.FailedAndReported)) {
if (elaborateErrors && related === RelationComparisonResult.Failed) {
// We are elaborating errors and the cached result is an unreported failure. Record the result as a reported
// failure and continue computing the relation such that errors get reported.
relation[id] = RelationComparisonResult.FailedAndReported;
}
else {
return related === RelationComparisonResult.Succeeded ? Ternary.True : Ternary.False;
}
}
@@ -6090,6 +6088,17 @@ namespace ts {
}
function inferFromTypes(source: Type, target: Type) {
if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union ||
source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) {
// Source and target are both unions or both intersections. To improve the quality of
// inferences we first reduce the types by removing constituents that are identically
// matched by a constituent in the other type. For example, when inferring from
// 'string | string[]' to 'string | T', we reduce the types to 'string[]' and 'T'.
const reducedSource = reduceUnionOrIntersectionType(<UnionOrIntersectionType>source, <UnionOrIntersectionType>target);
const reducedTarget = reduceUnionOrIntersectionType(<UnionOrIntersectionType>target, <UnionOrIntersectionType>source);
source = reducedSource;
target = reducedTarget;
}
if (target.flags & TypeFlags.TypeParameter) {
// If target is a type parameter, make an inference, unless the source type contains
// the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
@@ -6100,7 +6109,6 @@ namespace ts {
if (source.flags & TypeFlags.ContainsAnyFunctionType) {
return;
}
const typeParameters = context.typeParameters;
for (let i = 0; i < typeParameters.length; i++) {
if (target === typeParameters[i]) {
@@ -6248,6 +6256,41 @@ namespace ts {
}
}
function typeIdenticalToSomeType(source: Type, target: UnionOrIntersectionType): boolean {
for (const t of target.types) {
if (isTypeIdenticalTo(source, t)) {
return true;
}
}
return false;
}
/**
* Return the reduced form of the source type. This type is computed by by removing all source
* constituents that have an identical match in the target type.
*/
function reduceUnionOrIntersectionType(source: UnionOrIntersectionType, target: UnionOrIntersectionType) {
let sourceTypes = source.types;
let sourceIndex = 0;
let modified = false;
while (sourceIndex < sourceTypes.length) {
if (typeIdenticalToSomeType(sourceTypes[sourceIndex], target)) {
if (!modified) {
sourceTypes = sourceTypes.slice(0);
modified = true;
}
sourceTypes.splice(sourceIndex, 1);
}
else {
sourceIndex++;
}
}
if (modified) {
return source.flags & TypeFlags.Union ? getUnionType(sourceTypes, /*noSubtypeReduction*/ true) : getIntersectionType(sourceTypes);
}
return source;
}
function getInferenceCandidates(context: InferenceContext, index: number): Type[] {
const inferences = context.inferences[index];
return inferences.primary || inferences.secondary || emptyArray;
@@ -8751,7 +8794,7 @@ namespace ts {
// for the argument. In that case, we should check the argument.
if (argType === undefined) {
argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors
? getStringLiteralType(<StringLiteral>arg)
? getStringLiteralTypeForText((<StringLiteral>arg).text)
: checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
}
@@ -8946,7 +8989,7 @@ namespace ts {
case SyntaxKind.Identifier:
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
return getStringLiteralType(<StringLiteral>element.name);
return getStringLiteralTypeForText((<Identifier | LiteralExpression>element.name).text);
case SyntaxKind.ComputedPropertyName:
const nameType = checkComputedPropertyName(<ComputedPropertyName>element.name);
@@ -9815,17 +9858,25 @@ namespace ts {
return aggregatedTypes;
}
// TypeScript Specification 1.0 (6.3) - July 2014
// An explicitly typed function whose return type isn't the Void or the Any type
// must have at least one return statement somewhere in its body.
// An exception to this rule is if the function implementation consists of a single 'throw' statement.
/*
*TypeScript Specification 1.0 (6.3) - July 2014
* An explicitly typed function whose return type isn't the Void or the Any type
* must have at least one return statement somewhere in its body.
* An exception to this rule is if the function implementation consists of a single 'throw' statement.
* @param returnType - return type of the function, can be undefined if return type is not explicitly specified
*/
function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration, returnType: Type): void {
if (!produceDiagnostics) {
return;
}
// Functions that return 'void' or 'any' don't need any return expressions.
if (returnType === voidType || isTypeAny(returnType)) {
// Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
if (returnType && (returnType === voidType || isTypeAny(returnType))) {
return;
}
// if return type is not specified then we'll do the check only if 'noImplicitReturns' option is set
if (!returnType && !compilerOptions.noImplicitReturns) {
return;
}
@@ -9835,13 +9886,14 @@ namespace ts {
return;
}
if (func.flags & NodeFlags.HasExplicitReturn) {
if (!returnType || func.flags & NodeFlags.HasExplicitReturn) {
if (compilerOptions.noImplicitReturns) {
error(func.type, Diagnostics.Not_all_code_paths_return_a_value);
error(func.type || func, Diagnostics.Not_all_code_paths_return_a_value);
}
}
else {
// This function does not conform to the specification.
// NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
error(func.type, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
}
}
@@ -9916,14 +9968,10 @@ namespace ts {
emitAwaiter = true;
}
const returnType = node.type && getTypeFromTypeNode(node.type);
let promisedType: Type;
if (returnType && isAsync) {
promisedType = checkAsyncFunctionReturnType(node);
}
if (returnType && !node.asteriskToken) {
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType);
const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type));
if (!node.asteriskToken) {
// return is not necessary in the body of generators
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
if (node.body) {
@@ -9946,13 +9994,13 @@ namespace ts {
// check assignability of the awaited type of the expression body against the promised type of
// its return type annotation.
const exprType = checkExpression(<Expression>node.body);
if (returnType) {
if (returnOrPromisedType) {
if (isAsync) {
const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member);
checkTypeAssignableTo(awaitedType, promisedType, node.body);
checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
else {
checkTypeAssignableTo(exprType, returnType, node.body);
checkTypeAssignableTo(exprType, returnOrPromisedType, node.body);
}
}
@@ -10568,7 +10616,7 @@ namespace ts {
function checkStringLiteralExpression(node: StringLiteral): Type {
const contextualType = getContextualType(node);
if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
return getStringLiteralType(node);
return getStringLiteralTypeForText(node.text);
}
return stringType;
@@ -11402,7 +11450,7 @@ namespace ts {
// we can get here in two cases
// 1. mixed static and instance class members
// 2. something with the same name was defined before the set of overloads that prevents them from merging
// here we'll report error only for the first case since for second we should already report error in binder
// here we'll report error only for the first case since for second we should already report error in binder
if (reportError) {
const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static;
error(errorNode, diagnostic);
@@ -12092,14 +12140,9 @@ namespace ts {
}
checkSourceElement(node.body);
if (node.type && !isAccessor(node.kind) && !node.asteriskToken) {
const returnType = getTypeFromTypeNode(node.type);
let promisedType: Type;
if (isAsync) {
promisedType = checkAsyncFunctionReturnType(node);
}
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType);
if (!isAccessor(node.kind) && !node.asteriskToken) {
const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type));
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
if (produceDiagnostics && !node.type) {
+16 -7
View File
@@ -357,7 +357,7 @@ namespace ts {
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.StringLiteral:
case SyntaxKind.StringLiteralType:
return writeTextOfNode(currentText, type);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>type);
@@ -658,7 +658,7 @@ namespace ts {
}
else {
write("require(");
writeTextOfNode(currentText, getExternalModuleImportEqualsDeclarationExpression(node));
emitExternalModuleSpecifier(node);
write(");");
}
writer.writeLine();
@@ -715,14 +715,23 @@ namespace ts {
}
write(" from ");
}
emitExternalModuleSpecifier(node.moduleSpecifier);
emitExternalModuleSpecifier(node);
write(";");
writer.writeLine();
}
function emitExternalModuleSpecifier(moduleSpecifier: Expression) {
if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit) {
const moduleName = getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent as (ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration));
function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration) {
let moduleSpecifier: Node;
if (parent.kind === SyntaxKind.ImportEqualsDeclaration) {
const node = parent as ImportEqualsDeclaration;
moduleSpecifier = getExternalModuleImportEqualsDeclarationExpression(node);
}
else {
const node = parent as (ImportDeclaration | ExportDeclaration);
moduleSpecifier = node.moduleSpecifier;
}
if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) {
const moduleName = getExternalModuleNameFromDeclaration(host, resolver, parent);
if (moduleName) {
write("\"");
write(moduleName);
@@ -765,7 +774,7 @@ namespace ts {
}
if (node.moduleSpecifier) {
write(" from ");
emitExternalModuleSpecifier(node.moduleSpecifier);
emitExternalModuleSpecifier(node);
}
write(";");
writer.writeLine();
+9 -1
View File
@@ -1622,7 +1622,7 @@
},
"Cannot assign an abstract constructor type to a non-abstract constructor type.": {
"category": "Error",
"code":2517
"code": 2517
},
"Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": {
"category": "Error",
@@ -2068,6 +2068,14 @@
"category": "Error",
"code": 5056
},
"Cannot find a tsconfig.json file at the specified directory: '{0}'": {
"category": "Error",
"code": 5057
},
"The specified path does not exist: '{0}'": {
"category": "Error",
"code": 5058
},
"Concatenate and emit output to single file.": {
"category": "Message",
+90 -35
View File
@@ -402,6 +402,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
*/
argumentsName?: string;
/*
* alias for 'this' from the calling code stack frame in case if this was used inside the converted loop
*/
thisName?: string;
/*
* list of non-block scoped variable declarations that appear inside converted loop
* such variable declarations should be moved outside the loop body
@@ -1271,7 +1276,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function isBinaryOrOctalIntegerLiteral(node: LiteralExpression, text: string): boolean {
function isBinaryOrOctalIntegerLiteral(node: LiteralLikeNode, text: string): boolean {
if (node.kind === SyntaxKind.NumericLiteral && text.length > 1) {
switch (text.charCodeAt(1)) {
case CharacterCodes.b:
@@ -1285,7 +1290,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return false;
}
function emitLiteral(node: LiteralExpression) {
function emitLiteral(node: LiteralExpression | TemplateLiteralFragment) {
const text = getLiteralText(node);
if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) {
@@ -1300,7 +1305,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function getLiteralText(node: LiteralExpression) {
function getLiteralText(node: LiteralExpression | TemplateLiteralFragment) {
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
@@ -1359,7 +1364,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(`"${text}"`);
}
function emitDownlevelTaggedTemplateArray(node: TaggedTemplateExpression, literalEmitter: (literal: LiteralExpression) => void) {
function emitDownlevelTaggedTemplateArray(node: TaggedTemplateExpression, literalEmitter: (literal: LiteralExpression | TemplateLiteralFragment) => void) {
write("[");
if (node.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral) {
literalEmitter(<LiteralExpression>node.template);
@@ -1992,6 +1997,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.LexicalThis) {
write("_this");
}
else if (convertedLoopState) {
write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this")));
}
else {
write("this");
}
@@ -3322,6 +3330,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName;
}
if (convertedOuterLoopState.thisName) {
// outer loop has already used 'this' so we've already have some name to alias it
// use the same name in all nested loops
convertedLoopState.thisName = convertedOuterLoopState.thisName;
}
if (convertedOuterLoopState.hoistedLocalVariables) {
// we've already collected some non-block scoped variable declarations in enclosing loop
// use the same storage in nested loop
@@ -3351,6 +3365,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeLine();
}
}
if (convertedLoopState.thisName) {
// if alias for this is set
if (convertedOuterLoopState) {
// pass it to outer converted loop
convertedOuterLoopState.thisName = convertedLoopState.thisName;
}
else {
// this is top level converted loop so we need to create an alias for 'this' here
// NOTE:
// if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
// If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
write(`var ${convertedLoopState.thisName} = this;`);
writeLine();
}
}
if (convertedLoopState.hoistedLocalVariables) {
// if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
@@ -5542,9 +5571,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDecoratorsOfClass(node);
}
if (!(node.flags & NodeFlags.Export)) {
return;
}
// If this is an exported class, but not on the top level (i.e. on an internal
// module), export it
if (!isES6ExportedDeclaration(node) && (node.flags & NodeFlags.Export)) {
if (node.flags & NodeFlags.Default) {
// if this is a top level default export of decorated class, write the export after the declaration.
writeLine();
if (thisNodeIsDecorated && modulekind === ModuleKind.ES6) {
write("export default ");
emitDeclarationName(node);
write(";");
}
else if (modulekind === ModuleKind.System) {
write(`${exportFunctionForFile}("default", `);
emitDeclarationName(node);
write(");");
}
else if (modulekind !== ModuleKind.ES6) {
write(`exports.default = `);
emitDeclarationName(node);
write(";");
}
}
else if (node.parent.kind !== SyntaxKind.SourceFile || (modulekind !== ModuleKind.ES6 && !(node.flags & NodeFlags.Default))) {
writeLine();
emitStart(node);
emitModuleMemberName(node);
@@ -5553,13 +5604,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitEnd(node);
write(";");
}
else if (isES6ExportedDeclaration(node) && (node.flags & NodeFlags.Default) && thisNodeIsDecorated) {
// if this is a top level default export of decorated class, write the export after the declaration.
writeLine();
write("export default ");
emitDeclarationName(node);
write(";");
}
}
function emitClassLikeDeclarationBelowES6(node: ClassLikeDeclaration) {
@@ -5925,7 +5969,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitSerializedTypeNode(node: TypeNode) {
if (node) {
switch (node.kind) {
case SyntaxKind.VoidKeyword:
write("void 0");
@@ -5951,7 +5994,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return;
case SyntaxKind.StringKeyword:
case SyntaxKind.StringLiteral:
case SyntaxKind.StringLiteralType:
write("String");
return;
@@ -6767,7 +6810,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string {
function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, emitRelativePathAsModuleName: boolean): string {
if (emitRelativePathAsModuleName) {
const name = getExternalModuleNameFromDeclaration(host, resolver, importNode);
if (name) {
return `"${name}"`;
}
}
const moduleName = getExternalModuleName(importNode);
if (moduleName.kind === SyntaxKind.StringLiteral) {
return tryRenameExternalModule(<LiteralExpression>moduleName) || getLiteralText(<LiteralExpression>moduleName);
@@ -7327,7 +7376,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; ++i) {
let text = getExternalModuleNameText(externalImports[i]);
const text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName);
if (hasProperty(groupIndices, text)) {
// deduplicate/group entries in dependency list by the dependency name
const groupIndex = groupIndices[text];
@@ -7343,18 +7392,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(", ");
}
if (emitRelativePathAsModuleName) {
const name = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
if (name) {
text = `"${name}"`;
}
}
write(text);
}
write(`], function(${exportFunctionForFile}) {`);
writeLine();
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
emitEmitHelpers(node);
emitCaptureThisForNodeIfNecessary(node);
emitSystemModuleBody(node, dependencyGroups, startIndex);
@@ -7391,14 +7434,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
for (const importNode of externalImports) {
// Find the name of the external module
let externalModuleName = getExternalModuleNameText(importNode);
if (emitRelativePathAsModuleName) {
const name = getExternalModuleNameFromDeclaration(host, resolver, importNode);
if (name) {
externalModuleName = `"${name}"`;
}
}
const externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName);
// Find the name of the module alias, if there is one
const importAliasName = getLocalNameForExternalImport(importNode);
@@ -7464,7 +7500,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeModuleName(node, emitRelativePathAsModuleName);
emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName);
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
@@ -7476,7 +7512,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitCommonJSModule(node: SourceFile) {
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ true);
emitEmitHelpers(node);
collectExternalModuleInfo(node);
emitExportStarHelper();
@@ -7505,7 +7541,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
})(`);
emitAMDFactoryHeader(dependencyNames);
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
@@ -7647,19 +7683,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean): number {
function isUseStrictPrologue(node: ExpressionStatement): boolean {
return !!(node.expression as StringLiteral).text.match(/use strict/);
}
function ensureUseStrictPrologue(startWithNewLine: boolean, writeUseStrict: boolean) {
if (writeUseStrict) {
if (startWithNewLine) {
writeLine();
}
write("\"use strict\";");
}
}
function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean, ensureUseStrict?: boolean): number {
let foundUseStrict = false;
for (let i = 0; i < statements.length; ++i) {
if (isPrologueDirective(statements[i])) {
if (isUseStrictPrologue(statements[i] as ExpressionStatement)) {
foundUseStrict = true;
}
if (startWithNewLine || i > 0) {
writeLine();
}
emit(statements[i]);
}
else {
ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict);
// return index of the first non prologue directive
return i;
}
}
ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict);
return statements.length;
}
+18 -6
View File
@@ -1874,7 +1874,7 @@ namespace ts {
function parseTemplateExpression(): TemplateExpression {
const template = <TemplateExpression>createNode(SyntaxKind.TemplateExpression);
template.head = parseLiteralNode();
template.head = parseTemplateLiteralFragment();
Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
const templateSpans = <NodeArray<TemplateSpan>>[];
@@ -1895,22 +1895,34 @@ namespace ts {
const span = <TemplateSpan>createNode(SyntaxKind.TemplateSpan);
span.expression = allowInAnd(parseExpression);
let literal: LiteralExpression;
let literal: TemplateLiteralFragment;
if (token === SyntaxKind.CloseBraceToken) {
reScanTemplateToken();
literal = parseLiteralNode();
literal = parseTemplateLiteralFragment();
}
else {
literal = <LiteralExpression>parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
literal = <TemplateLiteralFragment>parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
}
span.literal = literal;
return finishNode(span);
}
function parseStringLiteralTypeNode(): StringLiteralTypeNode {
return <StringLiteralTypeNode>parseLiteralLikeNode(SyntaxKind.StringLiteralType, /*internName*/ true);
}
function parseLiteralNode(internName?: boolean): LiteralExpression {
const node = <LiteralExpression>createNode(token);
return <LiteralExpression>parseLiteralLikeNode(token, internName);
}
function parseTemplateLiteralFragment(): TemplateLiteralFragment {
return <TemplateLiteralFragment>parseLiteralLikeNode(token, /*internName*/ false);
}
function parseLiteralLikeNode(kind: SyntaxKind, internName: boolean): LiteralLikeNode {
const node = <LiteralExpression>createNode(kind);
const text = scanner.getTokenValue();
node.text = internName ? internIdentifier(text) : text;
@@ -2397,7 +2409,7 @@ namespace ts {
const node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReferenceOrTypePredicate();
case SyntaxKind.StringLiteral:
return <StringLiteral>parseLiteralNode(/*internName*/ true);
return parseStringLiteralTypeNode();
case SyntaxKind.VoidKeyword:
return parseTokenNode<TypeNode>();
case SyntaxKind.ThisKeyword:
+25 -18
View File
@@ -395,7 +395,7 @@ namespace ts {
getTypeChecker,
getClassifiableNames,
getDiagnosticsProducingTypeChecker,
getCommonSourceDirectory: () => commonSourceDirectory,
getCommonSourceDirectory,
emit,
getCurrentDirectory: () => currentDirectory,
getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(),
@@ -411,6 +411,25 @@ namespace ts {
return program;
function getCommonSourceDirectory() {
if (typeof commonSourceDirectory === "undefined") {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
commonSourceDirectory = computeCommonSourceDirectory(files);
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
}
}
return commonSourceDirectory;
}
function getClassifiableNames() {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
@@ -1234,24 +1253,12 @@ namespace ts {
options.sourceRoot || // there is --sourceRoot specified
options.mapRoot) { // there is --mapRoot specified
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
// Compute the commonSourceDirectory from the input files
commonSourceDirectory = computeCommonSourceDirectory(files);
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
if (options.outDir && commonSourceDirectory === "" && forEach(files, file => getRootLength(file.fileName) > 1)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
}
}
// Precalculate and cache the common source directory
const dir = getCommonSourceDirectory();
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
}
}
+16 -1
View File
@@ -295,11 +295,26 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
configFileName = normalizePath(combinePaths(commandLine.options.project, "tsconfig.json"));
if (commandLine.fileNames.length !== 0) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
const fileOrDirectory = normalizePath(commandLine.options.project);
if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) {
configFileName = combinePaths(fileOrDirectory, "tsconfig.json");
if (!sys.fileExists(configFileName)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
}
else {
configFileName = fileOrDirectory;
if (!sys.fileExists(configFileName)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
}
}
else if (commandLine.fileNames.length === 0 && isJSONSupported()) {
const searchPath = normalizePath(sys.getCurrentDirectory());
+22 -10
View File
@@ -205,6 +205,7 @@ namespace ts {
IntersectionType,
ParenthesizedType,
ThisType,
StringLiteralType,
// Binding patterns
ObjectBindingPattern,
ArrayBindingPattern,
@@ -350,7 +351,7 @@ namespace ts {
FirstFutureReservedWord = ImplementsKeyword,
LastFutureReservedWord = YieldKeyword,
FirstTypeNode = TypePredicate,
LastTypeNode = ThisType,
LastTypeNode = StringLiteralType,
FirstPunctuation = OpenBraceToken,
LastPunctuation = CaretEqualsToken,
FirstToken = Unknown,
@@ -790,10 +791,13 @@ namespace ts {
type: TypeNode;
}
// Note that a StringLiteral AST node is both an Expression and a TypeNode. The latter is
// because string literals can appear in type annotations as well.
// @kind(SyntaxKind.StringLiteralType)
export interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode {
_stringLiteralTypeBrand: any;
}
// @kind(SyntaxKind.StringLiteral)
export interface StringLiteral extends LiteralExpression, TypeNode {
export interface StringLiteral extends LiteralExpression {
_stringLiteralBrand: any;
}
@@ -911,24 +915,32 @@ namespace ts {
body: ConciseBody;
}
export interface LiteralLikeNode extends Node {
text: string;
isUnterminated?: boolean;
hasExtendedUnicodeEscape?: boolean;
}
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
// or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
// For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
// @kind(SyntaxKind.NumericLiteral)
// @kind(SyntaxKind.RegularExpressionLiteral)
// @kind(SyntaxKind.NoSubstitutionTemplateLiteral)
export interface LiteralExpression extends LiteralLikeNode, PrimaryExpression {
_literalExpressionBrand: any;
}
// @kind(SyntaxKind.TemplateHead)
// @kind(SyntaxKind.TemplateMiddle)
// @kind(SyntaxKind.TemplateTail)
export interface LiteralExpression extends PrimaryExpression {
text: string;
isUnterminated?: boolean;
hasExtendedUnicodeEscape?: boolean;
export interface TemplateLiteralFragment extends LiteralLikeNode {
_templateLiteralFragmentBrand: any;
}
// @kind(SyntaxKind.TemplateExpression)
export interface TemplateExpression extends PrimaryExpression {
head: LiteralExpression;
head: TemplateLiteralFragment;
templateSpans: NodeArray<TemplateSpan>;
}
@@ -937,7 +949,7 @@ namespace ts {
// @kind(SyntaxKind.TemplateSpan)
export interface TemplateSpan extends Node {
expression: Expression;
literal: LiteralExpression;
literal: TemplateLiteralFragment;
}
// @kind(SyntaxKind.ParenthesizedExpression)
+1 -4
View File
@@ -466,9 +466,6 @@ namespace ts {
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.VoidExpression;
case SyntaxKind.StringLiteral:
// Specialized signatures can have string literals as their parameters' type names
return node.parent.kind === SyntaxKind.Parameter;
case SyntaxKind.ExpressionWithTypeArguments:
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
@@ -1909,7 +1906,7 @@ namespace ts {
* Resolves a local path to a path which is absolute to the base of the emit
*/
export function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string {
const dir = host.getCurrentDirectory();
const dir = toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), f => host.getCanonicalFileName(f));
const relativePath = getRelativePathToDirectoryOrUrl(dir, fileName, dir, f => host.getCanonicalFileName(f), /*isAbsolutePathAnUrl*/ false);
return removeFileExtension(relativePath);
}