Merge branch 'master' into this-function-types

This commit is contained in:
Nathan Shively-Sanders
2016-02-16 13:57:25 -08:00
520 changed files with 8644 additions and 2453 deletions
+10 -10
View File
@@ -12,7 +12,7 @@ namespace ts {
}
const enum Reachability {
Unintialized = 1 << 0,
Uninitialized = 1 << 0,
Reachable = 1 << 1,
Unreachable = 1 << 2,
ReportedUnreachable = 1 << 3
@@ -393,7 +393,7 @@ namespace ts {
// the getLocalNameOfContainer function in the type checker to validate that the local name
// used for a container is unique.
function bindChildren(node: Node) {
// Before we recurse into a node's chilren, we first save the existing parent, container
// Before we recurse into a node's children, we first save the existing parent, container
// and block-container. Then after we pop out of processing the children, we restore
// these saved values.
const saveParent = parent;
@@ -418,7 +418,7 @@ namespace ts {
// Finally, if this is a block-container, then we clear out any existing .locals object
// it may contain within it. This happens in incremental scenarios. Because we can be
// reusing a node from a previous compilation, that node may have had 'locals' created
// for it. We must clear this so we don't accidently move any stale data forward from
// for it. We must clear this so we don't accidentally move any stale data forward from
// a previous compilation.
const containerFlags = getContainerFlags(node);
if (containerFlags & ContainerFlags.IsContainer) {
@@ -699,7 +699,7 @@ namespace ts {
const hasDefault = forEach(n.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause);
// post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case
// post switch state is unreachable if switch is exhaustive (has a default case ) and does not have fallthrough from the last case
const postSwitchState = hasDefault && currentReachabilityState !== Reachability.Reachable ? Reachability.Unreachable : preSwitchState;
popImplicitLabel(postSwitchLabel, postSwitchState);
@@ -766,7 +766,7 @@ namespace ts {
case SyntaxKind.Block:
// do not treat blocks directly inside a function as a block-scoped-container.
// Locals that reside in this block should go to the function locals. Othewise 'x'
// Locals that reside in this block should go to the function locals. Otherwise 'x'
// would not appear to be a redeclaration of a block scoped local in the following
// example:
//
@@ -956,7 +956,7 @@ namespace ts {
const identifier = <Identifier>prop.name;
// ECMA-262 11.1.5 Object Initialiser
// ECMA-262 11.1.5 Object Initializer
// If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
// a.This production is contained in strict code and IsDataDescriptor(previous) is true and
// IsDataDescriptor(propId.descriptor) is true.
@@ -1632,14 +1632,14 @@ namespace ts {
if (hasProperty(labelIndexMap, name.text)) {
return false;
}
labelIndexMap[name.text] = labelStack.push(Reachability.Unintialized) - 1;
labelIndexMap[name.text] = labelStack.push(Reachability.Uninitialized) - 1;
return true;
}
function pushImplicitLabel(): number {
initializeReachabilityStateIfNecessary();
const index = labelStack.push(Reachability.Unintialized) - 1;
const index = labelStack.push(Reachability.Uninitialized) - 1;
implicitLabels.push(index);
return index;
}
@@ -1669,7 +1669,7 @@ namespace ts {
}
function setCurrentStateAtLabel(innerMergedState: Reachability, outerState: Reachability, label: Identifier): void {
if (innerMergedState === Reachability.Unintialized) {
if (innerMergedState === Reachability.Uninitialized) {
if (label && !options.allowUnusedLabels) {
file.bindDiagnostics.push(createDiagnosticForNode(label, Diagnostics.Unused_label));
}
@@ -1690,7 +1690,7 @@ namespace ts {
return false;
}
const stateAtLabel = labelStack[index];
labelStack[index] = stateAtLabel === Reachability.Unintialized ? outerState : or(stateAtLabel, outerState);
labelStack[index] = stateAtLabel === Reachability.Uninitialized ? outerState : or(stateAtLabel, outerState);
return true;
}
+353 -301
View File
File diff suppressed because it is too large Load Diff
+27 -3
View File
@@ -78,6 +78,7 @@ namespace ts {
name: "module",
shortName: "m",
type: {
"none": ModuleKind.None,
"commonjs": ModuleKind.CommonJS,
"amd": ModuleKind.AMD,
"system": ModuleKind.System,
@@ -87,7 +88,7 @@ namespace ts {
},
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
paramType: Diagnostics.KIND,
error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015
error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none
},
{
name: "newLine",
@@ -324,6 +325,11 @@ namespace ts {
name: "allowSyntheticDefaultImports",
type: "boolean",
description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
},
{
name: "noImplicitUseStrict",
type: "boolean",
description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
}
];
@@ -550,7 +556,21 @@ namespace ts {
}
else {
const filesSeen: Map<boolean> = {};
const exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let exclude: string[] = [];
if (json["exclude"] instanceof Array) {
exclude = json["exclude"];
}
else {
// by default exclude node_modules, and any specificied output directory
exclude = ["node_modules"];
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
}
}
exclude = map(exclude, normalizeSlashes);
const supportedExtensions = getSupportedExtensions(options);
Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick");
@@ -564,6 +584,11 @@ namespace ts {
continue;
}
// Skip over any minified JavaScript files (ending in ".min.js")
if (/\.min\.js$/.test(fileName)) {
continue;
}
// If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files)
// do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation
if (extension === ".d.ts" || (options.allowJs && contains(supportedJavascriptExtensions, extension))) {
@@ -587,7 +612,6 @@ namespace ts {
const errors: Diagnostic[] = [];
if (configFileName && getBaseFileName(configFileName) === "jsconfig.json") {
options.module = ModuleKind.CommonJS;
options.allowJs = true;
}
+2 -2
View File
@@ -667,7 +667,7 @@ namespace ts {
}
function getNormalizedPathComponentsOfUrl(url: string) {
// Get root length of http://www.website.com/folder1/foler2/
// Get root length of http://www.website.com/folder1/folder2/
// In this example the root is: http://www.website.com/
// normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
@@ -695,7 +695,7 @@ namespace ts {
const indexOfNextSlash = url.indexOf(directorySeparator, rootLength);
if (indexOfNextSlash !== -1) {
// Found the "/" after the website.com so the root is length of http://www.website.com/
// and get components afetr the root normally like any other folder components
// and get components after the root normally like any other folder components
rootLength = indexOfNextSlash + 1;
return normalizedPathComponents(url, rootLength);
}
+66 -69
View File
@@ -18,7 +18,7 @@ namespace ts {
referencePathsOutput: string;
}
type GetSymbolAccessibilityDiagnostic = (symbolAccesibilityResult: SymbolAccessiblityResult) => SymbolAccessibilityDiagnostic;
type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic;
interface EmitTextWriterWithSymbolWriter extends EmitTextWriter, SymbolWriter {
getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic;
@@ -51,7 +51,9 @@ namespace ts {
let decreaseIndent: () => void;
let writeTextOfNode: (text: string, node: Node) => void;
let writer = createAndSetNewTextWriterWithSymbolWriter();
let writer: EmitTextWriterWithSymbolWriter;
createAndSetNewTextWriterWithSymbolWriter();
let enclosingDeclaration: Node;
let resultHasExternalModuleIndicator: boolean;
@@ -174,7 +176,7 @@ namespace ts {
}
}
function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter {
function createAndSetNewTextWriterWithSymbolWriter(): void {
const writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine);
writer.trackSymbol = trackSymbol;
writer.reportInaccessibleThisError = reportInaccessibleThisError;
@@ -186,7 +188,6 @@ namespace ts {
writer.writeParameter = writer.write;
writer.writeSymbol = writer.write;
setWriter(writer);
return writer;
}
function setWriter(newWriter: EmitTextWriterWithSymbolWriter) {
@@ -252,30 +253,30 @@ namespace ts {
setWriter(oldWriter);
}
function handleSymbolAccessibilityError(symbolAccesibilityResult: SymbolAccessiblityResult) {
if (symbolAccesibilityResult.accessibility === SymbolAccessibility.Accessible) {
function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) {
// write the aliases
if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) {
writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible);
if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible);
}
}
else {
// Report error
reportedDeclarationError = true;
const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
getTextOfNodeFromSourceText(currentText, errorInfo.typeName),
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
symbolAccessibilityResult.errorSymbolName,
symbolAccessibilityResult.errorModuleName));
}
else {
emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
symbolAccessibilityResult.errorSymbolName,
symbolAccessibilityResult.errorModuleName));
}
}
}
@@ -548,7 +549,7 @@ namespace ts {
writeAsynchronousModuleElements(nodes);
}
function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
errorNode: node
@@ -677,7 +678,7 @@ namespace ts {
}
writer.writeLine();
function getImportEntityNameVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getImportEntityNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1,
errorNode: node,
@@ -698,10 +699,6 @@ namespace ts {
}
function writeImportDeclaration(node: ImportDeclaration) {
if (!node.importClause && !(node.flags & NodeFlags.Export)) {
// do not write non-exported import declarations that don't have import clauses
return;
}
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
write("export ");
@@ -737,7 +734,7 @@ namespace ts {
function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration) {
// emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations).
// the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered
// external modules since they are indistingushable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}'
// external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}'
// so compiler will treat them as external modules.
resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration;
let moduleSpecifier: Node;
@@ -854,7 +851,7 @@ namespace ts {
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
errorNode: node.type,
@@ -921,7 +918,7 @@ namespace ts {
}
}
function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
// Type parameter constraints are named by user so we should always be able to name it
let diagnosticMessage: DiagnosticMessage;
switch (node.parent.kind) {
@@ -991,7 +988,7 @@ namespace ts {
write("null");
}
function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getHeritageClauseVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
// Heritage clause is written by user so it can always be named
if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
@@ -1108,10 +1105,10 @@ namespace ts {
}
}
function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult) {
function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (node.kind === SyntaxKind.VariableDeclaration) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
@@ -1120,30 +1117,30 @@ namespace ts {
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (node.flags & NodeFlags.Static) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
}
else if (node.parent.kind === SyntaxKind.ClassDeclaration) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
}
else {
// Interfaces cannot have types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
}
}
}
function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult);
function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
errorNode: node,
@@ -1167,8 +1164,8 @@ namespace ts {
}
function emitBindingElement(bindingElement: BindingElement) {
function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult);
function getBindingElementTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
errorNode: bindingElement,
@@ -1259,17 +1256,17 @@ namespace ts {
}
}
function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) {
// Setters have to have type named and cannot infer it so, the type should always be named
if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1;
}
else {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1;
}
@@ -1282,15 +1279,15 @@ namespace ts {
}
else {
if (accessorWithTypeAnnotation.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0;
}
else {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0;
@@ -1389,26 +1386,26 @@ namespace ts {
writeLine();
}
function getReturnTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
switch (node.kind) {
case SyntaxKind.ConstructSignature:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
case SyntaxKind.CallSignature:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
case SyntaxKind.IndexSignature:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
@@ -1416,30 +1413,30 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
}
else if (node.parent.kind === SyntaxKind.ClassDeclaration) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
}
else {
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
}
break;
case SyntaxKind.FunctionDeclaration:
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
@@ -1485,8 +1482,8 @@ namespace ts {
writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError);
}
function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult);
function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
errorNode: node,
@@ -1494,53 +1491,53 @@ namespace ts {
} : undefined;
}
function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult): DiagnosticMessage {
function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult): DiagnosticMessage {
switch (node.parent.kind) {
case SyntaxKind.Constructor:
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
case SyntaxKind.ConstructSignature:
// Interfaces cannot have parameter types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
case SyntaxKind.CallSignature:
// Interfaces cannot have parameter types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.parent.flags & NodeFlags.Static) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
}
else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
}
else {
// Interfaces cannot have parameter types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
}
case SyntaxKind.FunctionDeclaration:
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
+30 -29
View File
@@ -1,4 +1,4 @@
{
{
"Unterminated string literal.": {
"category": "Error",
"code": 1002
@@ -123,7 +123,7 @@
"category": "Error",
"code": 1043
},
"'{0}' modifier cannot appear on a module element.": {
"'{0}' modifier cannot appear on a module or namespace element.": {
"category": "Error",
"code": 1044
},
@@ -447,7 +447,7 @@
"category": "Error",
"code": 1147
},
"Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"category": "Error",
"code": 1148
},
@@ -687,7 +687,7 @@
"category": "Error",
"code": 1218
},
"Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": {
"Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.": {
"category": "Error",
"code": 1219
},
@@ -723,6 +723,10 @@
"category": "Error",
"code": 1227
},
"A type predicate is only allowed in return type position for functions and methods.": {
"category": "Error",
"code": 1228
},
"A type predicate cannot reference a rest parameter.": {
"category": "Error",
"code": 1229
@@ -1279,10 +1283,6 @@
"category": "Error",
"code": 2417
},
"Type name '{0}' in extends clause does not reference constructor function for '{0}'.": {
"category": "Error",
"code": 2419
},
"Class '{0}' incorrectly implements interface '{1}'.": {
"category": "Error",
"code": 2420
@@ -2203,6 +2203,7 @@
"category": "Error",
"code": 5062
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@@ -2247,10 +2248,10 @@
"category": "Message",
"code": 6011
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": {
"category": "Message",
"code": 6015
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": {
"category": "Message",
"code": 6015
},
"Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'": {
"category": "Message",
"code": 6016
@@ -2335,7 +2336,7 @@
"category": "Error",
"code": 6045
},
"Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'.": {
"Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'.": {
"category": "Error",
"code": 6046
},
@@ -2587,6 +2588,11 @@
"category": "Message",
"code": 6111
},
"Do not emit 'use strict' directives in module output.": {
"category": "Message",
"code": 6112
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2739,11 +2745,6 @@
"category": "Error",
"code": 8016
},
"'decorators' can only be used in a .ts file.": {
"category": "Error",
"code": 8017
},
"Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": {
"category": "Error",
"code": 9002
@@ -2773,23 +2774,23 @@
"code": 17004
},
"A constructor cannot contain a 'super' call when its class extends 'null'": {
"category": "Error",
"code": 17005
"category": "Error",
"code": 17005
},
"An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": {
"category": "Error",
"code": 17006
"category": "Error",
"code": 17006
},
"A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": {
"category": "Error",
"code": 17007
"category": "Error",
"code": 17007
},
"JSX element '{0}' has no corresponding closing tag.": {
"category": "Error",
"code": 17008
"category": "Error",
"code": 17008
},
"'super' must be called before accessing 'this' in the constructor of a derived class.": {
"category": "Error",
"code": 17009
"category": "Error",
"code": 17009
}
}
}
+160 -47
View File
@@ -287,6 +287,54 @@ namespace ts {
_i = 0x10000000, // Use/preference flag for '_i'
}
const enum CopyDirection {
ToOriginal,
ToOutParameter
}
/**
* If loop contains block scoped binding captured in some function then loop body is converted to a function.
* Lexical bindings declared in loop initializer will be passed into the loop body function as parameters,
* however if this binding is modified inside the body - this new value should be propagated back to the original binding.
* This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body.
* On every iteration this variable is initialized with value of corresponding binding.
* At every point where control flow leaves the loop either explicitly (break/continue) or implicitly (at the end of loop body)
* we copy the value inside the loop to the out parameter holder.
*
* for (let x;;) {
* let a = 1;
* let b = () => a;
* x++
* if (...) break;
* ...
* }
*
* will be converted to
*
* var out_x;
* var loop = function(x) {
* var a = 1;
* var b = function() { return a; }
* x++;
* if (...) return out_x = x, "break";
* ...
* out_x = x;
* }
* for (var x;;) {
* out_x = x;
* var state = loop(x);
* x = out_x;
* if (state === "break") break;
* }
*
* NOTE: values to out parameters are not copies if loop is abrupted with 'return' - in this case this will end the entire enclosing function
* so nobody can observe this new value.
*/
interface LoopOutParameter {
originalName: Identifier;
outParamName: string;
}
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult {
// emit output for the __extends helper function
@@ -359,14 +407,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
interface ConvertedLoopState {
/*
* set of labels that occured inside the converted loop
* set of labels that occurred inside the converted loop
* used to determine if labeled jump can be emitted as is or it should be dispatched to calling code
*/
labels?: Map<string>;
/*
* collection of labeled jumps that transfer control outside the converted loop.
* maps store association 'label -> labelMarker' where
* - label - value of label as it apprear in code
* - label - value of label as it appear in code
* - label marker - return value that should be interpreted by calling code as 'jump to <label>'
*/
labeledNonLocalBreaks?: Map<string>;
@@ -389,7 +437,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
* i.e.
* for (let x;;) <statement that captures x in closure and uses 'arguments'>
* should be converted to
* var loop = function(x) { <code where 'arguments' is replaced witg 'arguments_1'> }
* var loop = function(x) { <code where 'arguments' is replaced with 'arguments_1'> }
* var arguments_1 = arguments
* for (var x;;) loop(x);
* otherwise semantics of the code will be different since 'arguments' inside converted loop body
@@ -419,6 +467,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
* for (var x;;) loop(x);
*/
hoistedLocalVariables?: Identifier[];
/**
* List of loop out parameters - detailed descripion can be found in the comment to LoopOutParameter
*/
loopOutParameters?: LoopOutParameter[];
}
function setLabeledJump(state: ConvertedLoopState, isBreak: boolean, labelText: string, labelMarker: string): void {
@@ -952,7 +1005,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
let text = getTextOfNodeFromSourceText(currentText, node);
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
// text contains the original source, it will also contain quotes ("`"), dollar signs and braces ("${" and "}"),
// thus we need to remove those characters.
// First template piece starts with "`", others with "}"
// Last template piece ends with "`", others with "${"
@@ -2968,11 +3021,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
let loopParameters: string[];
let loopOutParameters: LoopOutParameter[];
if (loopInitializer && (getCombinedNodeFlags(loopInitializer) & NodeFlags.BlockScoped)) {
// if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters
loopParameters = [];
for (const varDeclaration of loopInitializer.declarations) {
collectNames(varDeclaration.name);
processVariableDeclaration(varDeclaration.name);
}
}
@@ -2982,14 +3036,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
writeLine();
write(`var ${functionName} = function(${paramList})`);
if (!bodyIsBlock) {
write(" {");
writeLine();
increaseIndent();
}
const convertedOuterLoopState = convertedLoopState;
convertedLoopState = {};
convertedLoopState = { loopOutParameters };
if (convertedOuterLoopState) {
// convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
@@ -3013,16 +3061,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
emitEmbeddedStatement(node.statement);
write(" {");
writeLine();
increaseIndent();
if (!bodyIsBlock) {
decreaseIndent();
writeLine();
write("}");
if (bodyIsBlock) {
emitLines((<Block>node.statement).statements);
}
write(";");
else {
emit(node.statement);
}
writeLine();
// end of loop body -> copy out parameter
copyLoopOutParameters(convertedLoopState, CopyDirection.ToOutParameter, /*emitAsStatements*/true);
decreaseIndent();
writeLine();
write("};");
writeLine();
if (loopOutParameters) {
// declare variables to hold out params for loop body
write(`var `);
for (let i = 0; i < loopOutParameters.length; i++) {
if (i !== 0) {
write(", ");
}
write(loopOutParameters[i].outParamName);
}
write(";");
writeLine();
}
if (convertedLoopState.argumentsName) {
// if alias for arguments is set
if (convertedOuterLoopState) {
@@ -3086,14 +3156,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return { functionName, paramList, state: currentLoopState };
function collectNames(name: Identifier | BindingPattern): void {
function processVariableDeclaration(name: Identifier | BindingPattern): void {
if (name.kind === SyntaxKind.Identifier) {
const nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(<Identifier>name) ? getGeneratedNameForNode(name) : (<Identifier>name).text;
const nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(<Identifier>name)
? getGeneratedNameForNode(name)
: (<Identifier>name).text;
loopParameters.push(nameText);
if (resolver.getNodeCheckFlags(name.parent) & NodeCheckFlags.NeedsLoopOutParameter) {
const reassignedVariable = { originalName: <Identifier>name, outParamName: makeUniqueName(`out_${nameText}`) };
(loopOutParameters || (loopOutParameters = [])).push(reassignedVariable);
}
}
else {
for (const element of (<BindingPattern>name).elements) {
collectNames(element.name);
processVariableDeclaration(element.name);
}
}
}
@@ -3124,6 +3201,28 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
}
function copyLoopOutParameters(state: ConvertedLoopState, copyDirection: CopyDirection, emitAsStatements: boolean) {
if (state.loopOutParameters) {
for (const outParam of state.loopOutParameters) {
if (copyDirection === CopyDirection.ToOriginal) {
emitIdentifier(outParam.originalName);
write(` = ${outParam.outParamName}`);
}
else {
write(`${outParam.outParamName} = `);
emitIdentifier(outParam.originalName);
}
if (emitAsStatements) {
write(";");
writeLine();
}
else {
write(", ");
}
}
}
}
function emitConvertedLoopCall(loop: ConvertedLoop, emitAsBlock: boolean): void {
if (emitAsBlock) {
write(" {");
@@ -3144,6 +3243,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
write(`${loop.functionName}(${loop.paramList});`);
writeLine();
copyLoopOutParameters(loop.state, CopyDirection.ToOriginal, /*emitAsStatements*/ true);
if (!isSimpleLoop) {
// for non simple loops we need to store result returned from converted loop function and use it to do dispatching
@@ -3463,14 +3565,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
(!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
if (!canUseBreakOrContinue) {
write ("return ");
// explicit exit from loop -> copy out parameters
copyLoopOutParameters(convertedLoopState, CopyDirection.ToOutParameter, /*emitAsStatements*/ false);
if (!node.label) {
if (node.kind === SyntaxKind.BreakStatement) {
convertedLoopState.nonLocalJumps |= Jump.Break;
write(`return "break";`);
write(`"break";`);
}
else {
convertedLoopState.nonLocalJumps |= Jump.Continue;
write(`return "continue";`);
write(`"continue";`);
}
}
else {
@@ -3483,7 +3588,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
labelMarker = `continue-${node.label.text}`;
setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker);
}
write(`return "${labelMarker}";`);
write(`"${labelMarker}";`);
}
return;
@@ -3959,14 +4064,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (properties.length !== 1) {
// For anything but a single element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once.
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
// When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode);
}
for (const p of properties) {
if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) {
const propName = <Identifier | LiteralExpression>(<PropertyAssignment>p).name;
const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? <ShorthandPropertyAssignment>p : (<PropertyAssignment>p).initializer || propName;
// Assignment for target = value.propName should highligh whole property, hence use p as source map node
// Assignment for target = value.propName should highlight whole property, hence use p as source map node
emitDestructuringAssignment(target, createPropertyAccessForDestructuringProperty(value, propName), p);
}
}
@@ -3977,13 +4082,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
if (elements.length !== 1) {
// For anything but a single element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once.
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
// When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode);
}
for (let i = 0; i < elements.length; i++) {
const e = elements[i];
if (e.kind !== SyntaxKind.OmittedExpression) {
// Assignment for target = value.propName should highligh whole property, hence use e as source map node
// Assignment for target = value.propName should highlight whole property, hence use e as source map node
if (e.kind !== SyntaxKind.SpreadElementExpression) {
emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e);
}
@@ -4791,18 +4896,24 @@ const _super = (function (geti, seti) {
emitToken(SyntaxKind.CloseBraceToken, body.statements.end);
}
function findInitialSuperCall(ctor: ConstructorDeclaration): ExpressionStatement {
if (ctor.body) {
const statement = (<Block>ctor.body).statements[0];
if (statement && statement.kind === SyntaxKind.ExpressionStatement) {
const expr = (<ExpressionStatement>statement).expression;
if (expr && expr.kind === SyntaxKind.CallExpression) {
const func = (<CallExpression>expr).expression;
if (func && func.kind === SyntaxKind.SuperKeyword) {
return <ExpressionStatement>statement;
}
}
}
/**
* Return the statement at a given index if it is a super-call statement
* @param ctor a constructor declaration
* @param index an index to constructor's body to check
*/
function getSuperCallAtGivenIndex(ctor: ConstructorDeclaration, index: number): ExpressionStatement {
if (!ctor.body) {
return undefined;
}
const statements = ctor.body.statements;
if (!statements || index >= statements.length) {
return undefined;
}
const statement = statements[index];
if (statement.kind === SyntaxKind.ExpressionStatement) {
return isSuperCallExpression((<ExpressionStatement>statement).expression) ? <ExpressionStatement>statement : undefined;
}
}
@@ -5086,13 +5197,15 @@ const _super = (function (geti, seti) {
if (ctor) {
emitDefaultValueAssignments(ctor);
emitRestParameter(ctor);
if (baseTypeElement) {
superCall = findInitialSuperCall(ctor);
superCall = getSuperCallAtGivenIndex(ctor, startIndex);
if (superCall) {
writeLine();
emit(superCall);
}
}
emitParameterPropertyAssignments(ctor);
}
else {
@@ -6634,7 +6747,7 @@ const _super = (function (geti, seti) {
// when resolving exports local exported entries/indirect exported entries in the module
// should always win over entries with similar names that were added via star exports
// to support this we store names of local/indirect exported entries in a set.
// this set is used to filter names brought by star expors.
// this set is used to filter names brought by star exports.
if (!hasExportStarsToExportValues) {
// local names set is needed only in presence of star exports
return undefined;
@@ -7180,7 +7293,7 @@ const _super = (function (geti, seti) {
write(`], function(${exportFunctionForFile}, ${contextObjectForFile}) {`);
writeLine();
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict);
writeLine();
write(`var __moduleName = ${contextObjectForFile} && ${contextObjectForFile}.id;`);
writeLine();
@@ -7286,7 +7399,7 @@ const _super = (function (geti, seti) {
writeModuleName(node, emitRelativePathAsModuleName);
emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName);
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/!compilerOptions.noImplicitUseStrict);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
@@ -7298,7 +7411,7 @@ const _super = (function (geti, seti) {
}
function emitCommonJSModule(node: SourceFile) {
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict);
emitEmitHelpers(node);
collectExternalModuleInfo(node);
emitExportStarHelper();
@@ -7327,7 +7440,7 @@ const _super = (function (geti, seti) {
})(`);
emitAMDFactoryHeader(dependencyNames);
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true);
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict);
emitExportStarHelper();
emitCaptureThisForNodeIfNecessary(node);
emitLinesStartingAt(node.statements, startIndex);
@@ -7965,7 +8078,7 @@ const _super = (function (geti, seti) {
// declare var x;
// /// <reference-path ...>
// interface F {}
// The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted
// The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
if (node.pos === 0) {
leadingComments = filter(getLeadingCommentsToEmit(node), isTripleSlashComment);
}
+68 -43
View File
@@ -577,7 +577,7 @@ namespace ts {
scanner.setText("");
scanner.setOnError(undefined);
// Clear any data. We don't want to accidently hold onto it for too long.
// Clear any data. We don't want to accidentally hold onto it for too long.
parseDiagnostics = undefined;
sourceFile = undefined;
identifiers = undefined;
@@ -1442,8 +1442,8 @@ namespace ts {
// We can only reuse a node if it was parsed under the same strict mode that we're
// currently in. i.e. if we originally parsed a node in non-strict mode, but then
// the user added 'using strict' at the top of the file, then we can't use that node
// again as the presense of strict mode may cause us to parse the tokens in the file
// differetly.
// again as the presence of strict mode may cause us to parse the tokens in the file
// differently.
//
// Note: we *can* reuse tokens when the strict mode changes. That's because tokens
// are unaffected by strict mode. It's just the parser will decide what to do with it
@@ -1456,7 +1456,7 @@ namespace ts {
}
// Ok, we have a node that looks like it could be reused. Now verify that it is valid
// in the currest list parsing context that we're currently at.
// in the current list parsing context that we're currently at.
if (!canReuseNode(node, parsingContext)) {
return undefined;
}
@@ -1937,7 +1937,7 @@ namespace ts {
return finishNode(node);
}
function parseTypePredicate(lhs: Identifier | ThisTypeNode): TypePredicateNode {
function parseThisTypePredicate(lhs: ThisTypeNode): TypePredicateNode {
nextToken();
const node = createNode(SyntaxKind.TypePredicate, lhs.pos) as TypePredicateNode;
node.parameterName = lhs;
@@ -2225,7 +2225,7 @@ namespace ts {
method.name = name;
method.questionToken = questionToken;
// Method signatues don't exist in expression contexts. So they have neither
// Method signatures don't exist in expression contexts. So they have neither
// [Yield] nor [Await]
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method);
parseTypeMemberSemicolon();
@@ -2366,7 +2366,7 @@ namespace ts {
case SyntaxKind.ThisKeyword: {
const thisKeyword = parseThisTypeNode();
if (token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) {
return parseTypePredicate(thisKeyword);
return parseThisTypePredicate(thisKeyword);
}
else {
return thisKeyword;
@@ -2454,10 +2454,27 @@ namespace ts {
if (token === SyntaxKind.LessThanToken) {
return true;
}
return token === SyntaxKind.OpenParenToken && lookAhead(isUnambiguouslyStartOfFunctionType);
}
function skipParameterStart(): boolean {
if (isModifierKind(token)) {
// Skip modifiers
parseModifiers();
}
if (isIdentifier() || token === SyntaxKind.ThisKeyword) {
nextToken();
return true;
}
if (token === SyntaxKind.OpenBracketToken || token === SyntaxKind.OpenBraceToken) {
// Return true if we can parse an array or object binding pattern with no errors
const previousErrorCount = parseDiagnostics.length;
parseIdentifierOrPattern();
return previousErrorCount === parseDiagnostics.length;
}
return false;
}
function isUnambiguouslyStartOfFunctionType() {
nextToken();
if (token === SyntaxKind.CloseParenToken || token === SyntaxKind.DotDotDotToken) {
@@ -2465,22 +2482,21 @@ namespace ts {
// ( ...
return true;
}
if (isIdentifier() || isModifierKind(token) || token === SyntaxKind.ThisKeyword) {
nextToken();
if (skipParameterStart()) {
// We successfully skipped modifiers (if any) and an identifier or binding pattern,
// now see if we have something that indicates a parameter declaration
if (token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken ||
token === SyntaxKind.QuestionToken || token === SyntaxKind.EqualsToken ||
isIdentifier() || isModifierKind(token)) {
// ( id :
// ( id ,
// ( id ?
// ( id =
// ( modifier id
token === SyntaxKind.QuestionToken || token === SyntaxKind.EqualsToken) {
// ( xxx :
// ( xxx ,
// ( xxx ?
// ( xxx =
return true;
}
if (token === SyntaxKind.CloseParenToken) {
nextToken();
if (token === SyntaxKind.EqualsGreaterThanToken) {
// ( id ) =>
// ( xxx ) =>
return true;
}
}
@@ -2707,7 +2723,7 @@ namespace ts {
function isYieldExpression(): boolean {
if (token === SyntaxKind.YieldKeyword) {
// If we have a 'yield' keyword, and htis is a context where yield expressions are
// If we have a 'yield' keyword, and this is a context where yield expressions are
// allowed, then definitely parse out a yield expression.
if (inYieldContext()) {
return true;
@@ -2726,7 +2742,7 @@ namespace ts {
//
// for now we just check if the next token is an identifier. More heuristics
// can be added here later as necessary. We just need to make sure that we
// don't accidently consume something legal.
// don't accidentally consume something legal.
return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine);
}
@@ -2755,7 +2771,7 @@ namespace ts {
}
else {
// if the next token is not on the same line as yield. or we don't have an '*' or
// the start of an expressin, then this is just a simple "yield" expression.
// the start of an expression, then this is just a simple "yield" expression.
return finishNode(node);
}
}
@@ -3048,7 +3064,7 @@ namespace ts {
// Check the precedence to see if we should "take" this operator
// - For left associative operator (all operator but **), consume the operator,
// recursively call the function below, and parse binaryExpression as a rightOperand
// of the caller if the new precendence of the operator is greater then or equal to the current precendence.
// of the caller if the new precedence of the operator is greater then or equal to the current precedence.
// For example:
// a - b - c;
// ^token; leftOperand = b. Return b to the caller as a rightOperand
@@ -3057,8 +3073,8 @@ namespace ts {
// a - b * c;
// ^token; leftOperand = b. Return b * c to the caller as a rightOperand
// - For right associative operator (**), consume the operator, recursively call the function
// and parse binaryExpression as a rightOperand of the caller if the new precendence of
// the operator is strictly grater than the current precendence
// and parse binaryExpression as a rightOperand of the caller if the new precedence of
// the operator is strictly grater than the current precedence
// For example:
// a ** b ** c;
// ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
@@ -3299,7 +3315,7 @@ namespace ts {
*/
function isIncrementExpression(): boolean {
// This function is called inside parseUnaryExpression to decide
// whether to call parseSimpleUnaryExpression or call parseIncrmentExpression directly
// whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly
switch (token) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
@@ -3787,7 +3803,7 @@ namespace ts {
return undefined;
}
// If we have a '<', then only parse this as a arugment list if the type arguments
// If we have a '<', then only parse this as a argument list if the type arguments
// are complete and we have an open paren. if we don't, rewind and return nothing.
return typeArguments && canFollowTypeArgumentsInExpression()
? typeArguments
@@ -3964,7 +3980,7 @@ namespace ts {
shorthandDeclaration.equalsToken = equalsToken;
shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
}
return finishNode(shorthandDeclaration);
return addJSDocComment(finishNode(shorthandDeclaration));
}
else {
const propertyAssignment = <PropertyAssignment>createNode(SyntaxKind.PropertyAssignment, fullStart);
@@ -3973,7 +3989,7 @@ namespace ts {
propertyAssignment.questionToken = questionToken;
parseExpected(SyntaxKind.ColonToken);
propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
return finishNode(propertyAssignment);
return addJSDocComment(finishNode(propertyAssignment));
}
}
@@ -4780,8 +4796,8 @@ namespace ts {
// off. The grammar would look something like this:
//
// MemberVariableDeclaration[Yield]:
// AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initialiser_opt[In];
// AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield];
// AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In];
// AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield];
//
// The checker may still error in the static case to explicitly disallow the yield expression.
property.initializer = modifiers && modifiers.flags & NodeFlags.Static
@@ -5382,7 +5398,7 @@ namespace ts {
// ImportSpecifier:
// BindingIdentifier
// IdentifierName as BindingIdentifier
// ExportSpecififer:
// ExportSpecifier:
// IdentifierName
// IdentifierName as IdentifierName
let checkIdentifierIsKeyword = isKeyword(token) && !isIdentifier();
@@ -5731,6 +5747,9 @@ namespace ts {
function parseJSDocParameter(): ParameterDeclaration {
const parameter = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
parameter.type = parseJSDocType();
if (parseOptional(SyntaxKind.EqualsToken)) {
parameter.questionToken = createNode(SyntaxKind.EqualsToken);
}
return finishNode(parameter);
}
@@ -5738,16 +5757,22 @@ namespace ts {
const result = <JSDocTypeReference>createNode(SyntaxKind.JSDocTypeReference);
result.name = parseSimplePropertyName();
while (parseOptional(SyntaxKind.DotToken)) {
if (token === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
break;
}
else {
result.name = parseQualifiedName(result.name);
if (token === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
}
else {
while (parseOptional(SyntaxKind.DotToken)) {
if (token === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
break;
}
else {
result.name = parseQualifiedName(result.name);
}
}
}
return finishNode(result);
}
@@ -6217,7 +6242,7 @@ namespace ts {
}
// Make sure we're not trying to incrementally update a source file more than once. Once
// we do an update the original source file is considered unusbale from that point onwards.
// we do an update the original source file is considered unusable from that point onwards.
//
// This is because we do incremental parsing in-place. i.e. we take nodes from the old
// tree and give them new positions and parents. From that point on, trusting the old
@@ -6348,7 +6373,7 @@ namespace ts {
// We have an element that intersects the change range in some way. It may have its
// start, or its end (or both) in the changed range. We want to adjust any part
// that intersects such that the final tree is in a consistent state. i.e. all
// chlidren have spans within the span of their parent, and all siblings are ordered
// children have spans within the span of their parent, and all siblings are ordered
// properly.
// We may need to update both the 'pos' and the 'end' of the element.
@@ -6370,7 +6395,7 @@ namespace ts {
// -------------------ZZZ-----------------
//
// In this case, any element that started in the 'X' range will keep its position.
// However any element htat started after that will have their pos adjusted to be
// However any element that started after that will have their pos adjusted to be
// at the end of the new range. i.e. any node that started in the 'Y' range will
// be adjusted to have their start at the end of the 'Z' range.
//
@@ -6395,7 +6420,7 @@ namespace ts {
// -------------------ZZZ-----------------
//
// In this case, any element that ended in the 'X' range will keep its position.
// However any element htat ended after that will have their pos adjusted to be
// However any element that ended after that will have their pos adjusted to be
// at the end of the new range. i.e. any node that ended in the 'Y' range will
// be adjusted to have their end at the end of the 'Z' range.
if (element.end >= changeRangeOldEnd) {
@@ -6725,7 +6750,7 @@ namespace ts {
// Position was within this node. Keep searching deeper to find the node.
forEachChild(node, visitNode, visitArray);
// don't procede any futher in the search.
// don't proceed any further in the search.
return true;
}
+33 -24
View File
@@ -100,7 +100,7 @@ namespace ts {
let moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
if (traceEnabled) {
trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
}
@@ -141,7 +141,7 @@ namespace ts {
* 'typings' entry or file 'index' with some supported extension
* - Classic loader will only try to interpret '/a/b/c' as file.
*/
type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFalures: boolean, state: ModuleResolutionState) => string;
type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string;
/**
* Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
@@ -151,7 +151,7 @@ namespace ts {
* fallback to standard resolution routine.
*
* - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
* names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then canditate location to resolve module name 'c/d' will
* names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
* be '/a/b/c/d'
* - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
* will be resolved based on the content of the module name.
@@ -169,7 +169,7 @@ namespace ts {
* If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
* After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
* from the candidate location.
* Substitiution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
* Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
* substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
* will be converted to absolute using baseUrl.
* For example:
@@ -197,10 +197,10 @@ namespace ts {
* 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
* root dirs were merged together.
* I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
* Compiler wil first convert './protocols/file2' into absolute path relative to the location of containing file:
* Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
* '/local/src/content/protocols/file2' and try to load it - failure.
* Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
* be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remainining
* be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
* entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
*/
function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
@@ -232,7 +232,7 @@ namespace ts {
for (const rootDir of state.compilerOptions.rootDirs) {
// rootDirs are expected to be absolute
// in case of tsconfig.json this will happen automatically - compiler will expand relative names
// using locaton of tsconfig.json as base location
// using location of tsconfig.json as base location
let normalizedRoot = normalizePath(rootDir);
if (!endsWith(normalizedRoot, directorySeparator)) {
normalizedRoot += directorySeparator;
@@ -329,7 +329,7 @@ namespace ts {
}
}
else if (pattern === moduleName) {
// pattern was matched as is - no need to seatch further
// pattern was matched as is - no need to search further
matchedPattern = pattern;
matchedStar = undefined;
break;
@@ -533,18 +533,25 @@ namespace ts {
}
let referencedSourceFile: string;
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
break;
if (moduleHasNonRelativeName(moduleName)) {
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
break;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return referencedSourceFile
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
@@ -1025,7 +1032,7 @@ namespace ts {
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly agressive here. We do not actually *have* to throw away
// Note: we are overly aggressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
@@ -1169,7 +1176,9 @@ namespace ts {
diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.Decorator:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.decorators_can_only_be_used_in_a_ts_file));
if (!options.experimentalDecorators) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
}
return true;
}
@@ -1477,7 +1486,7 @@ namespace ts {
const resolution = resolutions[i];
setResolvedModule(file, moduleNames[i], resolution);
// add file to program only if:
// - resolution was successfull
// - resolution was successful
// - noResolve is falsy
// - module name come from the list fo imports
const shouldAddFile = resolution &&
@@ -1652,7 +1661,7 @@ namespace ts {
const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (options.isolatedModules) {
if (!options.module && languageVersion < ScriptTarget.ES6) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
@@ -1662,10 +1671,10 @@ namespace ts {
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) {
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
}
// Cannot specify module gen target of es6 when below es6
+2 -2
View File
@@ -511,7 +511,7 @@ namespace ts {
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
// a <<<<<<< or >>>>>>> marker then it is also followed by a space.
const mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text: string, pos: number) {
@@ -551,7 +551,7 @@ namespace ts {
}
else {
Debug.assert(ch === CharacterCodes.equals);
// Consume everything from the start of the mid-conlict marker to the start of the next
// Consume everything from the start of the mid-conflict marker to the start of the next
// end-conflict marker.
while (pos < len) {
const ch = text.charCodeAt(pos);
+13 -9
View File
@@ -16,6 +16,14 @@ namespace ts {
}
let nullSourceMapWriter: SourceMapWriter;
// Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans
const defaultLastEncodedSourceMapSpan: SourceMapSpan = {
emittedLine: 1,
emittedColumn: 1,
sourceLine: 1,
sourceColumn: 1,
sourceIndex: 0
};
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
@@ -79,13 +87,7 @@ namespace ts {
// Last recorded and encoded spans
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = {
emittedLine: 1,
emittedColumn: 1,
sourceLine: 1,
sourceColumn: 1,
sourceIndex: 0
};
lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan;
lastEncodedNameIndex = 0;
// Initialize source map data
@@ -159,10 +161,12 @@ namespace ts {
// Pop sourceMapDecodedMappings to remove last entry
sourceMapData.sourceMapDecodedMappings.pop();
// Change the last encoded source map
// Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan
// If the list is empty which indicates that we are at the beginning of the file,
// we have to reset it to default value (same value when we first initialize sourceMapWriter)
lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ?
sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] :
undefined;
defaultLastEncodedSourceMapSpan;
// TODO: Update lastEncodedNameIndex
// Since we dont support this any more, lets not worry about it right now.
+32 -9
View File
@@ -378,7 +378,8 @@ namespace ts {
const filePath = typeof relativeFileName !== "string"
? undefined
: toPath(relativeFileName, baseDirPath, createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
if (eventName === "change" && fileWatcherCallbacks.contains(filePath)) {
// Some applications save a working file via rename operations
if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) {
for (const fileCallback of fileWatcherCallbacks.get(filePath)) {
fileCallback(filePath);
}
@@ -411,7 +412,7 @@ namespace ts {
const useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
function readFile(fileName: string, encoding?: string): string {
if (!_fs.existsSync(fileName)) {
if (!fileExists(fileName)) {
return undefined;
}
const buffer = _fs.readFileSync(fileName);
@@ -462,6 +463,32 @@ namespace ts {
return useCaseSensitiveFileNames ? path : path.toLowerCase();
}
const enum FileSystemEntryKind {
File,
Directory
}
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {
try {
const stat = _fs.statSync(path);
switch (entryKind) {
case FileSystemEntryKind.File: return stat.isFile();
case FileSystemEntryKind.Directory: return stat.isDirectory();
}
}
catch (e) {
return false;
}
}
function fileExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.File);
}
function directoryExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.Directory);
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
@@ -500,7 +527,7 @@ namespace ts {
readFile,
writeFile,
watchFile: (filePath, callback) => {
// Node 4.0 stablized the `fs.watch` function on Windows which avoids polling
// Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling
// and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
@@ -538,12 +565,8 @@ namespace ts {
resolvePath: function (path: string): string {
return _path.resolve(path);
},
fileExists(path: string): boolean {
return _fs.existsSync(path);
},
directoryExists(path: string) {
return _fs.existsSync(path) && _fs.statSync(path).isDirectory();
},
fileExists,
directoryExists,
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
+6 -6
View File
@@ -115,7 +115,7 @@ namespace ts {
const gutterStyleSequence = "\u001b[100;30m";
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const elipsis = "...";
const ellipsis = "...";
const categoryFormatMap: Map<string> = {
[DiagnosticCategory.Warning]: yellowForegroundEscapeSequence,
[DiagnosticCategory.Error]: redForegroundEscapeSequence,
@@ -139,7 +139,7 @@ namespace ts {
const hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
let gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(elipsis.length, gutterWidth);
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
output += sys.newLine;
@@ -147,7 +147,7 @@ namespace ts {
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
output += formatAndReset(padLeft(elipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine;
output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine;
i = lastLine - 1;
}
@@ -341,7 +341,7 @@ namespace ts {
const directory = ts.getDirectoryPath(configFileName);
directoryWatcher = sys.watchDirectory(
// When the configFileName is just "tsconfig.json", the watched directory should be
// the current direcotry; if there is a given "project" parameter, then the configFileName
// the current directory; if there is a given "project" parameter, then the configFileName
// is an absolute file name.
directory == "" ? "." : directory,
watchedDirectoryChanged, /*recursive*/ true);
@@ -376,7 +376,7 @@ namespace ts {
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options);
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options, configFileName);
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -486,7 +486,7 @@ namespace ts {
}
function watchedDirectoryChanged(fileName: string) {
if (fileName && !ts.isSupportedSourceFileName(fileName, commandLine.options)) {
if (fileName && !ts.isSupportedSourceFileName(fileName, compilerOptions)) {
return;
}
+1 -2
View File
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
@@ -8,9 +7,9 @@
"sourceMap": true
},
"files": [
"types.ts",
"core.ts",
"sys.ts",
"types.ts",
"diagnosticInformationMap.generated.ts",
"scanner.ts",
"parser.ts",
+24 -27
View File
@@ -422,15 +422,10 @@ namespace ts {
IntrinsicNamedElement = 1 << 0,
/** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 1 << 1,
/** An element backed by a class, class-like, or function value */
ValueElement = 1 << 2,
/** Element resolution failed */
UnknownElement = 1 << 4,
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement,
}
/* @internal */
export const enum RelationComparisonResult {
Succeeded = 1, // Should be truthy
@@ -1559,7 +1554,7 @@ namespace ts {
/* @internal */ classifiableNames?: Map<string>;
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
// It is used to resolve module names in the checker.
// Content of this fiels should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<ResolvedModule>;
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
@@ -1753,7 +1748,8 @@ namespace ts {
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -1818,22 +1814,24 @@ namespace ts {
Identifier
}
export interface TypePredicate {
export interface TypePredicateBase {
kind: TypePredicateKind;
type: Type;
}
// @kind (TypePredicateKind.This)
export interface ThisTypePredicate extends TypePredicate {
export interface ThisTypePredicate extends TypePredicateBase {
_thisTypePredicateBrand: any;
}
// @kind (TypePredicateKind.Identifier)
export interface IdentifierTypePredicate extends TypePredicate {
export interface IdentifierTypePredicate extends TypePredicateBase {
parameterName: string;
parameterIndex: number;
}
export type TypePredicate = IdentifierTypePredicate | ThisTypePredicate;
/* @internal */
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
@@ -1846,7 +1844,7 @@ namespace ts {
}
/* @internal */
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
export interface SymbolAccessibilityResult extends SymbolVisibilityResult {
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
@@ -1888,7 +1886,7 @@ namespace ts {
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
@@ -2013,7 +2011,7 @@ namespace ts {
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
isDeclaratonWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // true if module exports some value (not just types)
}
@@ -2041,9 +2039,9 @@ namespace ts {
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function
BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement
HasSeenSuperCall = 0x00080000, // Set during the binding when encounter 'super'
ClassWithBodyScopedClassBinding = 0x00100000, // Decorated class that contains a binding to itself inside of the class body.
BodyScopedClassBinding = 0x00200000, // Binding to a decorated class inside of the class's body.
ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body.
BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body.
NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop
}
/* @internal */
@@ -2061,8 +2059,10 @@ namespace ts {
assignmentChecks?: Map<boolean>; // Cache of assignment checks
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
importOnRightSide?: Symbol; // for import declarations - import that appear on the right side
jsxFlags?: JsxFlags; // flags for knowning what kind of element/attributes we're dealing with
jsxFlags?: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
resolvedJsxType?: Type; // resolved element attributes type of a JSX openinglike element
hasSuperCall?: boolean; // recorded result when we try to find super-call. We only try to find one if this flag is undefined, indicating that we haven't made an attempt.
superCall?: ExpressionStatement; // Cached first super-call found in the constructor. Used in checking whether super is called before this-accessing
}
export const enum TypeFlags {
@@ -2098,7 +2098,6 @@ namespace ts {
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
PredicateType = 0x08000000, // Predicate types are also Boolean types, but should not be considered Intrinsics - there's no way to capture this with flags
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@@ -2110,7 +2109,7 @@ namespace ts {
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral | PredicateType,
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
/* @internal */
PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
@@ -2131,11 +2130,6 @@ namespace ts {
intrinsicName: string; // Name of intrinsic type
}
// Predicate types (TypeFlags.Predicate)
export interface PredicateType extends Type {
predicate: ThisTypePredicate | IdentifierTypePredicate;
}
// String literal types (TypeFlags.StringLiteral)
export interface StringLiteralType extends Type {
text: string; // Text of string literal
@@ -2166,7 +2160,7 @@ namespace ts {
// Type references (TypeFlags.Reference). When a class or interface has type parameters or
// a "this" type, references to the class or interface are made using type references. The
// typeArguments property specififes the types to substitute for the type parameters of the
// typeArguments property specifies the types to substitute for the type parameters of the
// class or interface and optionally includes an extra element that specifies the type to
// substitute for "this" in the resulting instantiation. When no extra argument is present,
// the type reference itself is substituted for "this". The typeArguments property is undefined
@@ -2271,6 +2265,8 @@ namespace ts {
erasedSignatureCache?: Signature; // Erased version of signature (deferred)
/* @internal */
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
/* @internal */
typePredicate?: TypePredicate;
}
export const enum IndexKind {
@@ -2424,6 +2420,7 @@ namespace ts {
traceModuleResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
/* @internal */ stripInternal?: boolean;
// Skip checking lib.d.ts to help speed up tests.
@@ -2694,7 +2691,7 @@ namespace ts {
/*
* CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
* module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
* will appply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
* will apply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
* If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
* 'throw new Error("NotImplemented")'
*/
@@ -2720,7 +2717,7 @@ namespace ts {
getGlobalDiagnostics(): Diagnostic[];
// If fileName is provided, gets all the diagnostics associated with that file name.
// Otherwise, returns all the diagnostics (global and file associated) in this colletion.
// Otherwise, returns all the diagnostics (global and file associated) in this collection.
getDiagnostics(fileName?: string): Diagnostic[];
// Gets a count of how many times this collection has been modified. This value changes
+45 -15
View File
@@ -137,7 +137,7 @@ namespace ts {
node.flags |= NodeFlags.ThisNodeOrAnySubNodesHasError;
}
// Also mark that we've propogated the child information to this node. This way we can
// Also mark that we've propagated the child information to this node. This way we can
// always consult the bit directly on this node without needing to check its children
// again.
node.flags |= NodeFlags.HasAggregatedChildData;
@@ -387,6 +387,8 @@ namespace ts {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeAliasDeclaration:
errorNode = (<Declaration>node).name;
break;
@@ -464,6 +466,10 @@ namespace ts {
return !!(getCombinedNodeFlags(node) & NodeFlags.Let);
}
export function isSuperCallExpression(n: Node): boolean {
return n.kind === SyntaxKind.CallExpression && (<CallExpression>n).expression.kind === SyntaxKind.SuperKeyword;
}
export function isPrologueDirective(node: Node): boolean {
return node.kind === SyntaxKind.ExpressionStatement && (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
}
@@ -742,6 +748,10 @@ namespace ts {
return predicate && predicate.kind === TypePredicateKind.Identifier;
}
export function isThisTypePredicate(predicate: TypePredicate): predicate is ThisTypePredicate {
return predicate && predicate.kind === TypePredicateKind.This;
}
export function getContainingFunction(node: Node): FunctionLikeDeclaration {
while (true) {
node = node.parent;
@@ -1212,13 +1222,19 @@ namespace ts {
}
// Also recognize when the node is the RHS of an assignment expression
const parent = node.parent;
const isSourceOfAssignmentExpressionStatement =
node.parent && node.parent.parent &&
node.parent.kind === SyntaxKind.BinaryExpression &&
(node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken &&
node.parent.parent.kind === SyntaxKind.ExpressionStatement;
parent && parent.parent &&
parent.kind === SyntaxKind.BinaryExpression &&
(parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken &&
parent.parent.kind === SyntaxKind.ExpressionStatement;
if (isSourceOfAssignmentExpressionStatement) {
return node.parent.parent.jsDocComment;
return parent.parent.jsDocComment;
}
const isPropertyAssignmentExpression = parent && parent.kind === SyntaxKind.PropertyAssignment;
if (isPropertyAssignmentExpression) {
return parent.jsDocComment;
}
}
@@ -2001,9 +2017,9 @@ namespace ts {
}
export function getEmitModuleKind(compilerOptions: CompilerOptions) {
return compilerOptions.module ?
return typeof compilerOptions.module === "number" ?
compilerOptions.module :
getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None;
getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS;
}
export interface EmitFileNames {
@@ -2030,8 +2046,22 @@ namespace ts {
}
function onSingleFileEmit(host: EmitHost, sourceFile: SourceFile) {
const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host,
sourceFile.languageVariant === LanguageVariant.JSX && options.jsx === JsxEmit.Preserve ? ".jsx" : ".js");
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
let extension = ".js";
if (options.jsx === JsxEmit.Preserve) {
if (isSourceFileJavaScript(sourceFile)) {
if (fileExtensionIs(sourceFile.fileName, ".jsx")) {
extension = ".jsx";
}
}
else if (sourceFile.languageVariant === LanguageVariant.JSX) {
// TypeScript source file preserving JSX syntax
extension = ".jsx";
}
}
const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
const emitFileNames: EmitFileNames = {
jsFilePath,
sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
@@ -2562,7 +2592,7 @@ namespace ts {
byte4 = 64;
}
// Write to the ouput
// Write to the output
result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
i += 3;
@@ -2757,9 +2787,9 @@ namespace ts {
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// (Note the dots represent the newly inferrred start.
// (Note the dots represent the newly inferred start.
// Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
// absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see
// absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
// which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
// means:
//
@@ -2782,8 +2812,8 @@ namespace ts {
// ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
// that's the same as if we started at char 80 instead of 60.
//
// As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter
// than pusing the first edit forward to match the second, we'll push the second edit forward to match the
// As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather
// than pushing the first edit forward to match the second, we'll push the second edit forward to match the
// first.
//
// In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
+3 -3
View File
@@ -746,7 +746,7 @@ namespace Harness {
namespace Harness {
export const libFolder = "built/local/";
const tcServicesFileName = ts.combinePaths(libFolder, "typescriptServices.js");
const tcServicesFileName = ts.combinePaths(libFolder, Utils.getExecutionEnvironment() === Utils.ExecutionEnvironment.Browser ? "typescriptServicesInBrowserTest.js" : "typescriptServices.js");
export const tcServicesFile = IO.readFile(tcServicesFileName);
export interface SourceMapEmitterCallback {
@@ -895,7 +895,8 @@ namespace Harness {
{ name: "includeBuiltFile", type: "string" },
{ name: "fileName", type: "string" },
{ name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" }
{ name: "noErrorTruncation", type: "boolean" },
{ name: "suppressOutputPathCheck", type: "boolean" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
@@ -965,7 +966,6 @@ namespace Harness {
const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.clone(compilerOptions) : { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.module = options.module || ts.ModuleKind.None;
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
options.noErrorTruncation = true;
options.skipDefaultLibCheck = true;
+12 -1
View File
@@ -223,7 +223,18 @@ namespace Playback {
recordLog.directoriesRead.push(logEntry);
return result;
},
(path, extension, exclude) => findResultByPath(wrapper, replayLog.directoriesRead.filter(d => d.extension === extension && ts.arrayIsEqualTo(d.exclude, exclude)), path));
(path, extension, exclude) => findResultByPath(wrapper,
replayLog.directoriesRead.filter(
d => {
if (d.extension === extension) {
if (d.exclude) {
return ts.arrayIsEqualTo(d.exclude, exclude);
}
return true;
}
return false;
}
), path));
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
+1 -6
View File
@@ -1116,12 +1116,7 @@ interface Array<T> {
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat<U extends T[]>(...items: U[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: T[]): T[];
concat(...items: (T | T[])[]): T[];
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
-1
View File
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
+28 -20
View File
@@ -502,7 +502,7 @@ namespace ts {
spacesToRemoveAfterAsterisk = 0;
}
// Analyse text on this line
// Analyze text on this line
while (pos < end && !isLineBreak(sourceFile.text.charCodeAt(pos))) {
const ch = sourceFile.text.charAt(pos);
if (ch === "@") {
@@ -641,7 +641,7 @@ namespace ts {
paramHelpStringMargin = undefined;
}
// If this is the start of another tag, continue with the loop in seach of param tag with symbol name
// If this is the start of another tag, continue with the loop in search of param tag with symbol name
if (sourceFile.text.charCodeAt(pos) === CharacterCodes.at) {
continue;
}
@@ -1714,7 +1714,6 @@ namespace ts {
// Always default to "ScriptTarget.ES5" for the language service
return {
target: ScriptTarget.ES5,
module: ModuleKind.None,
jsx: JsxEmit.Preserve
};
}
@@ -2823,7 +2822,7 @@ namespace ts {
}
// Check if the language version has changed since we last created a program; if they are the same,
// it is safe to reuse the souceFiles; if not, then the shape of the AST can change, and the oldSourceFile
// it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile
// can not be reused. we have to dump all syntax trees and create new ones.
if (!changesInCompilationSettingsAffectSyntax) {
// Check if the old program had this file already
@@ -2917,7 +2916,7 @@ namespace ts {
}
/**
* getSemanticDiagnostiscs return array of Diagnostics. If '-d' is not enabled, only report semantic errors
* getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors
* If '-d' enabled, report both semantic and emitter errors
*/
function getSemanticDiagnostics(fileName: string): Diagnostic[] {
@@ -3726,7 +3725,7 @@ namespace ts {
* do not occur at the current position and have not otherwise been typed.
*/
function filterNamedImportOrExportCompletionItems(exportsOfModule: Symbol[], namedImportsOrExports: ImportOrExportSpecifier[]): Symbol[] {
const exisingImportsOrExports: Map<boolean> = {};
const existingImportsOrExports: Map<boolean> = {};
for (const element of namedImportsOrExports) {
// If this is the current item we are editing right now, do not filter it out
@@ -3735,14 +3734,14 @@ namespace ts {
}
const name = element.propertyName || element.name;
exisingImportsOrExports[name.text] = true;
existingImportsOrExports[name.text] = true;
}
if (isEmpty(exisingImportsOrExports)) {
if (isEmpty(existingImportsOrExports)) {
return exportsOfModule;
}
return filter(exportsOfModule, e => !lookUp(exisingImportsOrExports, e.name));
return filter(exportsOfModule, e => !lookUp(existingImportsOrExports, e.name));
}
/**
@@ -3824,7 +3823,7 @@ namespace ts {
return undefined;
}
const { symbols, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot, isJsDocTagName } = completionData;
const { symbols, isMemberCompletion, isNewIdentifierLocation, location, isJsDocTagName } = completionData;
if (isJsDocTagName) {
// If the current position is a jsDoc tag name, only tag names should be provided for completion
@@ -3835,7 +3834,7 @@ namespace ts {
const entries: CompletionEntry[] = [];
if (isRightOfDot && isSourceFileJavaScript(sourceFile)) {
if (isSourceFileJavaScript(sourceFile)) {
const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries);
addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames));
}
@@ -4652,7 +4651,16 @@ namespace ts {
// to jump to the implementation directly.
if (symbol.flags & SymbolFlags.Alias) {
const declaration = symbol.declarations[0];
if (node.kind === SyntaxKind.Identifier && node.parent === declaration) {
// Go to the original declaration for cases:
//
// (1) when the aliased symbol was declared in the location(parent).
// (2) when the aliased symbol is originating from a named import.
//
if (node.kind === SyntaxKind.Identifier &&
(node.parent === declaration ||
(declaration.kind === SyntaxKind.ImportSpecifier && declaration.parent && declaration.parent.kind === SyntaxKind.NamedImports))) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
}
@@ -5578,7 +5586,7 @@ namespace ts {
}
// If the symbol is an import we would like to find it if we are looking for what it imports.
// So consider it visibile outside its declaration scope.
// So consider it visible outside its declaration scope.
if (symbol.flags & SymbolFlags.Alias) {
return undefined;
}
@@ -5978,12 +5986,12 @@ namespace ts {
// The search set contains at least the current symbol
let result = [symbol];
// If the symbol is an alias, add what it alaises to the list
// If the symbol is an alias, add what it aliases to the list
if (isImportSpecifierSymbol(symbol)) {
result.push(typeChecker.getAliasedSymbol(symbol));
}
// For export specifiers, the exported name can be refering to a local symbol, e.g.:
// For export specifiers, the exported name can be referring to a local symbol, e.g.:
// import {a} from "mod";
// export {a as somethingElse}
// We want the *local* declaration of 'a' as declared in the import,
@@ -6019,7 +6027,7 @@ namespace ts {
// If the symbol.valueDeclaration is a property parameter declaration,
// we should include both parameter declaration symbol and property declaration symbol
// Parameter Declaration symbol is only visible within function scope, so the symbol is stored in contructor.locals.
// Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals.
// Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members
if (symbol.valueDeclaration && symbol.valueDeclaration.kind === SyntaxKind.Parameter &&
isParameterPropertyDeclaration(<ParameterDeclaration>symbol.valueDeclaration)) {
@@ -6045,9 +6053,9 @@ namespace ts {
/**
* Find symbol of the given property-name and add the symbol to the given result array
* @param symbol a symbol to start searching for the given propertyName
* @param propertyName a name of property to serach for
* @param propertyName a name of property to search for
* @param result an array of symbol of found property symbols
* @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisitng of the same symbol.
* @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
* The value of previousIterationSymbol is undefined when the function is first called.
*/
function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, result: Symbol[],
@@ -7390,12 +7398,12 @@ namespace ts {
// comment portion.
const singleLineCommentStart = /(?:\/\/+\s*)/.source;
const multiLineCommentStart = /(?:\/\*+\s*)/.source;
const anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
// Match any of the above three TODO comment start regexps.
// Note that the outermost group *is* a capture group. We want to capture the preamble
// so that we can determine the starting position of the TODO comment match.
const preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
// Takes the descriptors and forms a regexp that matches them as if they were literals.
// For example, if the descriptors are "TODO(jason)" and "HACK", then this will be:
-1
View File
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,