Merge branch 'master' into dynamicNames

This commit is contained in:
Ron Buckton committed 2017-05-10 09:40:46 -07:00
commit 2a73d08d38
331 files changed
+7612 -3246

No files matched your search

-1
View File
@@ -39,7 +39,6 @@
"@types/gulp-help": "latest",
"@types/gulp-newer": "latest",
"@types/gulp-sourcemaps": "latest",
"@types/gulp-typescript": "latest",
"@types/merge2": "latest",
"@types/minimatch": "latest",
"@types/minimist": "latest",
+23 -22
View File
@@ -227,12 +227,13 @@ namespace ts {
// Should not be called on a declaration with a computed property name,
// unless it is a well known Symbol.
function getDeclarationName(node: Declaration): string {
if (node.name) {
const name = getNameOfDeclaration(node);
if (name) {
if (isAmbientModule(node)) {
return isGlobalScopeAugmentation(<ModuleDeclaration>node) ? "__global" : `"${(<LiteralExpression>node.name).text}"`;
return isGlobalScopeAugmentation(<ModuleDeclaration>node) ? "__global" : `"${(<LiteralExpression>name).text}"`;
}
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>node.name).expression;
if (name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>name).expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteral(nameExpression)) {
return nameExpression.text;
@@ -241,7 +242,7 @@ namespace ts {
Debug.assert(isWellKnownSymbolSyntactically(nameExpression));
return getPropertyNameForKnownSymbolName((<PropertyAccessExpression>nameExpression).name.text);
}
return (<Identifier | LiteralExpression>node.name).text;
return (<Identifier | LiteralExpression>name).text;
}
switch (node.kind) {
case SyntaxKind.Constructor:
@@ -303,7 +304,7 @@ namespace ts {
}
function getDisplayName(node: Declaration): string {
return node.name ? declarationNameToString(node.name) : getDeclarationName(node);
return (node as NamedDeclaration).name ? declarationNameToString((node as NamedDeclaration).name) : getDeclarationName(node);
}
/**
@@ -366,8 +367,8 @@ namespace ts {
symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name));
}
else {
if (node.name) {
node.name.parent = node;
if ((node as NamedDeclaration).name) {
(node as NamedDeclaration).name.parent = node;
}
// Report errors every position with duplicate declaration
@@ -389,16 +390,16 @@ namespace ts {
// 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
// 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
if (symbol.declarations && symbol.declarations.length &&
(isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(<ExportAssignment>node).isExportEquals))) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
}
(isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(<ExportAssignment>node).isExportEquals))) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
}
}
}
forEach(symbol.declarations, declaration => {
file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));
file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(declaration) || declaration, message, getDisplayName(declaration)));
});
file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node)));
file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(node) || node, message, getDisplayName(node)));
symbol = createSymbol(SymbolFlags.None, name);
}
@@ -439,9 +440,9 @@ namespace ts {
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag &&
node.name &&
node.name.kind === SyntaxKind.Identifier &&
(<Identifier>node.name).isInJSDocNamespace;
(node as JSDocTypedefTag).name &&
(node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier &&
((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace;
if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) {
const exportKind =
(symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) |
@@ -1414,7 +1415,7 @@ namespace ts {
if (isObjectLiteralOrClassExpressionMethod(node)) {
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod;
}
// falls through
// falls through
case SyntaxKind.Constructor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodSignature:
@@ -1716,7 +1717,7 @@ namespace ts {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
}
// falls through
// falls through
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = createMap<Symbol>();
@@ -2010,7 +2011,7 @@ namespace ts {
bindBlockScopedDeclaration(<Declaration>parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
break;
}
// falls through
// falls through
case SyntaxKind.ThisKeyword:
if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) {
node.flowNode = currentFlow;
@@ -2186,7 +2187,7 @@ namespace ts {
if (!isFunctionLike(node.parent)) {
return;
}
// falls through
// falls through
case SyntaxKind.ModuleBlock:
return updateStrictModeStatementList((<Block | ModuleBlock>node).statements);
}
@@ -2211,7 +2212,7 @@ namespace ts {
}
function bindSourceFileAsExternalModule() {
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName) }"`);
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`);
}
function bindExportAssignment(node: ExportAssignment | BinaryExpression) {
@@ -2504,7 +2505,7 @@ namespace ts {
}
function bindParameter(node: ParameterDeclaration) {
if (inStrictMode) {
if (inStrictMode && !isInAmbientContext(node)) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
checkStrictModeEvalOrArguments(node, node.name);
+470 -223
View File
File diff suppressed because it is too large. Load diff
+125 -82
View File
@@ -1088,58 +1088,38 @@ namespace ts {
* @param host Instance of ParseConfigHost used to enumerate files in folder.
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
* @param resolutionStack Only present for backwards-compatibility. Should be empty.
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: JsFileExtensionInfo[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(
json: any,
host: ParseConfigHost,
basePath: string,
existingOptions: CompilerOptions = {},
configFileName?: string,
resolutionStack: Path[] = [],
extraFileExtensions: JsFileExtensionInfo[] = [],
): ParsedCommandLine {
const errors: Diagnostic[] = [];
basePath = normalizeSlashes(basePath);
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
return {
options: {},
fileNames: [],
typeAcquisition: {},
raw: json,
errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))],
wildcardDirectories: {}
};
}
let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
let options = (() => {
const { include, exclude, files, options, compileOnSave } = parseConfig(json, host, basePath, configFileName, resolutionStack, errors);
if (include) { json.include = include; }
if (exclude) { json.exclude = exclude; }
if (files) { json.files = files; }
if (compileOnSave !== undefined) { json.compileOnSave = compileOnSave; }
return options;
})();
options = extend(existingOptions, options);
options.configFilePath = configFileName;
// typingOptions has been deprecated and is only supported for backward compatibility purposes.
// It should be removed in future releases - use typeAcquisition instead.
const jsonOptions = json["typeAcquisition"] || json["typingOptions"];
const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
let baseCompileOnSave: boolean;
if (json["extends"]) {
let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}];
if (typeof json["extends"] === "string") {
[include, exclude, files, baseCompileOnSave, baseOptions] = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]);
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
}
if (include && !json["include"]) {
json["include"] = include;
}
if (exclude && !json["exclude"]) {
json["exclude"] = exclude;
}
if (files && !json["files"]) {
json["files"] = files;
}
options = assign({}, baseOptions, options);
}
options = extend(existingOptions, options);
options.configFilePath = configFileName;
const { fileNames, wildcardDirectories } = getFileNames(errors);
let compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
if (baseCompileOnSave && json[compileOnSaveCommandLineOption.name] === undefined) {
compileOnSave = baseCompileOnSave;
}
const { fileNames, wildcardDirectories } = getFileNames();
const compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
return {
options,
@@ -1151,40 +1131,7 @@ namespace ts {
compileOnSave
};
function tryExtendsName(extendedConfig: string): [string[], string[], string[], boolean, CompilerOptions] {
// If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future)
if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) {
errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
return;
}
let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName);
if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) {
extendedConfigPath = `${extendedConfigPath}.json` as Path;
if (!host.fileExists(extendedConfigPath)) {
errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig));
return;
}
}
const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path));
if (extendedResult.error) {
errors.push(extendedResult.error);
return;
}
const extendedDirname = getDirectoryPath(extendedConfigPath);
const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName);
const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path);
// Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios)
const result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath]));
errors.push(...result.errors);
const [include, exclude, files] = map(["include", "exclude", "files"], key => {
if (!json[key] && extendedResult.config[key]) {
return map(extendedResult.config[key], updatePath);
}
});
return [include, exclude, files, result.compileOnSave, result.options];
}
function getFileNames(errors: Diagnostic[]): ExpandResult {
function getFileNames(): ExpandResult {
let fileNames: string[];
if (hasProperty(json, "files")) {
if (isArray(json["files"])) {
@@ -1217,9 +1164,6 @@ namespace ts {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"));
}
}
else if (hasProperty(json, "excludes")) {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
else {
// If no includes were specified, exclude common package folders and the outDir
excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"];
@@ -1249,7 +1193,106 @@ namespace ts {
}
}
export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined {
interface ParsedTsconfig {
include: string[] | undefined;
exclude: string[] | undefined;
files: string[] | undefined;
options: CompilerOptions;
compileOnSave: boolean | undefined;
}
/**
* This *just* extracts options/include/exclude/files out of a config file.
* It does *not* resolve the included files.
*/
function parseConfig(
json: any,
host: ParseConfigHost,
basePath: string,
configFileName: string,
resolutionStack: Path[],
errors: Diagnostic[],
): ParsedTsconfig {
basePath = normalizeSlashes(basePath);
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
return { include: undefined, exclude: undefined, files: undefined, options: {}, compileOnSave: undefined };
}
if (hasProperty(json, "excludes")) {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
let include: string[] | undefined = json.include, exclude: string[] | undefined = json.exclude, files: string[] | undefined = json.files;
let compileOnSave: boolean | undefined = json.compileOnSave;
if (json.extends) {
// copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = resolutionStack.concat([resolvedPath]);
const base = getExtendedConfig(json.extends, host, basePath, getCanonicalFileName, resolutionStack, errors);
if (base) {
include = include || base.include;
exclude = exclude || base.exclude;
files = files || base.files;
if (compileOnSave === undefined) {
compileOnSave = base.compileOnSave;
}
options = assign({}, base.options, options);
}
}
return { include, exclude, files, options, compileOnSave };
}
function getExtendedConfig(
extended: any, // Usually a string.
host: ts.ParseConfigHost,
basePath: string,
getCanonicalFileName: (fileName: string) => string,
resolutionStack: Path[],
errors: Diagnostic[],
): ParsedTsconfig | undefined {
if (typeof extended !== "string") {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
return undefined;
}
extended = normalizeSlashes(extended);
// If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future)
if (!(isRootedDiskPath(extended) || startsWith(extended, "./") || startsWith(extended, "../"))) {
errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extended));
return undefined;
}
let extendedConfigPath = toPath(extended, basePath, getCanonicalFileName);
if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, ".json")) {
extendedConfigPath = extendedConfigPath + ".json" as Path;
if (!host.fileExists(extendedConfigPath)) {
errors.push(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, extended));
return undefined;
}
}
const extendedResult = readConfigFile(extendedConfigPath, path => host.readFile(path));
if (extendedResult.error) {
errors.push(extendedResult.error);
return undefined;
}
const extendedDirname = getDirectoryPath(extendedConfigPath);
const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName);
const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path);
const { include, exclude, files, options, compileOnSave } = parseConfig(extendedResult.config, host, extendedDirname, getBaseFileName(extendedConfigPath), resolutionStack, errors);
return { include: map(include, updatePath), exclude: map(exclude, updatePath), files: map(files, updatePath), compileOnSave, options };
}
export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean {
if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) {
return false;
}
+60 -40
View File
@@ -596,12 +596,11 @@ namespace ts {
emitLines(node.statements);
}
// Return a temp variable name to be used in `export default` statements.
// Return a temp variable name to be used in `export default`/`export class ... extends` statements.
// The temp name will be of the form _default_counter.
// Note that export default is only allowed at most once in a module, so we
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName(): string {
const baseName = "_default";
function getExportTempVariableName(baseName: string): string {
if (!currentIdentifiers.has(baseName)) {
return baseName;
}
@@ -615,24 +614,31 @@ namespace ts {
}
}
function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic): string {
const tempVarName = getExportTempVariableName(baseName);
if (!noDeclare) {
write("declare ");
}
write("const ");
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = () => diagnostic;
resolver.writeTypeOfExpression(expr, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
write(";");
writeLine();
return tempVarName;
}
function emitExportAssignment(node: ExportAssignment) {
if (node.expression.kind === SyntaxKind.Identifier) {
write(node.isExportEquals ? "export = " : "export default ");
writeTextOfNode(currentText, node.expression);
}
else {
// Expression
const tempVarName = getExportDefaultTempVariableName();
if (!noDeclare) {
write("declare ");
}
write("var ");
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
write(";");
writeLine();
const tempVarName = emitTempVariableDeclaration(node.expression, "_default", {
diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
errorNode: node
});
write(node.isExportEquals ? "export = " : "export default ");
write(tempVarName);
}
@@ -646,13 +652,6 @@ namespace ts {
// write each of these declarations asynchronously
writeAsynchronousModuleElements(nodes);
}
function getDefaultExportAccessibilityDiagnostic(): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
errorNode: node
};
}
}
function isModuleElementVisible(node: Declaration) {
@@ -1099,7 +1098,7 @@ namespace ts {
}
}
function emitHeritageClause(className: Identifier, typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) {
function emitHeritageClause(typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) {
if (typeReferences) {
write(isImplementsList ? " implements " : " extends ");
emitCommaList(typeReferences, emitTypeOfTypeReference);
@@ -1112,12 +1111,6 @@ namespace ts {
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
write("null");
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
errorNameNode = className;
resolver.writeBaseConstructorTypeOfClass(<ClassLikeDeclaration>enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
errorNameNode = undefined;
}
function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
@@ -1136,7 +1129,7 @@ namespace ts {
return {
diagnosticMessage,
errorNode: node,
typeName: (<Declaration>node.parent.parent).name
typeName: getNameOfDeclaration(node.parent.parent)
};
}
}
@@ -1153,23 +1146,43 @@ namespace ts {
}
}
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
const baseTypeNode = getClassExtendsHeritageClauseElement(node);
let tempVarName: string;
if (baseTypeNode && !isEntityNameExpression(baseTypeNode.expression)) {
tempVarName = baseTypeNode.expression.kind === SyntaxKind.NullKeyword ?
"null" :
emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.text}_base`, {
diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
errorNode: baseTypeNode,
typeName: node.name
});
}
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (hasModifier(node, ModifierFlags.Abstract)) {
write("abstract ");
}
write("class ");
writeTextOfNode(currentText, node.name);
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
const baseTypeNode = getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
node.name;
emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false);
if (!isEntityNameExpression(baseTypeNode.expression)) {
write(" extends ");
write(tempVarName);
if (baseTypeNode.typeArguments) {
write("<");
emitCommaList(baseTypeNode.typeArguments, emitType);
write(">");
}
}
else {
emitHeritageClause([baseTypeNode], /*isImplementsList*/ false);
}
}
emitHeritageClause(node.name, getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true);
emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true);
write(" {");
writeLine();
increaseIndent();
@@ -1191,7 +1204,7 @@ namespace ts {
emitTypeParameters(node.typeParameters);
const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression));
if (interfaceExtendsTypes && interfaceExtendsTypes.length) {
emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false);
emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false);
}
write(" {");
writeLine();
@@ -1262,7 +1275,9 @@ namespace ts {
Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) {
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature ||
(node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (hasModifier(node, ModifierFlags.Static)) {
return symbolAccessibilityResult.errorModuleName ?
@@ -1271,7 +1286,7 @@ namespace ts {
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) {
else if (node.parent.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.Parameter) {
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 :
@@ -1505,6 +1520,11 @@ namespace ts {
write("[");
}
else {
if (node.kind === SyntaxKind.Constructor && hasModifier(node, ModifierFlags.Private)) {
write("();");
writeLine();
return;
}
// Construct signature or constructor type write new Signature
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
+12 -1
View File
@@ -1852,6 +1852,14 @@
"category": "Error",
"code": 2550
},
"Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?": {
"category": "Error",
"code": 2551
},
"Cannot find name '{0}'. Did you mean '{1}'?": {
"category": "Error",
"code": 2552
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -3556,7 +3564,10 @@
"category": "Message",
"code": 90021
},
"Change spelling to '{0}'.": {
"category": "Message",
"code": 90022
},
"Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": {
"category": "Error",
+414 -378
View File
@@ -214,248 +214,14 @@ namespace ts {
: node;
}
// Type Elements
export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
const signatureDeclaration = createSynthesizedNode(kind) as SignatureDeclaration;
signatureDeclaration.typeParameters = asNodeArray(typeParameters);
signatureDeclaration.parameters = asNodeArray(parameters);
signatureDeclaration.type = type;
return signatureDeclaration;
}
function updateSignatureDeclaration(node: SignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
: node;
}
export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode;
}
export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <FunctionTypeNode>updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode;
}
export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <ConstructorTypeNode>updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration;
}
export function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <CallSignatureDeclaration>updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration;
}
export function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <ConstructSignatureDeclaration>updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) {
const methodSignature = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature;
methodSignature.name = asName(name);
methodSignature.questionToken = questionToken;
return methodSignature;
}
export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) {
return node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
|| node.name !== name
|| node.questionToken !== questionToken
? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
: node;
}
// Types
export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) {
return <KeywordTypeNode>createSynthesizedNode(kind);
}
export function createThisTypeNode() {
return <ThisTypeNode>createSynthesizedNode(SyntaxKind.ThisType);
}
export function createLiteralTypeNode(literal: Expression) {
const literalTypeNode = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode;
literalTypeNode.literal = literal;
return literalTypeNode;
}
export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) {
return node.literal !== literal
? updateNode(createLiteralTypeNode(literal), node)
: node;
}
export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) {
const typeReference = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode;
typeReference.typeName = asName(typeName);
typeReference.typeArguments = asNodeArray(typeArguments);
return typeReference;
}
export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined) {
return node.typeName !== typeName
|| node.typeArguments !== typeArguments
? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
: node;
}
export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) {
const typePredicateNode = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode;
typePredicateNode.parameterName = asName(parameterName);
typePredicateNode.type = type;
return typePredicateNode;
}
export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) {
return node.parameterName !== parameterName
|| node.type !== type
? updateNode(createTypePredicateNode(parameterName, type), node)
: node;
}
export function createTypeQueryNode(exprName: EntityName) {
const typeQueryNode = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode;
typeQueryNode.exprName = exprName;
return typeQueryNode;
}
export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) {
return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node;
}
export function createArrayTypeNode(elementType: TypeNode) {
const arrayTypeNode = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode;
arrayTypeNode.elementType = elementType;
return arrayTypeNode;
}
export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode {
return node.elementType !== elementType
? updateNode(createArrayTypeNode(elementType), node)
: node;
}
export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode;
export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode;
export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode;
export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) {
const unionTypeNode = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode;
unionTypeNode.types = createNodeArray(types);
return unionTypeNode;
}
export function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray<TypeNode>) {
return node.types !== types
? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
: node;
}
export function createParenthesizedType(type: TypeNode) {
const node = <ParenthesizedTypeNode>createSynthesizedNode(SyntaxKind.ParenthesizedType);
node.type = type;
return node;
}
export function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) {
return node.type !== type
? updateNode(createParenthesizedType(type), node)
: node;
}
export function createTypeLiteralNode(members: TypeElement[]) {
const typeLiteralNode = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode;
typeLiteralNode.members = createNodeArray(members);
return typeLiteralNode;
}
export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>) {
return node.members !== members
? updateNode(createTypeLiteralNode(members), node)
: node;
}
export function createTupleTypeNode(elementTypes: TypeNode[]) {
const tupleTypeNode = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode;
tupleTypeNode.elementTypes = createNodeArray(elementTypes);
return tupleTypeNode;
}
export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) {
return node.elementTypes !== elementTypes
? updateNode(createTupleTypeNode(elementTypes), node)
: node;
}
export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode {
const mappedTypeNode = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode;
mappedTypeNode.readonlyToken = readonlyToken;
mappedTypeNode.typeParameter = typeParameter;
mappedTypeNode.questionToken = questionToken;
mappedTypeNode.type = type;
return mappedTypeNode;
}
export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode {
return node.readonlyToken !== readonlyToken
|| node.typeParameter !== typeParameter
|| node.questionToken !== questionToken
|| node.type !== type
? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
: node;
}
export function createTypeOperatorNode(type: TypeNode) {
const typeOperatorNode = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode;
typeOperatorNode.operator = SyntaxKind.KeyOfKeyword;
typeOperatorNode.type = type;
return typeOperatorNode;
}
export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) {
return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node;
}
export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) {
const indexedAccessTypeNode = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode;
indexedAccessTypeNode.objectType = objectType;
indexedAccessTypeNode.indexType = indexType;
return indexedAccessTypeNode;
}
export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) {
return node.objectType !== objectType
|| node.indexType !== indexType
? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
: node;
}
// Type Declarations
// Signature elements
export function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) {
const typeParameter = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration;
typeParameter.name = asName(name);
typeParameter.constraint = constraint;
typeParameter.default = defaultType;
return typeParameter;
const node = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration;
node.name = asName(name);
node.constraint = constraint;
node.default = defaultType;
return node;
}
export function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) {
@@ -466,46 +232,6 @@ namespace ts {
: node;
}
// Signature elements
export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature {
const propertySignature = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature;
propertySignature.name = asName(name);
propertySignature.questionToken = questionToken;
propertySignature.type = type;
propertySignature.initializer = initializer;
return propertySignature;
}
export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.name !== name
|| node.questionToken !== questionToken
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createPropertySignature(name, questionToken, type, initializer), node)
: node;
}
export function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration {
const indexSignature = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration;
indexSignature.decorators = asNodeArray(decorators);
indexSignature.modifiers = asNodeArray(modifiers);
indexSignature.parameters = createNodeArray(parameters);
indexSignature.type = type;
return indexSignature;
}
export function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) {
return node.parameters !== parameters
|| node.type !== type
|| node.decorators !== decorators
|| node.modifiers !== modifiers
? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node)
: node;
}
// Signature elements
export function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression) {
const node = <ParameterDeclaration>createSynthesizedNode(SyntaxKind.Parameter);
node.decorators = asNodeArray(decorators);
@@ -542,7 +268,26 @@ namespace ts {
: node;
}
// Type members
// Type Elements
export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature {
const node = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature;
node.name = asName(name);
node.questionToken = questionToken;
node.type = type;
node.initializer = initializer;
return node;
}
export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.name !== name
|| node.questionToken !== questionToken
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createPropertySignature(name, questionToken, type, initializer), node)
: node;
}
export function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression) {
const node = <PropertyDeclaration>createSynthesizedNode(SyntaxKind.PropertyDeclaration);
@@ -565,7 +310,24 @@ namespace ts {
: node;
}
export function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) {
const node = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature;
node.name = asName(name);
node.questionToken = questionToken;
return node;
}
export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) {
return node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
|| node.name !== name
|| node.questionToken !== questionToken
? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
: node;
}
export function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
const node = <MethodDeclaration>createSynthesizedNode(SyntaxKind.MethodDeclaration);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
@@ -588,7 +350,7 @@ namespace ts {
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
: node;
}
@@ -656,6 +418,254 @@ namespace ts {
: node;
}
export function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration;
}
export function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration;
}
export function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration {
const node = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration;
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.parameters = createNodeArray(parameters);
node.type = type;
return node;
}
export function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) {
return node.parameters !== parameters
|| node.type !== type
|| node.decorators !== decorators
|| node.modifiers !== modifiers
? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
: node;
}
/* @internal */
export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
const node = createSynthesizedNode(kind) as SignatureDeclaration;
node.typeParameters = asNodeArray(typeParameters);
node.parameters = asNodeArray(parameters);
node.type = type;
return node;
}
function updateSignatureDeclaration<T extends SignatureDeclaration>(node: T, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): T {
return node.typeParameters !== typeParameters
|| node.parameters !== parameters
|| node.type !== type
? updateNode(<T>createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
: node;
}
// Types
export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) {
return <KeywordTypeNode>createSynthesizedNode(kind);
}
export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode;
node.parameterName = asName(parameterName);
node.type = type;
return node;
}
export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) {
return node.parameterName !== parameterName
|| node.type !== type
? updateNode(createTypePredicateNode(parameterName, type), node)
: node;
}
export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) {
const node = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode;
node.typeName = asName(typeName);
node.typeArguments = asNodeArray(typeArguments);
return node;
}
export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined) {
return node.typeName !== typeName
|| node.typeArguments !== typeArguments
? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
: node;
}
export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode;
}
export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <FunctionTypeNode>updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode;
}
export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined) {
return <ConstructorTypeNode>updateSignatureDeclaration(node, typeParameters, parameters, type);
}
export function createTypeQueryNode(exprName: EntityName) {
const node = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode;
node.exprName = exprName;
return node;
}
export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) {
return node.exprName !== exprName
? updateNode(createTypeQueryNode(exprName), node)
: node;
}
export function createTypeLiteralNode(members: TypeElement[]) {
const node = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode;
node.members = createNodeArray(members);
return node;
}
export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>) {
return node.members !== members
? updateNode(createTypeLiteralNode(members), node)
: node;
}
export function createArrayTypeNode(elementType: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode;
node.elementType = elementType;
return node;
}
export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode {
return node.elementType !== elementType
? updateNode(createArrayTypeNode(elementType), node)
: node;
}
export function createTupleTypeNode(elementTypes: TypeNode[]) {
const node = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode;
node.elementTypes = createNodeArray(elementTypes);
return node;
}
export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) {
return node.elementTypes !== elementTypes
? updateNode(createTupleTypeNode(elementTypes), node)
: node;
}
export function createUnionTypeNode(types: TypeNode[]): UnionTypeNode {
return <UnionTypeNode>createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types);
}
export function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray<TypeNode>) {
return updateUnionOrIntersectionTypeNode(node, types);
}
export function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode {
return <IntersectionTypeNode>createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types);
}
export function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray<TypeNode>) {
return updateUnionOrIntersectionTypeNode(node, types);
}
export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) {
const node = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode;
node.types = createNodeArray(types);
return node;
}
function updateUnionOrIntersectionTypeNode<T extends UnionOrIntersectionTypeNode>(node: T, types: NodeArray<TypeNode>): T {
return node.types !== types
? updateNode(<T>createUnionOrIntersectionTypeNode(node.kind, types), node)
: node;
}
export function createParenthesizedType(type: TypeNode) {
const node = <ParenthesizedTypeNode>createSynthesizedNode(SyntaxKind.ParenthesizedType);
node.type = type;
return node;
}
export function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) {
return node.type !== type
? updateNode(createParenthesizedType(type), node)
: node;
}
export function createThisTypeNode() {
return <ThisTypeNode>createSynthesizedNode(SyntaxKind.ThisType);
}
export function createTypeOperatorNode(type: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode;
node.operator = SyntaxKind.KeyOfKeyword;
node.type = type;
return node;
}
export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) {
return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node;
}
export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode;
node.objectType = objectType;
node.indexType = indexType;
return node;
}
export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) {
return node.objectType !== objectType
|| node.indexType !== indexType
? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
: node;
}
export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode {
const node = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode;
node.readonlyToken = readonlyToken;
node.typeParameter = typeParameter;
node.questionToken = questionToken;
node.type = type;
return node;
}
export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode {
return node.readonlyToken !== readonlyToken
|| node.typeParameter !== typeParameter
|| node.questionToken !== questionToken
|| node.type !== type
? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
: node;
}
export function createLiteralTypeNode(literal: Expression) {
const node = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode;
node.literal = literal;
return node;
}
export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) {
return node.literal !== literal
? updateNode(createLiteralTypeNode(literal), node)
: node;
}
// Binding Patterns
export function createObjectBindingPattern(elements: BindingElement[]) {
@@ -705,10 +715,7 @@ namespace ts {
export function createArrayLiteral(elements?: Expression[], multiLine?: boolean) {
const node = <ArrayLiteralExpression>createSynthesizedNode(SyntaxKind.ArrayLiteralExpression);
node.elements = parenthesizeListElements(createNodeArray(elements));
if (multiLine) {
node.multiLine = true;
}
if (multiLine) node.multiLine = true;
return node;
}
@@ -721,9 +728,7 @@ namespace ts {
export function createObjectLiteral(properties?: ObjectLiteralElementLike[], multiLine?: boolean) {
const node = <ObjectLiteralExpression>createSynthesizedNode(SyntaxKind.ObjectLiteralExpression);
node.properties = createNodeArray(properties);
if (multiLine) {
node.multiLine = true;
}
if (multiLine) node.multiLine = true;
return node;
}
@@ -773,9 +778,9 @@ namespace ts {
}
export function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]) {
return expression !== node.expression
|| typeArguments !== node.typeArguments
|| argumentsArray !== node.arguments
return node.expression !== expression
|| node.typeArguments !== typeArguments
|| node.arguments !== argumentsArray
? updateNode(createCall(expression, typeArguments, argumentsArray), node)
: node;
}
@@ -1099,6 +1104,19 @@ namespace ts {
: node;
}
export function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier) {
const node = <MetaProperty>createSynthesizedNode(SyntaxKind.MetaProperty);
node.keywordToken = keywordToken;
node.name = name;
return node;
}
export function updateMetaProperty(node: MetaProperty, name: Identifier) {
return node.name !== name
? updateNode(createMetaProperty(node.keywordToken, name), node)
: node;
}
// Misc
export function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail) {
@@ -1115,6 +1133,10 @@ namespace ts {
: node;
}
export function createSemicolonClassElement() {
return <SemicolonClassElement>createSynthesizedNode(SyntaxKind.SemicolonClassElement);
}
// Element
export function createBlock(statements: Statement[], multiLine?: boolean): Block {
@@ -1125,7 +1147,7 @@ namespace ts {
}
export function updateBlock(node: Block, statements: Statement[]) {
return statements !== node.statements
return node.statements !== statements
? updateNode(createBlock(statements, node.multiLine), node)
: node;
}
@@ -1145,35 +1167,6 @@ namespace ts {
: node;
}
export function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags) {
const node = <VariableDeclarationList>createSynthesizedNode(SyntaxKind.VariableDeclarationList);
node.flags |= flags;
node.declarations = createNodeArray(declarations);
return node;
}
export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]) {
return node.declarations !== declarations
? updateNode(createVariableDeclarationList(declarations, node.flags), node)
: node;
}
export function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression) {
const node = <VariableDeclaration>createSynthesizedNode(SyntaxKind.VariableDeclaration);
node.name = asName(name);
node.type = type;
node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined;
return node;
}
export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.name !== name
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createVariableDeclaration(name, type, initializer), node)
: node;
}
export function createEmptyStatement() {
return <EmptyStatement>createSynthesizedNode(SyntaxKind.EmptyStatement);
}
@@ -1392,6 +1385,39 @@ namespace ts {
: node;
}
export function createDebuggerStatement() {
return <DebuggerStatement>createSynthesizedNode(SyntaxKind.DebuggerStatement);
}
export function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression) {
const node = <VariableDeclaration>createSynthesizedNode(SyntaxKind.VariableDeclaration);
node.name = asName(name);
node.type = type;
node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined;
return node;
}
export function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.name !== name
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createVariableDeclaration(name, type, initializer), node)
: node;
}
export function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags) {
const node = <VariableDeclarationList>createSynthesizedNode(SyntaxKind.VariableDeclarationList);
node.flags |= flags & NodeFlags.BlockScoped;
node.declarations = createNodeArray(declarations);
return node;
}
export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]) {
return node.declarations !== declarations
? updateNode(createVariableDeclarationList(declarations, node.flags), node)
: node;
}
export function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
const node = <FunctionDeclaration>createSynthesizedNode(SyntaxKind.FunctionDeclaration);
node.decorators = asNodeArray(decorators);
@@ -1498,7 +1524,7 @@ namespace ts {
export function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags) {
const node = <ModuleDeclaration>createSynthesizedNode(SyntaxKind.ModuleDeclaration);
node.flags |= flags;
node.flags |= flags & (NodeFlags.Namespace | NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = name;
@@ -1539,6 +1565,18 @@ namespace ts {
: node;
}
export function createNamespaceExportDeclaration(name: string | Identifier) {
const node = <NamespaceExportDeclaration>createSynthesizedNode(SyntaxKind.NamespaceExportDeclaration);
node.name = asName(name);
return node;
}
export function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier) {
return node.name !== name
? updateNode(createNamespaceExportDeclaration(name), node)
: node;
}
export function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference) {
const node = <ImportEqualsDeclaration>createSynthesizedNode(SyntaxKind.ImportEqualsDeclaration);
node.decorators = asNodeArray(decorators);
@@ -1569,7 +1607,8 @@ namespace ts {
export function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier
|| node.importClause !== importClause
|| node.moduleSpecifier !== moduleSpecifier
? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
: node;
}
@@ -1759,19 +1798,6 @@ namespace ts {
: node;
}
export function createJsxAttributes(properties: JsxAttributeLike[]) {
const jsxAttributes = <JsxAttributes>createSynthesizedNode(SyntaxKind.JsxAttributes);
jsxAttributes.properties = createNodeArray(properties);
return jsxAttributes;
}
export function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]) {
if (jsxAttributes.properties !== properties) {
return updateNode(createJsxAttributes(properties), jsxAttributes);
}
return jsxAttributes;
}
export function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression) {
const node = <JsxAttribute>createSynthesizedNode(SyntaxKind.JsxAttribute);
node.name = name;
@@ -1786,6 +1812,18 @@ namespace ts {
: node;
}
export function createJsxAttributes(properties: JsxAttributeLike[]) {
const node = <JsxAttributes>createSynthesizedNode(SyntaxKind.JsxAttributes);
node.properties = createNodeArray(properties);
return node;
}
export function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]) {
return node.properties !== properties
? updateNode(createJsxAttributes(properties), node)
: node;
}
export function createJsxSpreadAttribute(expression: Expression) {
const node = <JsxSpreadAttribute>createSynthesizedNode(SyntaxKind.JsxSpreadAttribute);
node.expression = expression;
@@ -1813,20 +1851,6 @@ namespace ts {
// Clauses
export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) {
const node = <HeritageClause>createSynthesizedNode(SyntaxKind.HeritageClause);
node.token = token;
node.types = createNodeArray(types);
return node;
}
export function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]) {
if (node.types !== types) {
return updateNode(createHeritageClause(node.token, types), node);
}
return node;
}
export function createCaseClause(expression: Expression, statements: Statement[]) {
const node = <CaseClause>createSynthesizedNode(SyntaxKind.CaseClause);
node.expression = parenthesizeExpressionForList(expression);
@@ -1835,10 +1859,10 @@ namespace ts {
}
export function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]) {
if (node.expression !== expression || node.statements !== statements) {
return updateNode(createCaseClause(expression, statements), node);
}
return node;
return node.expression !== expression
|| node.statements !== statements
? updateNode(createCaseClause(expression, statements), node)
: node;
}
export function createDefaultClause(statements: Statement[]) {
@@ -1848,12 +1872,24 @@ namespace ts {
}
export function updateDefaultClause(node: DefaultClause, statements: Statement[]) {
if (node.statements !== statements) {
return updateNode(createDefaultClause(statements), node);
}
return node.statements !== statements
? updateNode(createDefaultClause(statements), node)
: node;
}
export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) {
const node = <HeritageClause>createSynthesizedNode(SyntaxKind.HeritageClause);
node.token = token;
node.types = createNodeArray(types);
return node;
}
export function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]) {
return node.types !== types
? updateNode(createHeritageClause(node.token, types), node)
: node;
}
export function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block) {
const node = <CatchClause>createSynthesizedNode(SyntaxKind.CatchClause);
node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
@@ -1862,10 +1898,10 @@ namespace ts {
}
export function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block) {
if (node.variableDeclaration !== variableDeclaration || node.block !== block) {
return updateNode(createCatchClause(variableDeclaration, block), node);
}
return node;
return node.variableDeclaration !== variableDeclaration
|| node.block !== block
? updateNode(createCatchClause(variableDeclaration, block), node)
: node;
}
// Property assignments
@@ -1879,10 +1915,10 @@ namespace ts {
}
export function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression) {
if (node.name !== name || node.initializer !== initializer) {
return updateNode(createPropertyAssignment(name, initializer), node);
}
return node;
return node.name !== name
|| node.initializer !== initializer
? updateNode(createPropertyAssignment(name, initializer), node)
: node;
}
export function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression) {
@@ -1893,10 +1929,10 @@ namespace ts {
}
export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined) {
if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) {
return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node);
}
return node;
return node.name !== name
|| node.objectAssignmentInitializer !== objectAssignmentInitializer
? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
: node;
}
export function createSpreadAssignment(expression: Expression) {
@@ -1906,10 +1942,9 @@ namespace ts {
}
export function updateSpreadAssignment(node: SpreadAssignment, expression: Expression) {
if (node.expression !== expression) {
return updateNode(createSpreadAssignment(expression), node);
}
return node;
return node.expression !== expression
? updateNode(createSpreadAssignment(expression), node)
: node;
}
// Enum
@@ -3064,9 +3099,10 @@ namespace ts {
}
function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) {
if (node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name)) {
const name = getMutableClone(node.name);
emitFlags |= getEmitFlags(node.name);
const nodeName = getNameOfDeclaration(node);
if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) {
const name = getMutableClone(nodeName);
emitFlags |= getEmitFlags(nodeName);
if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap;
if (!allowComments) emitFlags |= EmitFlags.NoComments;
if (emitFlags) setEmitFlags(name, emitFlags);
+17 -4
View File
@@ -2,7 +2,6 @@
/// <reference path="diagnosticInformationMap.generated.ts" />
namespace ts {
/* @internal */
export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
export function trace(host: ModuleResolutionHost): void {
@@ -15,6 +14,7 @@ namespace ts {
}
/** Array that is only intended to be pushed to, never read. */
/* @internal */
export interface Push<T> {
push(value: T): void;
}
@@ -675,12 +675,25 @@ namespace ts {
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations {
return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false);
return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false);
}
/**
* Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
* No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
* Throws an error if the module can't be resolved.
*/
/* @internal */
export function nodeModuleNameResolverWorker(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, jsOnly = false): ResolvedModuleWithFailedLookupLocations {
const containingDirectory = getDirectoryPath(containingFile);
export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string {
const { resolvedModule, failedLookupLocations } =
nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true);
if (!resolvedModule) {
throw new Error(`Could not resolve JS module ${moduleName} starting at ${initialDir}. Looked in: ${failedLookupLocations.join(", ")}`);
}
return resolvedModule.resolvedFileName;
}
function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
const failedLookupLocations: string[] = [];
+2
View File
@@ -6517,6 +6517,8 @@ namespace ts {
case "augments":
tag = parseAugmentsTag(atToken, tagName);
break;
case "arg":
case "argument":
case "param":
tag = parseParamTag(atToken, tagName);
break;
+4 -3
View File
@@ -2009,13 +2009,14 @@ namespace ts {
}
else {
assignment = createBinary(<Identifier>decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression));
setTextRange(assignment, decl);
}
assignments = append(assignments, assignment);
}
}
if (assignments) {
updated = setTextRange(createStatement(reduceLeft(assignments, (acc, v) => createBinary(v, SyntaxKind.CommaToken, acc))), node);
updated = setTextRange(createStatement(inlineExpressions(assignments)), node);
}
else {
// none of declarations has initializer - the entire variable statement can be deleted
@@ -3748,7 +3749,7 @@ namespace ts {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.VariableDeclaration:
return (<Declaration>parent).name === node
return (<NamedDeclaration>parent).name === node
&& resolver.isDeclarationWithCollidingName(<Declaration>parent);
}
@@ -3781,7 +3782,7 @@ namespace ts {
if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings && !isInternalName(node)) {
const declaration = resolver.getReferencedDeclarationWithCollidingName(node);
if (declaration && !(isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
return setTextRange(getGeneratedNameForNode(declaration.name), node);
return setTextRange(getGeneratedNameForNode(getNameOfDeclaration(declaration)), node);
}
}
+64 -58
View File
@@ -106,15 +106,11 @@ namespace ts {
}
}
function visitAwaitExpression(node: AwaitExpression) {
function visitAwaitExpression(node: AwaitExpression): Expression {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
const expression = visitNode(node.expression, visitor, isExpression);
return setOriginalNode(
setTextRange(
createYield(
/*asteriskToken*/ undefined,
createArrayLiteral([createLiteral("await"), expression])
),
createYield(createAwaitHelper(context, visitNode(node.expression, visitor, isExpression))),
/*location*/ node
),
node
@@ -124,18 +120,26 @@ namespace ts {
}
function visitYieldExpression(node: YieldExpression) {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator && node.asteriskToken) {
const expression = visitNode(node.expression, visitor, isExpression);
return updateYield(
node,
node.asteriskToken,
node.asteriskToken
? createAsyncDelegatorHelper(context, expression, expression)
: createArrayLiteral(
expression
? [createLiteral("yield"), expression]
: [createLiteral("yield")]
)
return setOriginalNode(
setTextRange(
createYield(
createAwaitHelper(context,
updateYield(
node,
node.asteriskToken,
createAsyncDelegatorHelper(
context,
createAsyncValuesHelper(context, expression, expression),
expression
)
)
)
),
node
),
node
);
}
return visitEachChild(node, visitor, context);
@@ -347,6 +351,10 @@ namespace ts {
);
}
function awaitAsYield(expression: Expression) {
return createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & FunctionFlags.Generator ? createAwaitHelper(context, expression) : expression);
}
function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement) {
const expression = visitNode(node.expression, visitor, isExpression);
const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined);
@@ -354,16 +362,11 @@ namespace ts {
const errorRecord = createUniqueName("e");
const catchVariable = getGeneratedNameForNode(errorRecord);
const returnMethod = createTempVariable(/*recordTempVariable*/ undefined);
const values = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
const next = createYield(
/*asteriskToken*/ undefined,
enclosingFunctionFlags & FunctionFlags.Generator
? createArrayLiteral([
createLiteral("await"),
createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, [])
])
: createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, [])
);
const callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
const callNext = createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []);
const getDone = createPropertyAccess(result, "done");
const getValue = createPropertyAccess(result, "value");
const callReturn = createFunctionCall(returnMethod, iterator, []);
hoistVariableDeclaration(errorRecord);
hoistVariableDeclaration(returnMethod);
@@ -374,16 +377,19 @@ namespace ts {
/*initializer*/ setEmitFlags(
setTextRange(
createVariableDeclarationList([
setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression),
createVariableDeclaration(result, /*type*/ undefined, next)
setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression),
createVariableDeclaration(result)
]),
node.expression
),
EmitFlags.NoHoisting
),
/*condition*/ createLogicalNot(createPropertyAccess(result, "done")),
/*incrementor*/ createAssignment(result, next),
/*statement*/ convertForOfStatementHead(node, createPropertyAccess(result, "value"))
/*condition*/ createComma(
createAssignment(result, awaitAsYield(callNext)),
createLogicalNot(getDone)
),
/*incrementor*/ undefined,
/*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))
),
/*location*/ node
),
@@ -421,26 +427,14 @@ namespace ts {
createLogicalAnd(
createLogicalAnd(
result,
createLogicalNot(
createPropertyAccess(result, "done")
)
createLogicalNot(getDone)
),
createAssignment(
returnMethod,
createPropertyAccess(iterator, "return")
)
),
createStatement(
createYield(
/*asteriskToken*/ undefined,
enclosingFunctionFlags & FunctionFlags.Generator
? createArrayLiteral([
createLiteral("await"),
createFunctionCall(returnMethod, iterator, [])
])
: createFunctionCall(returnMethod, iterator, [])
)
)
createStatement(awaitAsYield(callReturn))
),
EmitFlags.SingleLine
)
@@ -880,27 +874,39 @@ namespace ts {
);
}
const awaitHelper: EmitHelper = {
name: "typescript:await",
scoped: false,
text: `
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
`
};
function createAwaitHelper(context: TransformationContext, expression: Expression) {
context.requestEmitHelper(awaitHelper);
return createCall(getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
const asyncGeneratorHelper: EmitHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: `
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), q = [], c, i;
return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }
function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }
function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); }
function send(value) { settle(c[2], { value: value, done: false }); }
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { c = void 0, f(v), next(); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
`
};
function createAsyncGeneratorHelper(context: TransformationContext, generatorFunc: FunctionExpression) {
context.requestEmitHelper(awaitHelper);
context.requestEmitHelper(asyncGeneratorHelper);
// Mark this node as originally an async function
@@ -922,16 +928,16 @@ namespace ts {
scoped: false,
text: `
var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p;
return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }
var i, p;
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; }
};
`
};
function createAsyncDelegatorHelper(context: TransformationContext, expression: Expression, location?: TextRange) {
context.requestEmitHelper(awaitHelper);
context.requestEmitHelper(asyncDelegator);
context.requestEmitHelper(asyncValues);
return setTextRange(
createCall(
getHelperName("__asyncDelegator"),
+4 -8
View File
@@ -1762,23 +1762,19 @@ namespace ts {
}
function serializeUnionOrIntersectionType(node: UnionOrIntersectionTypeNode): SerializedTypeNode {
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
let serializedUnion: SerializedTypeNode;
for (const typeNode of node.types) {
const serializedIndividual = serializeTypeNode(typeNode);
if (isVoidExpression(serializedIndividual)) {
// If we dont have any other type already set, set the initial type
if (!serializedUnion) {
serializedUnion = serializedIndividual;
}
}
else if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") {
if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") {
// One of the individual is global object, return immediately
return serializedIndividual;
}
// If there exists union that is not void 0 expression, check if the the common type is identifier.
// anything more complex and we will just default to Object
else if (serializedUnion && !isVoidExpression(serializedUnion)) {
else if (serializedUnion) {
// Different types
if (!isIdentifier(serializedUnion) ||
!isIdentifier(serializedIndividual) ||
+38 -27
View File
@@ -606,10 +606,13 @@ namespace ts {
export interface Declaration extends Node {
_declarationBrand: any;
}
export interface NamedDeclaration extends Declaration {
name?: DeclarationName;
}
export interface DeclarationStatement extends Declaration, Statement {
export interface DeclarationStatement extends NamedDeclaration, Statement {
name?: Identifier | StringLiteral | NumericLiteral;
}
@@ -623,7 +626,7 @@ namespace ts {
expression: LeftHandSideExpression;
}
export interface TypeParameterDeclaration extends Declaration {
export interface TypeParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.TypeParameter;
parent?: DeclarationWithTypeParameters;
name: Identifier;
@@ -634,7 +637,7 @@ namespace ts {
expression?: Expression;
}
export interface SignatureDeclaration extends Declaration {
export interface SignatureDeclaration extends NamedDeclaration {
name?: PropertyName;
typeParameters?: NodeArray<TypeParameterDeclaration>;
parameters: NodeArray<ParameterDeclaration>;
@@ -651,7 +654,7 @@ namespace ts {
export type BindingName = Identifier | BindingPattern;
export interface VariableDeclaration extends Declaration {
export interface VariableDeclaration extends NamedDeclaration {
kind: SyntaxKind.VariableDeclaration;
parent?: VariableDeclarationList | CatchClause;
name: BindingName; // Declared variable name
@@ -665,7 +668,7 @@ namespace ts {
declarations: NodeArray<VariableDeclaration>;
}
export interface ParameterDeclaration extends Declaration {
export interface ParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.Parameter;
parent?: SignatureDeclaration;
dotDotDotToken?: DotDotDotToken; // Present on rest parameter
@@ -675,7 +678,7 @@ namespace ts {
initializer?: Expression; // Optional initializer
}
export interface BindingElement extends Declaration {
export interface BindingElement extends NamedDeclaration {
kind: SyntaxKind.BindingElement;
parent?: BindingPattern;
propertyName?: PropertyName; // Binding property name (in object binding pattern)
@@ -700,7 +703,7 @@ namespace ts {
initializer?: Expression; // Optional initializer
}
export interface ObjectLiteralElement extends Declaration {
export interface ObjectLiteralElement extends NamedDeclaration {
_objectLiteralBrandBrand: any;
name?: PropertyName;
}
@@ -744,7 +747,7 @@ namespace ts {
// SyntaxKind.ShorthandPropertyAssignment
// SyntaxKind.EnumMember
// SyntaxKind.JSDocPropertyTag
export interface VariableLikeDeclaration extends Declaration {
export interface VariableLikeDeclaration extends NamedDeclaration {
propertyName?: PropertyName;
dotDotDotToken?: DotDotDotToken;
name: DeclarationName;
@@ -753,7 +756,7 @@ namespace ts {
initializer?: Expression;
}
export interface PropertyLikeDeclaration extends Declaration {
export interface PropertyLikeDeclaration extends NamedDeclaration {
name: PropertyName;
}
@@ -1221,8 +1224,7 @@ namespace ts {
export type BinaryOperatorToken = Token<BinaryOperator>;
// Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files
export interface BinaryExpression extends Expression, Declaration {
export interface BinaryExpression extends Expression, Declaration {
kind: SyntaxKind.BinaryExpression;
left: Expression;
operatorToken: BinaryOperatorToken;
@@ -1422,7 +1424,7 @@ namespace ts {
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression;
export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
export interface PropertyAccessExpression extends MemberExpression, Declaration {
export interface PropertyAccessExpression extends MemberExpression, NamedDeclaration {
kind: SyntaxKind.PropertyAccessExpression;
expression: LeftHandSideExpression;
name: Identifier;
@@ -1511,7 +1513,7 @@ namespace ts {
// for the same reasons we treat NewExpression as a PrimaryExpression.
export interface MetaProperty extends PrimaryExpression {
kind: SyntaxKind.MetaProperty;
keywordToken: SyntaxKind;
keywordToken: SyntaxKind.NewKeyword;
name: Identifier;
}
@@ -1767,7 +1769,7 @@ namespace ts {
export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
export interface ClassLikeDeclaration extends Declaration {
export interface ClassLikeDeclaration extends NamedDeclaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
@@ -1783,12 +1785,12 @@ namespace ts {
kind: SyntaxKind.ClassExpression;
}
export interface ClassElement extends Declaration {
export interface ClassElement extends NamedDeclaration {
_classElementBrand: any;
name?: PropertyName;
}
export interface TypeElement extends Declaration {
export interface TypeElement extends NamedDeclaration {
_typeElementBrand: any;
name?: PropertyName;
questionToken?: QuestionToken;
@@ -1816,7 +1818,7 @@ namespace ts {
type: TypeNode;
}
export interface EnumMember extends Declaration {
export interface EnumMember extends NamedDeclaration {
kind: SyntaxKind.EnumMember;
parent?: EnumDeclaration;
// This does include ComputedPropertyName, but the parser will give an error
@@ -1905,14 +1907,14 @@ namespace ts {
// import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns }
// import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]}
// import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]}
export interface ImportClause extends Declaration {
export interface ImportClause extends NamedDeclaration {
kind: SyntaxKind.ImportClause;
parent?: ImportDeclaration;
name?: Identifier; // Default binding
namedBindings?: NamedImportBindings;
}
export interface NamespaceImport extends Declaration {
export interface NamespaceImport extends NamedDeclaration {
kind: SyntaxKind.NamespaceImport;
parent?: ImportClause;
name: Identifier;
@@ -1945,14 +1947,14 @@ namespace ts {
export type NamedImportsOrExports = NamedImports | NamedExports;
export interface ImportSpecifier extends Declaration {
export interface ImportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ImportSpecifier;
parent?: NamedImports;
propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
name: Identifier; // Declared name
}
export interface ExportSpecifier extends Declaration {
export interface ExportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ExportSpecifier;
parent?: NamedExports;
propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
@@ -2118,7 +2120,7 @@ namespace ts {
typeExpression: JSDocTypeExpression;
}
export interface JSDocTypedefTag extends JSDocTag, Declaration {
export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
@@ -2557,6 +2559,9 @@ namespace ts {
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string;
/* @internal */ getBaseConstraintOfType(type: Type): Type;
/* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol;
@@ -2740,7 +2745,6 @@ 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;
writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
@@ -4001,11 +4005,12 @@ namespace ts {
Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation)
Generator = 1 << 7, // __generator (used by ES2015 generator transformation)
Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations)
Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation)
Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation)
Spread = 1 << 10, // __spread (used by ES2015 array spread and argument list spread transformations)
AsyncGenerator = 1 << 11, // __asyncGenerator (used by ES2017 async generator transformation)
AsyncDelegator = 1 << 12, // __asyncDelegator (used by ES2017 async generator yield* transformation)
AsyncValues = 1 << 13, // __asyncValues (used by ES2017 for..await..of transformation)
Await = 1 << 11, // __await (used by ES2017 async generator transformation)
AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation)
AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation)
AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation)
// Helpers included by ES2015 for..of
ForOfIncludes = Values,
@@ -4013,6 +4018,12 @@ namespace ts {
// Helpers included by ES2017 for..await..of
ForAwaitOfIncludes = AsyncValues,
// Helpers included by ES2017 async generators
AsyncGeneratorIncludes = Await | AsyncGenerator,
// Helpers included by yield* in ES2017 async generators
AsyncDelegatorIncludes = Await | AsyncDelegator | AsyncValues,
// Helpers included by ES2015 spread
SpreadIncludes = Read | Spread,
+86 -19
View File
@@ -566,7 +566,7 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeAliasDeclaration:
errorNode = (<Declaration>node).name;
errorNode = (<NamedDeclaration>node).name;
break;
case SyntaxKind.ArrowFunction:
return getErrorSpanForArrowFunction(sourceFile, <ArrowFunction>node);
@@ -1154,6 +1154,10 @@ namespace ts {
}
}
export function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression {
return node.kind === SyntaxKind.CallExpression || node.kind === SyntaxKind.NewExpression;
}
export function getInvokedExpression(node: CallLikeExpression): Expression {
if (node.kind === SyntaxKind.TaggedTemplateExpression) {
return (<TaggedTemplateExpression>node).tag;
@@ -1778,12 +1782,42 @@ namespace ts {
}
if (isDeclaration(parent)) {
return (<Declaration>parent).name === name;
return parent.name === name;
}
return false;
}
export function getNameOfDeclaration(declaration: Declaration): DeclarationName {
if (!declaration) {
return undefined;
}
if (declaration.kind === SyntaxKind.BinaryExpression) {
const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression);
const lhs = (declaration as BinaryExpression).left;
switch (kind) {
case SpecialPropertyAssignmentKind.None:
case SpecialPropertyAssignmentKind.ModuleExports:
return undefined;
case SpecialPropertyAssignmentKind.ExportsProperty:
if (lhs.kind === SyntaxKind.Identifier) {
return (lhs as PropertyAccessExpression).name;
}
else {
return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name;
}
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
return (lhs as PropertyAccessExpression).name;
case SpecialPropertyAssignmentKind.PrototypeProperty:
return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name;
}
}
else {
return (declaration as NamedDeclaration).name;
}
}
export function isLiteralComputedPropertyDeclarationName(node: Node) {
return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) &&
node.parent.kind === SyntaxKind.ComputedPropertyName &&
@@ -1804,7 +1838,7 @@ namespace ts {
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyAccessExpression:
// Name in member declaration or property name in property access
return (<Declaration | PropertyAccessExpression>parent).name === node;
return (<NamedDeclaration | PropertyAccessExpression>parent).name === node;
case SyntaxKind.QualifiedName:
// Name on right hand side of dot in a type query
if ((<QualifiedName>parent).right === node) {
@@ -1936,16 +1970,18 @@ namespace ts {
}
export const enum FunctionFlags {
Normal = 0,
Generator = 1 << 0,
Async = 1 << 1,
AsyncOrAsyncGenerator = Async | Generator,
Invalid = 1 << 2,
InvalidAsyncOrAsyncGenerator = AsyncOrAsyncGenerator | Invalid,
InvalidGenerator = Generator | Invalid,
Normal = 0, // Function is a normal function
Generator = 1 << 0, // Function is a generator function or async generator function
Async = 1 << 1, // Function is an async function or an async generator function
Invalid = 1 << 2, // Function is a signature or overload and does not have a body.
AsyncGenerator = Async | Generator, // Function is an async generator function
}
export function getFunctionFlags(node: FunctionLikeDeclaration) {
export function getFunctionFlags(node: FunctionLikeDeclaration | undefined) {
if (!node) {
return FunctionFlags.Invalid;
}
let flags = FunctionFlags.Normal;
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
@@ -2000,7 +2036,8 @@ namespace ts {
* Symbol.
*/
export function hasDynamicName(declaration: Declaration): boolean {
return declaration.name && isDynamicName(declaration.name);
const name = getNameOfDeclaration(declaration);
return name && isDynamicName(name);
}
export function isDynamicName(name: DeclarationName): boolean {
@@ -2765,7 +2802,7 @@ namespace ts {
forEach(declarations, (member: Declaration) => {
if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor)
&& hasModifier(member, ModifierFlags.Static) === hasModifier(accessor, ModifierFlags.Static)) {
const memberName = getPropertyNameForPropertyNameNode(member.name);
const memberName = getPropertyNameForPropertyNameNode((member as NamedDeclaration).name);
const accessorName = getPropertyNameForPropertyNameNode(accessor.name);
if (memberName === accessorName) {
if (!firstAccessor) {
@@ -3580,10 +3617,6 @@ namespace ts {
return node.kind === SyntaxKind.Identifier;
}
export function isVoidExpression(node: Node): node is VoidExpression {
return node.kind === SyntaxKind.VoidExpression;
}
export function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier {
// Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`.
return isIdentifier(node) && node.autoGenerateKind > GeneratedIdentifierKind.None;
@@ -3660,7 +3693,18 @@ namespace ts {
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor
|| kind === SyntaxKind.IndexSignature
|| kind === SyntaxKind.SemicolonClassElement;
|| kind === SyntaxKind.SemicolonClassElement
|| kind === SyntaxKind.MissingDeclaration;
}
export function isTypeElement(node: Node): node is TypeElement {
const kind = node.kind;
return kind === SyntaxKind.ConstructSignature
|| kind === SyntaxKind.CallSignature
|| kind === SyntaxKind.PropertySignature
|| kind === SyntaxKind.MethodSignature
|| kind === SyntaxKind.IndexSignature
|| kind === SyntaxKind.MissingDeclaration;
}
export function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike {
@@ -4081,7 +4125,7 @@ namespace ts {
|| kind === SyntaxKind.MergeDeclarationMarker;
}
export function isDeclaration(node: Node): node is Declaration {
export function isDeclaration(node: Node): node is NamedDeclaration {
return isDeclarationKind(node.kind);
}
@@ -4640,4 +4684,27 @@ namespace ts {
export function unescapeIdentifier(identifier: string): string {
return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier;
}
export function levenshtein(s1: string, s2: string): number {
let previous: number[] = new Array(s2.length + 1);
let current: number[] = new Array(s2.length + 1);
for (let i = 0; i < s2.length + 1; i++) {
previous[i] = i;
current[i] = -1;
}
for (let i = 1; i < s1.length + 1; i++) {
current[0] = i;
for (let j = 1; j < s2.length + 1; j++) {
current[j] = Math.min(
previous[j] + 1,
current[j - 1] + 1,
previous[j - 1] + (s1[i - 1] === s2[j - 1] ? 0 : 2));
}
// shift current back to previous, and then reuse previous' array
const tmp = previous;
previous = current;
current = tmp;
}
return previous[previous.length - 1];
}
}
+149 -118
View File
@@ -218,16 +218,7 @@ namespace ts {
return node;
}
switch (node.kind) {
case SyntaxKind.SemicolonClassElement:
case SyntaxKind.EmptyStatement:
case SyntaxKind.OmittedExpression:
case SyntaxKind.DebuggerStatement:
case SyntaxKind.EndOfDeclarationMarker:
case SyntaxKind.MissingDeclaration:
// No need to visit nodes with no children.
return node;
switch (kind) {
// Names
case SyntaxKind.QualifiedName:
return updateQualifiedName(<QualifiedName>node,
@@ -238,45 +229,13 @@ namespace ts {
return updateComputedPropertyName(<ComputedPropertyName>node,
visitNode((<ComputedPropertyName>node).expression, visitor, isExpression));
// Signatures and Signature Elements
case SyntaxKind.FunctionType:
return updateFunctionTypeNode(<FunctionTypeNode>node,
nodesVisitor((<FunctionTypeNode>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<FunctionTypeNode>node).parameters, visitor, isParameterDeclaration),
visitNode((<FunctionTypeNode>node).type, visitor, isTypeNode));
// Signature elements
case SyntaxKind.ConstructorType:
return updateConstructorTypeNode(<ConstructorTypeNode>node,
nodesVisitor((<ConstructorTypeNode>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<ConstructorTypeNode>node).parameters, visitor, isParameterDeclaration),
visitNode((<ConstructorTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.CallSignature:
return updateCallSignatureDeclaration(<CallSignatureDeclaration>node,
nodesVisitor((<CallSignatureDeclaration>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<CallSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<CallSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.ConstructSignature:
return updateConstructSignatureDeclaration(<ConstructSignatureDeclaration>node,
nodesVisitor((<ConstructSignatureDeclaration>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<ConstructSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<ConstructSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.MethodSignature:
return updateMethodSignature(<MethodSignature>node,
nodesVisitor((<MethodSignature>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<MethodSignature>node).parameters, visitor, isParameterDeclaration),
visitNode((<MethodSignature>node).type, visitor, isTypeNode),
visitNode((<MethodSignature>node).name, visitor, isPropertyName),
visitNode((<MethodSignature>node).questionToken, tokenVisitor, isToken));
case SyntaxKind.IndexSignature:
return updateIndexSignatureDeclaration(<IndexSignatureDeclaration>node,
nodesVisitor((<IndexSignatureDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<IndexSignatureDeclaration>node).modifiers, visitor, isModifier),
nodesVisitor((<IndexSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<IndexSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.TypeParameter:
return updateTypeParameterDeclaration(<TypeParameterDeclaration>node,
visitNode((<TypeParameterDeclaration>node).name, visitor, isIdentifier),
visitNode((<TypeParameterDeclaration>node).constraint, visitor, isTypeNode),
visitNode((<TypeParameterDeclaration>node).default, visitor, isTypeNode));
case SyntaxKind.Parameter:
return updateParameter(<ParameterDeclaration>node,
@@ -292,67 +251,7 @@ namespace ts {
return updateDecorator(<Decorator>node,
visitNode((<Decorator>node).expression, visitor, isExpression));
// Types
case SyntaxKind.TypeReference:
return updateTypeReferenceNode(<TypeReferenceNode>node,
visitNode((<TypeReferenceNode>node).typeName, visitor, isEntityName),
nodesVisitor((<TypeReferenceNode>node).typeArguments, visitor, isTypeNode));
case SyntaxKind.TypePredicate:
return updateTypePredicateNode(<TypePredicateNode>node,
visitNode((<TypePredicateNode>node).parameterName, visitor),
visitNode((<TypePredicateNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeQuery:
return updateTypeQueryNode((<TypeQueryNode>node), visitNode((<TypeQueryNode>node).exprName, visitor, isEntityName));
case SyntaxKind.TypeLiteral:
return updateTypeLiteralNode((<TypeLiteralNode>node), nodesVisitor((<TypeLiteralNode>node).members, visitor));
case SyntaxKind.ArrayType:
return updateArrayTypeNode(<ArrayTypeNode>node, visitNode((<ArrayTypeNode>node).elementType, visitor, isTypeNode));
case SyntaxKind.TupleType:
return updateTypleTypeNode((<TupleTypeNode>node), nodesVisitor((<TupleTypeNode>node).elementTypes, visitor, isTypeNode));
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
return updateUnionOrIntersectionTypeNode(<UnionOrIntersectionTypeNode>node,
nodesVisitor((<UnionOrIntersectionTypeNode>node).types, visitor, isTypeNode));
case SyntaxKind.ParenthesizedType:
return updateParenthesizedType(<ParenthesizedTypeNode>node,
visitNode((<ParenthesizedTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeOperator:
return updateTypeOperatorNode(<TypeOperatorNode>node, visitNode((<TypeOperatorNode>node).type, visitor, isTypeNode));
case SyntaxKind.IndexedAccessType:
return updateIndexedAccessTypeNode((<IndexedAccessTypeNode>node),
visitNode((<IndexedAccessTypeNode>node).objectType, visitor, isTypeNode),
visitNode((<IndexedAccessTypeNode>node).indexType, visitor, isTypeNode));
case SyntaxKind.MappedType:
return updateMappedTypeNode((<MappedTypeNode>node),
visitNode((<MappedTypeNode>node).readonlyToken, tokenVisitor, isToken),
visitNode((<MappedTypeNode>node).typeParameter, visitor, isTypeParameter),
visitNode((<MappedTypeNode>node).questionToken, tokenVisitor, isToken),
visitNode((<MappedTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.LiteralType:
return updateLiteralTypeNode(<LiteralTypeNode>node,
visitNode((<LiteralTypeNode>node).literal, visitor, isExpression));
// Type Declarations
case SyntaxKind.TypeParameter:
return updateTypeParameterDeclaration(<TypeParameterDeclaration>node,
visitNode((<TypeParameterDeclaration>node).name, visitor, isIdentifier),
visitNode((<TypeParameterDeclaration>node).constraint, visitor, isTypeNode),
visitNode((<TypeParameterDeclaration>node).default, visitor, isTypeNode));
// Type members
// Type elements
case SyntaxKind.PropertySignature:
return updatePropertySignature((<PropertySignature>node),
@@ -369,6 +268,14 @@ namespace ts {
visitNode((<PropertyDeclaration>node).type, visitor, isTypeNode),
visitNode((<PropertyDeclaration>node).initializer, visitor, isExpression));
case SyntaxKind.MethodSignature:
return updateMethodSignature(<MethodSignature>node,
nodesVisitor((<MethodSignature>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<MethodSignature>node).parameters, visitor, isParameterDeclaration),
visitNode((<MethodSignature>node).type, visitor, isTypeNode),
visitNode((<MethodSignature>node).name, visitor, isPropertyName),
visitNode((<MethodSignature>node).questionToken, tokenVisitor, isToken));
case SyntaxKind.MethodDeclaration:
return updateMethod(<MethodDeclaration>node,
nodesVisitor((<MethodDeclaration>node).decorators, visitor, isDecorator),
@@ -405,7 +312,99 @@ namespace ts {
visitParameterList((<SetAccessorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitFunctionBody((<SetAccessorDeclaration>node).body, visitor, context));
case SyntaxKind.CallSignature:
return updateCallSignature(<CallSignatureDeclaration>node,
nodesVisitor((<CallSignatureDeclaration>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<CallSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<CallSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.ConstructSignature:
return updateConstructSignature(<ConstructSignatureDeclaration>node,
nodesVisitor((<ConstructSignatureDeclaration>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<ConstructSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<ConstructSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.IndexSignature:
return updateIndexSignature(<IndexSignatureDeclaration>node,
nodesVisitor((<IndexSignatureDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<IndexSignatureDeclaration>node).modifiers, visitor, isModifier),
nodesVisitor((<IndexSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<IndexSignatureDeclaration>node).type, visitor, isTypeNode));
// Types
case SyntaxKind.TypePredicate:
return updateTypePredicateNode(<TypePredicateNode>node,
visitNode((<TypePredicateNode>node).parameterName, visitor),
visitNode((<TypePredicateNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeReference:
return updateTypeReferenceNode(<TypeReferenceNode>node,
visitNode((<TypeReferenceNode>node).typeName, visitor, isEntityName),
nodesVisitor((<TypeReferenceNode>node).typeArguments, visitor, isTypeNode));
case SyntaxKind.FunctionType:
return updateFunctionTypeNode(<FunctionTypeNode>node,
nodesVisitor((<FunctionTypeNode>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<FunctionTypeNode>node).parameters, visitor, isParameterDeclaration),
visitNode((<FunctionTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.ConstructorType:
return updateConstructorTypeNode(<ConstructorTypeNode>node,
nodesVisitor((<ConstructorTypeNode>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<ConstructorTypeNode>node).parameters, visitor, isParameterDeclaration),
visitNode((<ConstructorTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeQuery:
return updateTypeQueryNode((<TypeQueryNode>node),
visitNode((<TypeQueryNode>node).exprName, visitor, isEntityName));
case SyntaxKind.TypeLiteral:
return updateTypeLiteralNode((<TypeLiteralNode>node),
nodesVisitor((<TypeLiteralNode>node).members, visitor, isTypeElement));
case SyntaxKind.ArrayType:
return updateArrayTypeNode(<ArrayTypeNode>node,
visitNode((<ArrayTypeNode>node).elementType, visitor, isTypeNode));
case SyntaxKind.TupleType:
return updateTypleTypeNode((<TupleTypeNode>node),
nodesVisitor((<TupleTypeNode>node).elementTypes, visitor, isTypeNode));
case SyntaxKind.UnionType:
return updateUnionTypeNode(<UnionTypeNode>node,
nodesVisitor((<UnionTypeNode>node).types, visitor, isTypeNode));
case SyntaxKind.IntersectionType:
return updateIntersectionTypeNode(<IntersectionTypeNode>node,
nodesVisitor((<IntersectionTypeNode>node).types, visitor, isTypeNode));
case SyntaxKind.ParenthesizedType:
return updateParenthesizedType(<ParenthesizedTypeNode>node,
visitNode((<ParenthesizedTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeOperator:
return updateTypeOperatorNode(<TypeOperatorNode>node,
visitNode((<TypeOperatorNode>node).type, visitor, isTypeNode));
case SyntaxKind.IndexedAccessType:
return updateIndexedAccessTypeNode((<IndexedAccessTypeNode>node),
visitNode((<IndexedAccessTypeNode>node).objectType, visitor, isTypeNode),
visitNode((<IndexedAccessTypeNode>node).indexType, visitor, isTypeNode));
case SyntaxKind.MappedType:
return updateMappedTypeNode((<MappedTypeNode>node),
visitNode((<MappedTypeNode>node).readonlyToken, tokenVisitor, isToken),
visitNode((<MappedTypeNode>node).typeParameter, visitor, isTypeParameter),
visitNode((<MappedTypeNode>node).questionToken, tokenVisitor, isToken),
visitNode((<MappedTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.LiteralType:
return updateLiteralTypeNode(<LiteralTypeNode>node,
visitNode((<LiteralTypeNode>node).literal, visitor, isExpression));
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
return updateObjectBindingPattern(<ObjectBindingPattern>node,
nodesVisitor((<ObjectBindingPattern>node).elements, visitor, isBindingElement));
@@ -422,6 +421,7 @@ namespace ts {
visitNode((<BindingElement>node).initializer, visitor, isExpression));
// Expression
case SyntaxKind.ArrayLiteralExpression:
return updateArrayLiteral(<ArrayLiteralExpression>node,
nodesVisitor((<ArrayLiteralExpression>node).elements, visitor, isExpression));
@@ -500,11 +500,6 @@ namespace ts {
return updateAwait(<AwaitExpression>node,
visitNode((<AwaitExpression>node).expression, visitor, isExpression));
case SyntaxKind.BinaryExpression:
return updateBinary(<BinaryExpression>node,
visitNode((<BinaryExpression>node).left, visitor, isExpression),
visitNode((<BinaryExpression>node).right, visitor, isExpression));
case SyntaxKind.PrefixUnaryExpression:
return updatePrefix(<PrefixUnaryExpression>node,
visitNode((<PrefixUnaryExpression>node).operand, visitor, isExpression));
@@ -513,6 +508,11 @@ namespace ts {
return updatePostfix(<PostfixUnaryExpression>node,
visitNode((<PostfixUnaryExpression>node).operand, visitor, isExpression));
case SyntaxKind.BinaryExpression:
return updateBinary(<BinaryExpression>node,
visitNode((<BinaryExpression>node).left, visitor, isExpression),
visitNode((<BinaryExpression>node).right, visitor, isExpression));
case SyntaxKind.ConditionalExpression:
return updateConditional(<ConditionalExpression>node,
visitNode((<ConditionalExpression>node).condition, visitor, isExpression),
@@ -555,13 +555,19 @@ namespace ts {
return updateNonNullExpression(<NonNullExpression>node,
visitNode((<NonNullExpression>node).expression, visitor, isExpression));
case SyntaxKind.MetaProperty:
return updateMetaProperty(<MetaProperty>node,
visitNode((<MetaProperty>node).name, visitor, isIdentifier));
// Misc
case SyntaxKind.TemplateSpan:
return updateTemplateSpan(<TemplateSpan>node,
visitNode((<TemplateSpan>node).expression, visitor, isExpression),
visitNode((<TemplateSpan>node).literal, visitor, isTemplateMiddleOrTemplateTail));
// Element
case SyntaxKind.Block:
return updateBlock(<Block>node,
nodesVisitor((<Block>node).statements, visitor, isStatement));
@@ -678,6 +684,21 @@ namespace ts {
nodesVisitor((<ClassDeclaration>node).heritageClauses, visitor, isHeritageClause),
nodesVisitor((<ClassDeclaration>node).members, visitor, isClassElement));
case SyntaxKind.InterfaceDeclaration:
return updateInterfaceDeclaration(<InterfaceDeclaration>node,
nodesVisitor((<InterfaceDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<InterfaceDeclaration>node).modifiers, visitor, isModifier),
visitNode((<InterfaceDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<InterfaceDeclaration>node).typeParameters, visitor, isTypeParameter),
nodesVisitor((<InterfaceDeclaration>node).heritageClauses, visitor, isHeritageClause),
nodesVisitor((<InterfaceDeclaration>node).members, visitor, isTypeElement));
case SyntaxKind.TypeAliasDeclaration:
return updateTypeAliasDeclaration(<TypeAliasDeclaration>node,
visitNode((<TypeAliasDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<TypeAliasDeclaration>node).typeParameters, visitor, isTypeParameter),
visitNode((<TypeAliasDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.EnumDeclaration:
return updateEnumDeclaration(<EnumDeclaration>node,
nodesVisitor((<EnumDeclaration>node).decorators, visitor, isDecorator),
@@ -700,6 +721,10 @@ namespace ts {
return updateCaseBlock(<CaseBlock>node,
nodesVisitor((<CaseBlock>node).clauses, visitor, isCaseOrDefaultClause));
case SyntaxKind.NamespaceExportDeclaration:
return updateNamespaceExportDeclaration(<NamespaceExportDeclaration>node,
visitNode((<NamespaceExportDeclaration>node).name, visitor, isIdentifier));
case SyntaxKind.ImportEqualsDeclaration:
return updateImportEqualsDeclaration(<ImportEqualsDeclaration>node,
nodesVisitor((<ImportEqualsDeclaration>node).decorators, visitor, isDecorator),
@@ -755,21 +780,19 @@ namespace ts {
visitNode((<ExportSpecifier>node).name, visitor, isIdentifier));
// Module references
case SyntaxKind.ExternalModuleReference:
return updateExternalModuleReference(<ExternalModuleReference>node,
visitNode((<ExternalModuleReference>node).expression, visitor, isExpression));
// JSX
case SyntaxKind.JsxElement:
return updateJsxElement(<JsxElement>node,
visitNode((<JsxElement>node).openingElement, visitor, isJsxOpeningElement),
nodesVisitor((<JsxElement>node).children, visitor, isJsxChild),
visitNode((<JsxElement>node).closingElement, visitor, isJsxClosingElement));
case SyntaxKind.JsxAttributes:
return updateJsxAttributes(<JsxAttributes>node,
nodesVisitor((<JsxAttributes>node).properties, visitor, isJsxAttributeLike));
case SyntaxKind.JsxSelfClosingElement:
return updateJsxSelfClosingElement(<JsxSelfClosingElement>node,
visitNode((<JsxSelfClosingElement>node).tagName, visitor, isJsxTagNameExpression),
@@ -789,6 +812,10 @@ namespace ts {
visitNode((<JsxAttribute>node).name, visitor, isIdentifier),
visitNode((<JsxAttribute>node).initializer, visitor, isStringLiteralOrJsxExpression));
case SyntaxKind.JsxAttributes:
return updateJsxAttributes(<JsxAttributes>node,
nodesVisitor((<JsxAttributes>node).properties, visitor, isJsxAttributeLike));
case SyntaxKind.JsxSpreadAttribute:
return updateJsxSpreadAttribute(<JsxSpreadAttribute>node,
visitNode((<JsxSpreadAttribute>node).expression, visitor, isExpression));
@@ -798,6 +825,7 @@ namespace ts {
visitNode((<JsxExpression>node).expression, visitor, isExpression));
// Clauses
case SyntaxKind.CaseClause:
return updateCaseClause(<CaseClause>node,
visitNode((<CaseClause>node).expression, visitor, isExpression),
@@ -817,6 +845,7 @@ namespace ts {
visitNode((<CatchClause>node).block, visitor, isBlock));
// Property assignments
case SyntaxKind.PropertyAssignment:
return updatePropertyAssignment(<PropertyAssignment>node,
visitNode((<PropertyAssignment>node).name, visitor, isPropertyName),
@@ -848,8 +877,10 @@ namespace ts {
visitNode((<PartiallyEmittedExpression>node).expression, visitor, isExpression));
default:
// No need to visit nodes with no children.
return node;
}
}
/**
+1 -1
View File
@@ -655,7 +655,7 @@ namespace FourSlash {
ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => {
const marker = this.getMarkerByName(endMarker);
if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) {
this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`);
this.raiseError(`goToDefinition failed for definition ${endMarker} (${i}): expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`);
}
});
}
+12
View File
@@ -241,6 +241,18 @@ namespace ts {
*/`);
parsesCorrectly("argSynonymForParamTag",
`/**
* @arg {number} name1 Description
*/`);
parsesCorrectly("argumentSynonymForParamTag",
`/**
* @argument {number} name1 Description
*/`);
parsesCorrectly("templateTag",
`/**
* @template T
+1 -1
View File
@@ -3,7 +3,7 @@ interface ProxyHandler<T extends object> {
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
+3 -4
View File
@@ -708,12 +708,11 @@ namespace ts.server {
}
sys.require = (initialDir: string, moduleName: string): RequireResult => {
const result = nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, /*cache*/ undefined, /*jsOnly*/ true);
try {
return { module: require(result.resolvedModule.resolvedFileName), error: undefined };
return { module: require(resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined };
}
catch (e) {
return { module: undefined, error: e };
catch (error) {
return { module: undefined, error };
}
};
@@ -96,6 +96,9 @@ namespace ts.server.typingsInstaller {
this.log.writeLine(`Updating ${TypesRegistryPackageName} npm package...`);
}
this.execSync(`${this.npmPath} install ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation, stdio: "ignore" });
if (this.log.isEnabled()) {
this.log.writeLine(`Updated ${TypesRegistryPackageName} npm package`);
}
}
catch (e) {
if (this.log.isEnabled()) {
+11 -10
View File
@@ -1,7 +1,8 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code],
errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1.code,
Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code],
getCodeActions: getActionsForAddMissingMember
});
@@ -110,16 +111,16 @@ namespace ts.codefix {
if (!isStatic) {
const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword);
const indexingParameter = createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
"x",
/*questionToken*/ undefined,
/*questionToken*/ undefined,
stringTypeNode,
/*initializer*/ undefined);
const indexSignature = createIndexSignatureDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*initializer*/ undefined);
const indexSignature = createIndexSignature(
/*decorators*/ undefined,
/*modifiers*/ undefined,
[indexingParameter],
typeNode);
@@ -135,4 +136,4 @@ namespace ts.codefix {
return actions;
}
}
}
}
+53
View File
@@ -0,0 +1,53 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code,
Diagnostics.Cannot_find_name_0_Did_you_mean_1.code],
getCodeActions: getActionsForCorrectSpelling
});
function getActionsForCorrectSpelling(context: CodeFixContext): CodeAction[] | undefined {
const sourceFile = context.sourceFile;
// This is the identifier of the misspelled word. eg:
// this.speling = 1;
// ^^^^^^^
const node = getTokenAtPosition(sourceFile, context.span.start);
const checker = context.program.getTypeChecker();
let suggestion: string;
if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) {
const containingType = checker.getTypeAtLocation(node.parent.expression);
suggestion = checker.getSuggestionForNonexistentProperty(node as Identifier, containingType);
}
else {
const meaning = getMeaningFromLocation(node);
suggestion = checker.getSuggestionForNonexistentSymbol(node, getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning));
}
if (suggestion) {
return [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_spelling_to_0), [suggestion]),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{
span: { start: node.getStart(), length: node.getWidth() },
newText: suggestion
}],
}],
}];
}
}
function convertSemanticMeaningToSymbolFlags(meaning: SemanticMeaning): SymbolFlags {
let flags = 0;
if (meaning & SemanticMeaning.Namespace) {
flags |= SymbolFlags.Namespace;
}
if (meaning & SemanticMeaning.Type) {
flags |= SymbolFlags.Type;
}
if (meaning & SemanticMeaning.Value) {
flags |= SymbolFlags.Value;
}
return flags;
}
}
+1
View File
@@ -1,5 +1,6 @@
/// <reference path="fixClassIncorrectlyImplementsInterface.ts" />
/// <reference path="fixAddMissingMember.ts" />
/// <reference path="fixSpelling.ts" />
/// <reference path="fixClassDoesntImplementInheritedAbstractMember.ts" />
/// <reference path="fixClassSuperMustPrecedeThisAccess.ts" />
/// <reference path="fixConstructorForDerivedNeedSuperCall.ts" />
+3 -3
View File
@@ -63,7 +63,7 @@ namespace ts.codefix {
const declaration = declarations[0] as Declaration;
// Clone name to remove leading trivia.
const name = getSynthesizedClone(<PropertyName>declaration.name);
const name = getSynthesizedClone(getNameOfDeclaration(declaration)) as PropertyName;
const visibilityModifier = createVisibilityModifier(getModifierFlags(declaration));
const modifiers = visibilityModifier ? createNodeArray([visibilityModifier]) : undefined;
const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
@@ -200,7 +200,7 @@ namespace ts.codefix {
}
export function createStubbedMethod(modifiers: Modifier[], name: PropertyName, optional: boolean, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], returnType: TypeNode | undefined) {
return createMethodDeclaration(
return createMethod(
/*decorators*/ undefined,
modifiers,
/*asteriskToken*/ undefined,
@@ -231,4 +231,4 @@ namespace ts.codefix {
}
return undefined;
}
}
}
+390 -388
View File
@@ -1,5 +1,14 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: [
Diagnostics.Cannot_find_name_0.code,
Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
Diagnostics.Cannot_find_namespace_0.code,
Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
],
getCodeActions: getImportCodeActions
});
type ImportCodeActionKind = "CodeChange" | "InsertingIntoExistingImport" | "NewImport";
interface ImportCodeAction extends CodeAction {
@@ -113,465 +122,458 @@ namespace ts.codefix {
}
}
registerCodeFix({
errorCodes: [
Diagnostics.Cannot_find_name_0.code,
Diagnostics.Cannot_find_namespace_0.code,
Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const checker = context.program.getTypeChecker();
const allSourceFiles = context.program.getSourceFiles();
const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false;
function getImportCodeActions(context: CodeFixContext): ImportCodeAction[] {
const sourceFile = context.sourceFile;
const checker = context.program.getTypeChecker();
const allSourceFiles = context.program.getSourceFiles();
const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false;
const token = getTokenAtPosition(sourceFile, context.span.start);
const name = token.getText();
const symbolIdActionMap = new ImportCodeActionMap();
const token = getTokenAtPosition(sourceFile, context.span.start);
const name = token.getText();
const symbolIdActionMap = new ImportCodeActionMap();
// this is a module id -> module import declaration map
const cachedImportDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[][] = [];
let lastImportDeclaration: Node;
// this is a module id -> module import declaration map
const cachedImportDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[][] = [];
let lastImportDeclaration: Node;
const currentTokenMeaning = getMeaningFromLocation(token);
if (context.errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) {
const symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token));
return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true);
const currentTokenMeaning = getMeaningFromLocation(token);
if (context.errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) {
const symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token));
return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true);
}
const candidateModules = checker.getAmbientModules();
for (const otherSourceFile of allSourceFiles) {
if (otherSourceFile !== sourceFile && isExternalOrCommonJsModule(otherSourceFile)) {
candidateModules.push(otherSourceFile.symbol);
}
}
const candidateModules = checker.getAmbientModules();
for (const otherSourceFile of allSourceFiles) {
if (otherSourceFile !== sourceFile && isExternalOrCommonJsModule(otherSourceFile)) {
candidateModules.push(otherSourceFile.symbol);
for (const moduleSymbol of candidateModules) {
context.cancellationToken.throwIfCancellationRequested();
// check the default export
const defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol);
if (defaultExport) {
const localSymbol = getLocalSymbolForExportDefault(defaultExport);
if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) {
// check if this symbol is already used
const symbolId = getUniqueSymbolId(localSymbol);
symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true));
}
}
for (const moduleSymbol of candidateModules) {
context.cancellationToken.throwIfCancellationRequested();
// check exports with the same name
const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol);
if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
const symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName);
symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol));
}
}
// check the default export
const defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol);
if (defaultExport) {
const localSymbol = getLocalSymbolForExportDefault(defaultExport);
if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) {
// check if this symbol is already used
const symbolId = getUniqueSymbolId(localSymbol);
symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true));
return symbolIdActionMap.getAllActions();
function getImportDeclarations(moduleSymbol: Symbol) {
const moduleSymbolId = getUniqueSymbolId(moduleSymbol);
const cached = cachedImportDeclarations[moduleSymbolId];
if (cached) {
return cached;
}
const existingDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[] = [];
for (const importModuleSpecifier of sourceFile.imports) {
const importSymbol = checker.getSymbolAtLocation(importModuleSpecifier);
if (importSymbol === moduleSymbol) {
existingDeclarations.push(getImportDeclaration(importModuleSpecifier));
}
}
cachedImportDeclarations[moduleSymbolId] = existingDeclarations;
return existingDeclarations;
function getImportDeclaration(moduleSpecifier: LiteralExpression) {
let node: Node = moduleSpecifier;
while (node) {
if (node.kind === SyntaxKind.ImportDeclaration) {
return <ImportDeclaration>node;
}
if (node.kind === SyntaxKind.ImportEqualsDeclaration) {
return <ImportEqualsDeclaration>node;
}
node = node.parent;
}
return undefined;
}
}
// check exports with the same name
const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol);
if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
const symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName);
symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol));
}
function getUniqueSymbolId(symbol: Symbol) {
if (symbol.flags & SymbolFlags.Alias) {
return getSymbolId(checker.getAliasedSymbol(symbol));
}
return getSymbolId(symbol);
}
function checkSymbolHasMeaning(symbol: Symbol, meaning: SemanticMeaning) {
const declarations = symbol.getDeclarations();
return declarations ? some(symbol.declarations, decl => !!(getMeaningFromDeclaration(decl) & meaning)) : false;
}
function getCodeActionForImport(moduleSymbol: Symbol, isDefault?: boolean, isNamespaceImport?: boolean): ImportCodeAction[] {
const existingDeclarations = getImportDeclarations(moduleSymbol);
if (existingDeclarations.length > 0) {
// With an existing import statement, there are more than one actions the user can do.
return getCodeActionsForExistingImport(existingDeclarations);
}
else {
return [getCodeActionForNewImport()];
}
return symbolIdActionMap.getAllActions();
function getCodeActionsForExistingImport(declarations: (ImportDeclaration | ImportEqualsDeclaration)[]): ImportCodeAction[] {
const actions: ImportCodeAction[] = [];
function getImportDeclarations(moduleSymbol: Symbol) {
const moduleSymbolId = getUniqueSymbolId(moduleSymbol);
const cached = cachedImportDeclarations[moduleSymbolId];
if (cached) {
return cached;
}
const existingDeclarations: (ImportDeclaration | ImportEqualsDeclaration)[] = [];
for (const importModuleSpecifier of sourceFile.imports) {
const importSymbol = checker.getSymbolAtLocation(importModuleSpecifier);
if (importSymbol === moduleSymbol) {
existingDeclarations.push(getImportDeclaration(importModuleSpecifier));
}
}
cachedImportDeclarations[moduleSymbolId] = existingDeclarations;
return existingDeclarations;
function getImportDeclaration(moduleSpecifier: LiteralExpression) {
let node: Node = moduleSpecifier;
while (node) {
if (node.kind === SyntaxKind.ImportDeclaration) {
return <ImportDeclaration>node;
// It is possible that multiple import statements with the same specifier exist in the file.
// e.g.
//
// import * as ns from "foo";
// import { member1, member2 } from "foo";
//
// member3/**/ <-- cusor here
//
// in this case we should provie 2 actions:
// 1. change "member3" to "ns.member3"
// 2. add "member3" to the second import statement's import list
// and it is up to the user to decide which one fits best.
let namespaceImportDeclaration: ImportDeclaration | ImportEqualsDeclaration;
let namedImportDeclaration: ImportDeclaration;
let existingModuleSpecifier: string;
for (const declaration of declarations) {
if (declaration.kind === SyntaxKind.ImportDeclaration) {
const namedBindings = declaration.importClause && declaration.importClause.namedBindings;
if (namedBindings && namedBindings.kind === SyntaxKind.NamespaceImport) {
// case:
// import * as ns from "foo"
namespaceImportDeclaration = declaration;
}
if (node.kind === SyntaxKind.ImportEqualsDeclaration) {
return <ImportEqualsDeclaration>node;
else {
// cases:
// import default from "foo"
// import { bar } from "foo" or combination with the first one
// import "foo"
namedImportDeclaration = declaration;
}
node = node.parent;
existingModuleSpecifier = declaration.moduleSpecifier.getText();
}
else {
// case:
// import foo = require("foo")
namespaceImportDeclaration = declaration;
existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration);
}
return undefined;
}
}
function getUniqueSymbolId(symbol: Symbol) {
if (symbol.flags & SymbolFlags.Alias) {
return getSymbolId(checker.getAliasedSymbol(symbol));
if (namespaceImportDeclaration) {
actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration));
}
return getSymbolId(symbol);
}
function checkSymbolHasMeaning(symbol: Symbol, meaning: SemanticMeaning) {
const declarations = symbol.getDeclarations();
return declarations ? some(symbol.declarations, decl => !!(getMeaningFromDeclaration(decl) & meaning)) : false;
}
function getCodeActionForImport(moduleSymbol: Symbol, isDefault?: boolean, isNamespaceImport?: boolean): ImportCodeAction[] {
const existingDeclarations = getImportDeclarations(moduleSymbol);
if (existingDeclarations.length > 0) {
// With an existing import statement, there are more than one actions the user can do.
return getCodeActionsForExistingImport(existingDeclarations);
if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause &&
(namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) {
/**
* If the existing import declaration already has a named import list, just
* insert the identifier into that list.
*/
const fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause);
const moduleSpecifierWithoutQuotes = stripQuotes(namedImportDeclaration.moduleSpecifier.getText());
actions.push(createCodeAction(
Diagnostics.Add_0_to_existing_import_declaration_from_1,
[name, moduleSpecifierWithoutQuotes],
fileTextChanges,
"InsertingIntoExistingImport",
moduleSpecifierWithoutQuotes
));
}
else {
return [getCodeActionForNewImport()];
// we need to create a new import statement, but the existing module specifier can be reused.
actions.push(getCodeActionForNewImport(existingModuleSpecifier));
}
return actions;
function getModuleSpecifierFromImportEqualsDeclaration(declaration: ImportEqualsDeclaration) {
if (declaration.moduleReference && declaration.moduleReference.kind === SyntaxKind.ExternalModuleReference) {
return declaration.moduleReference.expression.getText();
}
return declaration.moduleReference.getText();
}
function getCodeActionsForExistingImport(declarations: (ImportDeclaration | ImportEqualsDeclaration)[]): ImportCodeAction[] {
const actions: ImportCodeAction[] = [];
// It is possible that multiple import statements with the same specifier exist in the file.
// e.g.
//
// import * as ns from "foo";
// import { member1, member2 } from "foo";
//
// member3/**/ <-- cusor here
//
// in this case we should provie 2 actions:
// 1. change "member3" to "ns.member3"
// 2. add "member3" to the second import statement's import list
// and it is up to the user to decide which one fits best.
let namespaceImportDeclaration: ImportDeclaration | ImportEqualsDeclaration;
let namedImportDeclaration: ImportDeclaration;
let existingModuleSpecifier: string;
for (const declaration of declarations) {
if (declaration.kind === SyntaxKind.ImportDeclaration) {
const namedBindings = declaration.importClause && declaration.importClause.namedBindings;
if (namedBindings && namedBindings.kind === SyntaxKind.NamespaceImport) {
// case:
// import * as ns from "foo"
namespaceImportDeclaration = declaration;
}
else {
// cases:
// import default from "foo"
// import { bar } from "foo" or combination with the first one
// import "foo"
namedImportDeclaration = declaration;
}
existingModuleSpecifier = declaration.moduleSpecifier.getText();
}
else {
// case:
// import foo = require("foo")
namespaceImportDeclaration = declaration;
existingModuleSpecifier = getModuleSpecifierFromImportEqualsDeclaration(declaration);
}
function getTextChangeForImportClause(importClause: ImportClause): FileTextChanges[] {
const importList = <NamedImports>importClause.namedBindings;
const newImportSpecifier = createImportSpecifier(/*propertyName*/ undefined, createIdentifier(name));
// case 1:
// original text: import default from "module"
// change to: import default, { name } from "module"
// case 2:
// original text: import {} from "module"
// change to: import { name } from "module"
if (!importList || importList.elements.length === 0) {
const newImportClause = createImportClause(importClause.name, createNamedImports([newImportSpecifier]));
return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges();
}
if (namespaceImportDeclaration) {
actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration));
}
if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause &&
(namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) {
/**
* If the existing import declaration already has a named import list, just
* insert the identifier into that list.
*/
const fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause);
const moduleSpecifierWithoutQuotes = stripQuotes(namedImportDeclaration.moduleSpecifier.getText());
actions.push(createCodeAction(
Diagnostics.Add_0_to_existing_import_declaration_from_1,
[name, moduleSpecifierWithoutQuotes],
fileTextChanges,
"InsertingIntoExistingImport",
moduleSpecifierWithoutQuotes
));
}
else {
// we need to create a new import statement, but the existing module specifier can be reused.
actions.push(getCodeActionForNewImport(existingModuleSpecifier));
}
return actions;
function getModuleSpecifierFromImportEqualsDeclaration(declaration: ImportEqualsDeclaration) {
if (declaration.moduleReference && declaration.moduleReference.kind === SyntaxKind.ExternalModuleReference) {
return declaration.moduleReference.expression.getText();
}
return declaration.moduleReference.getText();
}
function getTextChangeForImportClause(importClause: ImportClause): FileTextChanges[] {
const importList = <NamedImports>importClause.namedBindings;
const newImportSpecifier = createImportSpecifier(/*propertyName*/ undefined, createIdentifier(name));
// case 1:
// original text: import default from "module"
// change to: import default, { name } from "module"
// case 2:
// original text: import {} from "module"
// change to: import { name } from "module"
if (!importList || importList.elements.length === 0) {
const newImportClause = createImportClause(importClause.name, createNamedImports([newImportSpecifier]));
return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges();
}
/**
* If the import list has one import per line, preserve that. Otherwise, insert on same line as last element
* import {
* foo
* } from "./module";
*/
return createChangeTracker().insertNodeInListAfter(
sourceFile,
importList.elements[importList.elements.length - 1],
newImportSpecifier).getChanges();
}
function getCodeActionForNamespaceImport(declaration: ImportDeclaration | ImportEqualsDeclaration): ImportCodeAction {
let namespacePrefix: string;
if (declaration.kind === SyntaxKind.ImportDeclaration) {
namespacePrefix = (<NamespaceImport>declaration.importClause.namedBindings).name.getText();
}
else {
namespacePrefix = declaration.name.getText();
}
namespacePrefix = stripQuotes(namespacePrefix);
/**
* Cases:
* import * as ns from "mod"
* import default, * as ns from "mod"
* import ns = require("mod")
*
* Because there is no import list, we alter the reference to include the
* namespace instead of altering the import declaration. For example, "foo" would
* become "ns.foo"
*/
return createCodeAction(
Diagnostics.Change_0_to_1,
[name, `${namespacePrefix}.${name}`],
createChangeTracker().replaceNode(sourceFile, token, createPropertyAccess(createIdentifier(namespacePrefix), name)).getChanges(),
"CodeChange"
);
}
/**
* If the import list has one import per line, preserve that. Otherwise, insert on same line as last element
* import {
* foo
* } from "./module";
*/
return createChangeTracker().insertNodeInListAfter(
sourceFile,
importList.elements[importList.elements.length - 1],
newImportSpecifier).getChanges();
}
function getCodeActionForNewImport(moduleSpecifier?: string): ImportCodeAction {
if (!lastImportDeclaration) {
// insert after any existing imports
for (let i = sourceFile.statements.length - 1; i >= 0; i--) {
const statement = sourceFile.statements[i];
if (statement.kind === SyntaxKind.ImportEqualsDeclaration || statement.kind === SyntaxKind.ImportDeclaration) {
lastImportDeclaration = statement;
break;
}
}
}
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport());
const changeTracker = createChangeTracker();
const importClause = isDefault
? createImportClause(createIdentifier(name), /*namedBindings*/ undefined)
: isNamespaceImport
? createImportClause(/*name*/ undefined, createNamespaceImport(createIdentifier(name)))
: createImportClause(/*name*/ undefined, createNamedImports([createImportSpecifier(/*propertyName*/ undefined, createIdentifier(name))]));
const importDecl = createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, createLiteral(moduleSpecifierWithoutQuotes));
if (!lastImportDeclaration) {
changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: `${context.newLineCharacter}${context.newLineCharacter}` });
function getCodeActionForNamespaceImport(declaration: ImportDeclaration | ImportEqualsDeclaration): ImportCodeAction {
let namespacePrefix: string;
if (declaration.kind === SyntaxKind.ImportDeclaration) {
namespacePrefix = (<NamespaceImport>declaration.importClause.namedBindings).name.getText();
}
else {
changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter });
namespacePrefix = declaration.name.getText();
}
namespacePrefix = stripQuotes(namespacePrefix);
// if this file doesn't have any import statements, insert an import statement and then insert a new line
// between the only import statement and user code. Otherwise just insert the statement because chances
// are there are already a new line seperating code and import statements.
/**
* Cases:
* import * as ns from "mod"
* import default, * as ns from "mod"
* import ns = require("mod")
*
* Because there is no import list, we alter the reference to include the
* namespace instead of altering the import declaration. For example, "foo" would
* become "ns.foo"
*/
return createCodeAction(
Diagnostics.Import_0_from_1,
[name, `"${moduleSpecifierWithoutQuotes}"`],
changeTracker.getChanges(),
"NewImport",
moduleSpecifierWithoutQuotes
Diagnostics.Change_0_to_1,
[name, `${namespacePrefix}.${name}`],
createChangeTracker().replaceNode(sourceFile, token, createPropertyAccess(createIdentifier(namespacePrefix), name)).getChanges(),
"CodeChange"
);
}
}
function getModuleSpecifierForNewImport() {
const fileName = sourceFile.fileName;
const moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName;
const sourceDirectory = getDirectoryPath(fileName);
const options = context.program.getCompilerOptions();
return tryGetModuleNameFromAmbientModule() ||
tryGetModuleNameFromTypeRoots() ||
tryGetModuleNameAsNodeModule() ||
tryGetModuleNameFromBaseUrl() ||
tryGetModuleNameFromRootDirs() ||
removeFileExtension(getRelativePath(moduleFileName, sourceDirectory));
function tryGetModuleNameFromAmbientModule(): string {
if (moduleSymbol.valueDeclaration.kind !== SyntaxKind.SourceFile) {
return moduleSymbol.name;
}
function getCodeActionForNewImport(moduleSpecifier?: string): ImportCodeAction {
if (!lastImportDeclaration) {
// insert after any existing imports
for (let i = sourceFile.statements.length - 1; i >= 0; i--) {
const statement = sourceFile.statements[i];
if (statement.kind === SyntaxKind.ImportEqualsDeclaration || statement.kind === SyntaxKind.ImportDeclaration) {
lastImportDeclaration = statement;
break;
}
}
}
function tryGetModuleNameFromBaseUrl() {
if (!options.baseUrl) {
return undefined;
}
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport());
const changeTracker = createChangeTracker();
const importClause = isDefault
? createImportClause(createIdentifier(name), /*namedBindings*/ undefined)
: isNamespaceImport
? createImportClause(/*name*/ undefined, createNamespaceImport(createIdentifier(name)))
: createImportClause(/*name*/ undefined, createNamedImports([createImportSpecifier(/*propertyName*/ undefined, createIdentifier(name))]));
const importDecl = createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, createLiteral(moduleSpecifierWithoutQuotes));
if (!lastImportDeclaration) {
changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: `${context.newLineCharacter}${context.newLineCharacter}` });
}
else {
changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter });
}
let relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl);
if (!relativeName) {
return undefined;
}
// if this file doesn't have any import statements, insert an import statement and then insert a new line
// between the only import statement and user code. Otherwise just insert the statement because chances
// are there are already a new line seperating code and import statements.
return createCodeAction(
Diagnostics.Import_0_from_1,
[name, `"${moduleSpecifierWithoutQuotes}"`],
changeTracker.getChanges(),
"NewImport",
moduleSpecifierWithoutQuotes
);
const relativeNameWithIndex = removeFileExtension(relativeName);
relativeName = removeExtensionAndIndexPostFix(relativeName);
function getModuleSpecifierForNewImport() {
const fileName = sourceFile.fileName;
const moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName;
const sourceDirectory = getDirectoryPath(fileName);
const options = context.program.getCompilerOptions();
if (options.paths) {
for (const key in options.paths) {
for (const pattern of options.paths[key]) {
const indexOfStar = pattern.indexOf("*");
if (indexOfStar === 0 && pattern.length === 1) {
continue;
}
else if (indexOfStar !== -1) {
const prefix = pattern.substr(0, indexOfStar);
const suffix = pattern.substr(indexOfStar + 1);
if (relativeName.length >= prefix.length + suffix.length &&
startsWith(relativeName, prefix) &&
endsWith(relativeName, suffix)) {
const matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length);
return key.replace("\*", matchedStar);
}
}
else if (pattern === relativeName || pattern === relativeNameWithIndex) {
return key;
}
}
}
}
return tryGetModuleNameFromAmbientModule() ||
tryGetModuleNameFromTypeRoots() ||
tryGetModuleNameAsNodeModule() ||
tryGetModuleNameFromBaseUrl() ||
tryGetModuleNameFromRootDirs() ||
removeFileExtension(getRelativePath(moduleFileName, sourceDirectory));
return relativeName;
function tryGetModuleNameFromAmbientModule(): string {
if (moduleSymbol.valueDeclaration.kind !== SyntaxKind.SourceFile) {
return moduleSymbol.name;
}
}
function tryGetModuleNameFromRootDirs() {
if (options.rootDirs) {
const normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs);
const normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs);
if (normalizedTargetPath !== undefined) {
const relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath;
return removeFileExtension(relativePath);
}
}
function tryGetModuleNameFromBaseUrl() {
if (!options.baseUrl) {
return undefined;
}
function tryGetModuleNameFromTypeRoots() {
const typeRoots = getEffectiveTypeRoots(options, context.host);
if (typeRoots) {
const normalizedTypeRoots = map(typeRoots, typeRoot => toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName));
for (const typeRoot of normalizedTypeRoots) {
if (startsWith(moduleFileName, typeRoot)) {
const relativeFileName = moduleFileName.substring(typeRoot.length + 1);
return removeExtensionAndIndexPostFix(relativeFileName);
}
}
}
let relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl);
if (!relativeName) {
return undefined;
}
function tryGetModuleNameAsNodeModule() {
if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs) {
// nothing to do here
return undefined;
}
const relativeNameWithIndex = removeFileExtension(relativeName);
relativeName = removeExtensionAndIndexPostFix(relativeName);
const indexOfNodeModules = moduleFileName.indexOf("node_modules");
if (indexOfNodeModules < 0) {
return undefined;
}
let relativeFileName: string;
if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) {
// if node_modules folder is in this folder or any of its parent folder, no need to keep it.
relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */);
}
else {
relativeFileName = getRelativePath(moduleFileName, sourceDirectory);
}
relativeFileName = removeFileExtension(relativeFileName);
if (endsWith(relativeFileName, "/index")) {
relativeFileName = getDirectoryPath(relativeFileName);
}
else {
try {
const moduleDirectory = getDirectoryPath(moduleFileName);
const packageJsonContent = JSON.parse(context.host.readFile(combinePaths(moduleDirectory, "package.json")));
if (packageJsonContent) {
const mainFile = packageJsonContent.main || packageJsonContent.typings;
if (mainFile) {
const mainExportFile = toPath(mainFile, moduleDirectory, getCanonicalFileName);
if (removeFileExtension(mainExportFile) === removeFileExtension(moduleFileName)) {
relativeFileName = getDirectoryPath(relativeFileName);
}
if (options.paths) {
for (const key in options.paths) {
for (const pattern of options.paths[key]) {
const indexOfStar = pattern.indexOf("*");
if (indexOfStar === 0 && pattern.length === 1) {
continue;
}
else if (indexOfStar !== -1) {
const prefix = pattern.substr(0, indexOfStar);
const suffix = pattern.substr(indexOfStar + 1);
if (relativeName.length >= prefix.length + suffix.length &&
startsWith(relativeName, prefix) &&
endsWith(relativeName, suffix)) {
const matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length);
return key.replace("\*", matchedStar);
}
}
else if (pattern === relativeName || pattern === relativeNameWithIndex) {
return key;
}
}
catch (e) { }
}
return relativeFileName;
}
return relativeName;
}
function getPathRelativeToRootDirs(path: string, rootDirs: string[]) {
for (const rootDir of rootDirs) {
const relativeName = getRelativePathIfInDirectory(path, rootDir);
if (relativeName !== undefined) {
return relativeName;
function tryGetModuleNameFromRootDirs() {
if (options.rootDirs) {
const normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs);
const normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs);
if (normalizedTargetPath !== undefined) {
const relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath;
return removeFileExtension(relativePath);
}
}
return undefined;
}
function removeExtensionAndIndexPostFix(fileName: string) {
fileName = removeFileExtension(fileName);
if (endsWith(fileName, "/index")) {
fileName = fileName.substr(0, fileName.length - 6/* "/index".length */);
function tryGetModuleNameFromTypeRoots() {
const typeRoots = getEffectiveTypeRoots(options, context.host);
if (typeRoots) {
const normalizedTypeRoots = map(typeRoots, typeRoot => toPath(typeRoot, /*basePath*/ undefined, getCanonicalFileName));
for (const typeRoot of normalizedTypeRoots) {
if (startsWith(moduleFileName, typeRoot)) {
const relativeFileName = moduleFileName.substring(typeRoot.length + 1);
return removeExtensionAndIndexPostFix(relativeFileName);
}
}
}
return fileName;
}
function getRelativePathIfInDirectory(path: string, directoryPath: string) {
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return isRootedDiskPath(relativePath) || startsWith(relativePath, "..") ? undefined : relativePath;
}
function tryGetModuleNameAsNodeModule() {
if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs) {
// nothing to do here
return undefined;
}
function getRelativePath(path: string, directoryPath: string) {
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath;
const indexOfNodeModules = moduleFileName.indexOf("node_modules");
if (indexOfNodeModules < 0) {
return undefined;
}
let relativeFileName: string;
if (sourceDirectory.indexOf(moduleFileName.substring(0, indexOfNodeModules - 1)) === 0) {
// if node_modules folder is in this folder or any of its parent folder, no need to keep it.
relativeFileName = moduleFileName.substring(indexOfNodeModules + 13 /* "node_modules\".length */);
}
else {
relativeFileName = getRelativePath(moduleFileName, sourceDirectory);
}
relativeFileName = removeFileExtension(relativeFileName);
if (endsWith(relativeFileName, "/index")) {
relativeFileName = getDirectoryPath(relativeFileName);
}
else {
try {
const moduleDirectory = getDirectoryPath(moduleFileName);
const packageJsonContent = JSON.parse(context.host.readFile(combinePaths(moduleDirectory, "package.json")));
if (packageJsonContent) {
const mainFile = packageJsonContent.main || packageJsonContent.typings;
if (mainFile) {
const mainExportFile = toPath(mainFile, moduleDirectory, getCanonicalFileName);
if (removeFileExtension(mainExportFile) === removeFileExtension(moduleFileName)) {
relativeFileName = getDirectoryPath(relativeFileName);
}
}
}
}
catch (e) { }
}
return relativeFileName;
}
}
function getPathRelativeToRootDirs(path: string, rootDirs: string[]) {
for (const rootDir of rootDirs) {
const relativeName = getRelativePathIfInDirectory(path, rootDir);
if (relativeName !== undefined) {
return relativeName;
}
}
return undefined;
}
function removeExtensionAndIndexPostFix(fileName: string) {
fileName = removeFileExtension(fileName);
if (endsWith(fileName, "/index")) {
fileName = fileName.substr(0, fileName.length - 6/* "/index".length */);
}
return fileName;
}
function getRelativePathIfInDirectory(path: string, directoryPath: string) {
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return isRootedDiskPath(relativePath) || startsWith(relativePath, "..") ? undefined : relativePath;
}
function getRelativePath(path: string, directoryPath: string) {
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath;
}
}
function createChangeTracker() {
return textChanges.ChangeTracker.fromCodeFixContext(context);
}
function createCodeAction(
description: DiagnosticMessage,
diagnosticArgs: string[],
changes: FileTextChanges[],
kind: ImportCodeActionKind,
moduleSpecifier?: string): ImportCodeAction {
return {
description: formatMessage.apply(undefined, [undefined, description].concat(<any[]>diagnosticArgs)),
changes,
kind,
moduleSpecifier
};
}
}
});
function createChangeTracker() {
return textChanges.ChangeTracker.fromCodeFixContext(context);
}
function createCodeAction(
description: DiagnosticMessage,
diagnosticArgs: string[],
changes: FileTextChanges[],
kind: ImportCodeActionKind,
moduleSpecifier?: string): ImportCodeAction {
return {
description: formatMessage.apply(undefined, [undefined, description].concat(<any[]>diagnosticArgs)),
changes,
kind,
moduleSpecifier
};
}
}
}
+2 -2
View File
@@ -260,7 +260,7 @@ namespace ts.Completions {
function addStringLiteralCompletionsFromType(type: Type, result: Push<CompletionEntry>, typeChecker: TypeChecker): void {
if (type && type.flags & TypeFlags.TypeParameter) {
type = typeChecker.getApparentType(type);
type = typeChecker.getBaseConstraintOfType(type);
}
if (!type) {
return;
@@ -1214,7 +1214,7 @@ namespace ts.Completions {
// TODO(jfreeman): Account for computed property name
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
existingName = (<Identifier>m.name).text;
existingName = (getNameOfDeclaration(m) as Identifier).text;
}
existingMemberNames.set(existingName, true);
+1 -10
View File
@@ -108,10 +108,6 @@ namespace ts.FindAllReferences {
switch (def.type) {
case "symbol": {
const { symbol, node } = def;
const declarations = symbol.declarations;
if (!declarations || declarations.length === 0) {
return undefined;
}
const { displayParts, kind } = getDefinitionKindAndDisplayParts(symbol, node, checker);
const name = displayParts.map(p => p.text).join("");
return { node, name, kind, displayParts };
@@ -285,11 +281,6 @@ namespace ts.FindAllReferences.Core {
return undefined;
}
// The symbol was an internal symbol and does not have a declaration e.g. undefined symbol
if (!symbol.declarations || !symbol.declarations.length) {
return undefined;
}
return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options);
}
@@ -908,7 +899,7 @@ namespace ts.FindAllReferences.Core {
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
if (!(flags & SymbolFlags.Transient) && search.includes(shorthandValueSymbol)) {
addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state);
addReference(getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state);
}
}
+1 -1
View File
@@ -487,7 +487,7 @@ namespace ts.formatting {
// falls through
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.Parameter:
return (<Declaration>node).name.kind;
return getNameOfDeclaration(<Declaration>node).kind;
}
}
+3 -1
View File
@@ -283,7 +283,9 @@ namespace ts.formatting {
this.NoSpaceAfterDot = new Rule(RuleDescriptor.create3(SyntaxKind.DotToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// No space before and after indexer
this.NoSpaceBeforeOpenBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeOpenBracket = new Rule(
RuleDescriptor.create2(Shared.TokenRange.AnyExcept(SyntaxKind.AsyncKeyword), SyntaxKind.OpenBracketToken),
RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), RuleAction.Delete));
// Place a space before open brace in a function declaration
+1 -2
View File
@@ -41,8 +41,7 @@ namespace ts.formatting {
}
private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void {
const specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any &&
rule.Descriptor.RightTokenRange !== Shared.TokenRange.Any;
const specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific();
rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => {
rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => {
+1 -4
View File
@@ -341,10 +341,7 @@ namespace ts.formatting {
return Value.Unknown;
}
if (node.parent && (
node.parent.kind === SyntaxKind.CallExpression ||
node.parent.kind === SyntaxKind.NewExpression) &&
(<CallExpression>node.parent).expression !== node) {
if (node.parent && isCallOrNewExpression(node.parent) && (<CallExpression>node.parent).expression !== node) {
const fullCallOrNewExpression = (<CallExpression | NewExpression>node.parent).expression;
const startingExpression = getStartingExpression(fullCallOrNewExpression);
+72 -75
View File
@@ -3,22 +3,13 @@
/* @internal */
namespace ts.formatting {
export namespace Shared {
export interface ITokenAccess {
GetTokens(): SyntaxKind[];
Contains(token: SyntaxKind): boolean;
const allTokens: SyntaxKind[] = [];
for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) {
allTokens.push(token);
}
export class TokenRangeAccess implements ITokenAccess {
private tokens: SyntaxKind[];
constructor(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[]) {
this.tokens = [];
for (let token = from; token <= to; token++) {
if (ts.indexOf(except, token) < 0) {
this.tokens.push(token);
}
}
}
class TokenValuesAccess implements TokenRange {
constructor(private readonly tokens: SyntaxKind[] = []) { }
public GetTokens(): SyntaxKind[] {
return this.tokens;
@@ -27,27 +18,12 @@ namespace ts.formatting {
public Contains(token: SyntaxKind): boolean {
return this.tokens.indexOf(token) >= 0;
}
public isSpecific() { return true; }
}
export class TokenValuesAccess implements ITokenAccess {
private tokens: SyntaxKind[];
constructor(tks: SyntaxKind[]) {
this.tokens = tks && tks.length ? tks : <SyntaxKind[]>[];
}
public GetTokens(): SyntaxKind[] {
return this.tokens;
}
public Contains(token: SyntaxKind): boolean {
return this.tokens.indexOf(token) >= 0;
}
}
export class TokenSingleValueAccess implements ITokenAccess {
constructor(public token: SyntaxKind) {
}
class TokenSingleValueAccess implements TokenRange {
constructor(private readonly token: SyntaxKind) {}
public GetTokens(): SyntaxKind[] {
return [this.token];
@@ -56,15 +32,13 @@ namespace ts.formatting {
public Contains(tokenValue: SyntaxKind): boolean {
return tokenValue === this.token;
}
public isSpecific() { return true; }
}
export class TokenAllAccess implements ITokenAccess {
class TokenAllAccess implements TokenRange {
public GetTokens(): SyntaxKind[] {
const result: SyntaxKind[] = [];
for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) {
result.push(token);
}
return result;
return allTokens;
}
public Contains(): boolean {
@@ -74,53 +48,76 @@ namespace ts.formatting {
public toString(): string {
return "[allTokens]";
}
public isSpecific() { return false; }
}
export class TokenRange {
constructor(public tokenAccess: ITokenAccess) {
}
static FromToken(token: SyntaxKind): TokenRange {
return new TokenRange(new TokenSingleValueAccess(token));
}
static FromTokens(tokens: SyntaxKind[]): TokenRange {
return new TokenRange(new TokenValuesAccess(tokens));
}
static FromRange(f: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange {
return new TokenRange(new TokenRangeAccess(f, to, except));
}
static AllTokens(): TokenRange {
return new TokenRange(new TokenAllAccess());
}
class TokenAllExceptAccess implements TokenRange {
constructor(private readonly except: SyntaxKind) {}
public GetTokens(): SyntaxKind[] {
return this.tokenAccess.GetTokens();
return allTokens.filter(t => t !== this.except);
}
public Contains(token: SyntaxKind): boolean {
return this.tokenAccess.Contains(token);
return token !== this.except;
}
public toString(): string {
return this.tokenAccess.toString();
public isSpecific() { return false; }
}
export interface TokenRange {
GetTokens(): SyntaxKind[];
Contains(token: SyntaxKind): boolean;
isSpecific(): boolean;
}
export namespace TokenRange {
export function FromToken(token: SyntaxKind): TokenRange {
return new TokenSingleValueAccess(token);
}
static Any: TokenRange = TokenRange.AllTokens();
static AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([SyntaxKind.MultiLineCommentTrivia]));
static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword);
static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator);
static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]);
static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]);
static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
static UnaryPostincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]);
static UnaryPredecrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
static UnaryPostdecrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]);
static Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]);
static TypeNames = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]);
export function FromTokens(tokens: SyntaxKind[]): TokenRange {
return new TokenValuesAccess(tokens);
}
export function FromRange(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange {
const tokens: SyntaxKind[] = [];
for (let token = from; token <= to; token++) {
if (ts.indexOf(except, token) < 0) {
tokens.push(token);
}
}
return new TokenValuesAccess(tokens);
}
export function AnyExcept(token: SyntaxKind): TokenRange {
return new TokenAllExceptAccess(token);
}
export const Any: TokenRange = new TokenAllAccess();
export const AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]);
export const Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword);
export const BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator);
export const BinaryKeywordOperators = TokenRange.FromTokens([
SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]);
export const UnaryPrefixOperators = TokenRange.FromTokens([
SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]);
export const UnaryPrefixExpressions = TokenRange.FromTokens([
SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken,
SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
export const UnaryPreincrementExpressions = TokenRange.FromTokens([
SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
export const UnaryPostincrementExpressions = TokenRange.FromTokens([
SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]);
export const UnaryPredecrementExpressions = TokenRange.FromTokens([
SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
export const UnaryPostdecrementExpressions = TokenRange.FromTokens([
SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]);
export const Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]);
export const TypeNames = TokenRange.FromTokens([
SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword,
SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]);
}
}
}
+1 -1
View File
@@ -235,7 +235,7 @@ namespace ts.GoToDefinition {
/** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
function createDefinitionInfo(node: Declaration, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo {
return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName);
return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName);
}
/** Creates a DefinitionInfo directly from the name of a declaration. */
+15 -18
View File
@@ -330,7 +330,7 @@ namespace ts.FindAllReferences {
/** Calls `action` for each import, re-export, or require() in a file. */
function forEachImport(sourceFile: SourceFile, action: (importStatement: ImporterOrCallExpression, imported: StringLiteral) => void): void {
if (sourceFile.externalModuleIndicator) {
if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) {
for (const moduleSpecifier of sourceFile.imports) {
action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier);
}
@@ -358,27 +358,21 @@ namespace ts.FindAllReferences {
}
}
});
if (sourceFile.flags & NodeFlags.JavaScriptFile) {
// Find all 'require()' calls.
sourceFile.forEachChild(function recur(node: Node): void {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
action(node, node.arguments[0] as StringLiteral);
} else {
node.forEachChild(recur);
}
});
}
}
}
function importerFromModuleSpecifier(moduleSpecifier: StringLiteral): Importer {
function importerFromModuleSpecifier(moduleSpecifier: StringLiteral): ImporterOrCallExpression {
const decl = moduleSpecifier.parent;
if (decl.kind === SyntaxKind.ImportDeclaration || decl.kind === SyntaxKind.ExportDeclaration) {
return decl as ImportDeclaration | ExportDeclaration;
switch (decl.kind) {
case SyntaxKind.CallExpression:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportDeclaration:
return decl as ImportDeclaration | ExportDeclaration | CallExpression;
case SyntaxKind.ExternalModuleReference:
return (decl as ExternalModuleReference).parent;
default:
Debug.assert(false);
}
Debug.assert(decl.kind === SyntaxKind.ExternalModuleReference);
return (decl as ExternalModuleReference).parent;
}
export interface ImportedSymbol {
@@ -537,7 +531,10 @@ namespace ts.FindAllReferences {
return symbol.name;
}
const name = forEach(symbol.declarations, ({ name }) => name && name.kind === SyntaxKind.Identifier && name.text);
const name = forEach(symbol.declarations, decl => {
const name = getNameOfDeclaration(decl);
return name && name.kind === SyntaxKind.Identifier && name.text;
});
Debug.assert(!!name);
return name;
}
+1 -2
View File
@@ -28,6 +28,7 @@ namespace ts.JsDoc {
"namespace",
"param",
"private",
"prop",
"property",
"public",
"requires",
@@ -38,8 +39,6 @@ namespace ts.JsDoc {
"throws",
"type",
"typedef",
"property",
"prop",
"version"
];
let jsDocTagNameCompletionEntries: CompletionEntry[];
+22 -17
View File
@@ -52,7 +52,7 @@ namespace ts.NavigateTo {
rawItems = filter(rawItems, item => {
const decl = item.declaration;
if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) {
const importer = checker.getSymbolAtLocation(decl.name);
const importer = checker.getSymbolAtLocation((decl as NamedDeclaration).name);
const imported = checker.getAliasedSymbol(importer);
return importer.name !== imported.name;
}
@@ -97,17 +97,20 @@ namespace ts.NavigateTo {
}
function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) {
if (declaration && declaration.name) {
const text = getTextOfIdentifierOrLiteral(declaration.name);
if (text !== undefined) {
containers.unshift(text);
}
else if (declaration.name.kind === SyntaxKind.ComputedPropertyName) {
return tryAddComputedPropertyName((<ComputedPropertyName>declaration.name).expression, containers, /*includeLastPortion*/ true);
}
else {
// Don't know how to add this.
return false;
if (declaration) {
const name = getNameOfDeclaration(declaration);
if (name) {
const text = getTextOfIdentifierOrLiteral(name);
if (text !== undefined) {
containers.unshift(text);
}
else if (name.kind === SyntaxKind.ComputedPropertyName) {
return tryAddComputedPropertyName((<ComputedPropertyName>name).expression, containers, /*includeLastPortion*/ true);
}
else {
// Don't know how to add this.
return false;
}
}
}
@@ -143,8 +146,9 @@ namespace ts.NavigateTo {
// First, if we started with a computed property name, then add all but the last
// portion into the container array.
if (declaration.name.kind === SyntaxKind.ComputedPropertyName) {
if (!tryAddComputedPropertyName((<ComputedPropertyName>declaration.name).expression, containers, /*includeLastPortion*/ false)) {
const name = getNameOfDeclaration(declaration);
if (name.kind === SyntaxKind.ComputedPropertyName) {
if (!tryAddComputedPropertyName((<ComputedPropertyName>name).expression, containers, /*includeLastPortion*/ false)) {
return undefined;
}
}
@@ -190,6 +194,7 @@ namespace ts.NavigateTo {
function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem {
const declaration = rawItem.declaration;
const container = <Declaration>getContainerNode(declaration);
const containerName = container && getNameOfDeclaration(container);
return {
name: rawItem.name,
kind: getNodeKind(declaration),
@@ -199,9 +204,9 @@ namespace ts.NavigateTo {
fileName: rawItem.fileName,
textSpan: createTextSpanFromNode(declaration),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: container && container.name ? (<Identifier>container.name).text : "",
containerKind: container && container.name ? getNodeKind(container) : ""
containerName: containerName ? (<Identifier>containerName).text : "",
containerKind: containerName ? getNodeKind(container) : ""
};
}
}
}
}
+6 -6
View File
@@ -279,8 +279,8 @@ namespace ts.NavigationBar {
function mergeChildren(children: NavigationBarNode[]): void {
const nameToItems = createMap<NavigationBarNode | NavigationBarNode[]>();
filterMutate(children, child => {
const decl = <Declaration>child.node;
const name = decl.name && nodeText(decl.name);
const declName = getNameOfDeclaration(<Declaration>child.node);
const name = declName && nodeText(declName);
if (!name) {
// Anonymous items are never merged.
return true;
@@ -378,9 +378,9 @@ namespace ts.NavigationBar {
return getModuleName(<ModuleDeclaration>node);
}
const decl = <Declaration>node;
if (decl.name) {
return getPropertyNameForPropertyNameNode(decl.name);
const declName = getNameOfDeclaration(<Declaration>node);
if (declName) {
return getPropertyNameForPropertyNameNode(declName);
}
switch (node.kind) {
case SyntaxKind.FunctionExpression:
@@ -399,7 +399,7 @@ namespace ts.NavigationBar {
return getModuleName(<ModuleDeclaration>node);
}
const name = (<Declaration>node).name;
const name = getNameOfDeclaration(<Declaration>node);
if (name) {
const text = nodeText(name);
if (text.length > 0) {
+5 -4
View File
@@ -578,14 +578,15 @@ namespace ts {
}
function getDeclarationName(declaration: Declaration) {
if (declaration.name) {
const result = getTextOfIdentifierOrLiteral(declaration.name);
const name = getNameOfDeclaration(declaration);
if (name) {
const result = getTextOfIdentifierOrLiteral(name);
if (result !== undefined) {
return result;
}
if (declaration.name.kind === SyntaxKind.ComputedPropertyName) {
const expr = (<ComputedPropertyName>declaration.name).expression;
if (name.kind === SyntaxKind.ComputedPropertyName) {
const expr = (<ComputedPropertyName>name).expression;
if (expr.kind === SyntaxKind.PropertyAccessExpression) {
return (<PropertyAccessExpression>expr).name.text;
}
+1 -163
View File
@@ -1,168 +1,6 @@
///<reference path='services.ts' />
/* @internal */
namespace ts.SignatureHelp {
// A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression
// or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference.
// To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it
// will return the generic identifier that started the expression (e.g. "foo" in "foo<any, |"). It is then up to the caller to ensure that this is a valid generic expression through
// looking up the type. The method will also keep track of the parameter index inside the expression.
// public static isInPartiallyWrittenTypeArgumentList(syntaxTree: TypeScript.SyntaxTree, position: number): any {
// let token = Syntax.findTokenOnLeft(syntaxTree.sourceUnit(), position, /*includeSkippedTokens*/ true);
// if (token && TypeScript.Syntax.hasAncestorOfKind(token, TypeScript.SyntaxKind.TypeParameterList)) {
// // We are in the wrong generic list. bail out
// return null;
// }
// let stack = 0;
// let argumentIndex = 0;
// whileLoop:
// while (token) {
// switch (token.kind()) {
// case TypeScript.SyntaxKind.LessThanToken:
// if (stack === 0) {
// // Found the beginning of the generic argument expression
// let lessThanToken = token;
// token = previousToken(token, /*includeSkippedTokens*/ true);
// if (!token || token.kind() !== TypeScript.SyntaxKind.IdentifierName) {
// break whileLoop;
// }
// // Found the name, return the data
// return {
// genericIdentifer: token,
// lessThanToken: lessThanToken,
// argumentIndex: argumentIndex
// };
// }
// else if (stack < 0) {
// // Seen one too many less than tokens, bail out
// break whileLoop;
// }
// else {
// stack--;
// }
// break;
// case TypeScript.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
// stack++;
// // Intentional fall through
// case TypeScript.SyntaxKind.GreaterThanToken:
// stack++;
// break;
// case TypeScript.SyntaxKind.CommaToken:
// if (stack === 0) {
// argumentIndex++;
// }
// break;
// case TypeScript.SyntaxKind.CloseBraceToken:
// // This can be object type, skip untill we find the matching open brace token
// let unmatchedOpenBraceTokens = 0;
// // Skip untill the matching open brace token
// token = SignatureInfoHelpers.moveBackUpTillMatchingTokenKind(token, TypeScript.SyntaxKind.CloseBraceToken, TypeScript.SyntaxKind.OpenBraceToken);
// if (!token) {
// // No matching token was found. bail out
// break whileLoop;
// }
// break;
// case TypeScript.SyntaxKind.EqualsGreaterThanToken:
// // This can be a function type or a constructor type. In either case, we want to skip the function definition
// token = previousToken(token, /*includeSkippedTokens*/ true);
// if (token && token.kind() === TypeScript.SyntaxKind.CloseParenToken) {
// // Skip untill the matching open paren token
// token = SignatureInfoHelpers.moveBackUpTillMatchingTokenKind(token, TypeScript.SyntaxKind.CloseParenToken, TypeScript.SyntaxKind.OpenParenToken);
// if (token && token.kind() === TypeScript.SyntaxKind.GreaterThanToken) {
// // Another generic type argument list, skip it\
// token = SignatureInfoHelpers.moveBackUpTillMatchingTokenKind(token, TypeScript.SyntaxKind.GreaterThanToken, TypeScript.SyntaxKind.LessThanToken);
// }
// if (token && token.kind() === TypeScript.SyntaxKind.NewKeyword) {
// // In case this was a constructor type, skip the new keyword
// token = previousToken(token, /*includeSkippedTokens*/ true);
// }
// if (!token) {
// // No matching token was found. bail out
// break whileLoop;
// }
// }
// else {
// // This is not a function type. exit the main loop
// break whileLoop;
// }
// break;
// case TypeScript.SyntaxKind.IdentifierName:
// case TypeScript.SyntaxKind.AnyKeyword:
// case TypeScript.SyntaxKind.NumberKeyword:
// case TypeScript.SyntaxKind.StringKeyword:
// case TypeScript.SyntaxKind.VoidKeyword:
// case TypeScript.SyntaxKind.BooleanKeyword:
// case TypeScript.SyntaxKind.DotToken:
// case TypeScript.SyntaxKind.OpenBracketToken:
// case TypeScript.SyntaxKind.CloseBracketToken:
// // Valid tokens in a type name. Skip.
// break;
// default:
// break whileLoop;
// }
// token = previousToken(token, /*includeSkippedTokens*/ true);
// }
// return null;
// }
// private static moveBackUpTillMatchingTokenKind(token: TypeScript.ISyntaxToken, tokenKind: TypeScript.SyntaxKind, matchingTokenKind: TypeScript.SyntaxKind): TypeScript.ISyntaxToken {
// if (!token || token.kind() !== tokenKind) {
// throw TypeScript.Errors.invalidOperation();
// }
// // Skip the current token
// token = previousToken(token, /*includeSkippedTokens*/ true);
// let stack = 0;
// while (token) {
// if (token.kind() === matchingTokenKind) {
// if (stack === 0) {
// // Found the matching token, return
// return token;
// }
// else if (stack < 0) {
// // tokens overlapped.. bail out.
// break;
// }
// else {
// stack--;
// }
// }
// else if (token.kind() === tokenKind) {
// stack++;
// }
// // Move back
// token = previousToken(token, /*includeSkippedTokens*/ true);
// }
// // Did not find matching token
// return null;
// }
const emptyArray: any[] = [];
export const enum ArgumentListKind {
@@ -262,7 +100,7 @@ namespace ts.SignatureHelp {
* in the argument of an invocation; returns undefined otherwise.
*/
export function getImmediatelyContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile): ArgumentListInfo {
if (node.parent.kind === SyntaxKind.CallExpression || node.parent.kind === SyntaxKind.NewExpression) {
if (isCallOrNewExpression(node.parent)) {
const callExpression = <CallExpression>node.parent;
// There are 3 cases to handle:
// 1. The token introduces a list, and should begin a signature help session
+1 -1
View File
@@ -120,7 +120,7 @@ namespace ts.SymbolDisplay {
// try get the call/construct signature from the type if it matches
let callExpressionLike: CallExpression | NewExpression | JsxOpeningLikeElement;
if (location.kind === SyntaxKind.CallExpression || location.kind === SyntaxKind.NewExpression) {
if (isCallOrNewExpression(location)) {
callExpressionLike = <CallExpression | NewExpression>location;
}
else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) {
+2 -1
View File
@@ -82,6 +82,7 @@
"formatting/tokenRange.ts",
"codeFixProvider.ts",
"codefixes/fixAddMissingMember.ts",
"codefixes/fixSpelling.ts",
"codefixes/fixExtendsInterfaceBecomesImplements.ts",
"codefixes/fixClassIncorrectlyImplementsInterface.ts",
"codefixes/fixClassDoesntImplementInheritedAbstractMember.ts",
@@ -94,4 +95,4 @@
"codefixes/unusedIdentifierFixes.ts",
"codefixes/disableJsDiagnostics.ts"
]
}
}
+1 -1
View File
@@ -238,7 +238,7 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ModuleDeclaration:
return (<Declaration>node.parent).name === node;
return getNameOfDeclaration(<Declaration>node.parent) === node;
case SyntaxKind.ElementAccessExpression:
return (<ElementAccessExpression>node.parent).argumentExpression === node;
case SyntaxKind.ComputedPropertyName:
@@ -0,0 +1,49 @@
{
"kind": "JSDocComment",
"pos": 0,
"end": 44,
"tags": {
"0": {
"kind": "JSDocParameterTag",
"pos": 8,
"end": 27,
"atToken": {
"kind": "AtToken",
"pos": 8,
"end": 9
},
"tagName": {
"kind": "Identifier",
"pos": 9,
"end": 12,
"text": "arg"
},
"typeExpression": {
"kind": "JSDocTypeExpression",
"pos": 13,
"end": 21,
"type": {
"kind": "NumberKeyword",
"pos": 14,
"end": 20
}
},
"postParameterName": {
"kind": "Identifier",
"pos": 22,
"end": 27,
"text": "name1"
},
"parameterName": {
"kind": "Identifier",
"pos": 22,
"end": 27,
"text": "name1"
},
"comment": "Description"
},
"length": 1,
"pos": 8,
"end": 27
}
}
@@ -0,0 +1,49 @@
{
"kind": "JSDocComment",
"pos": 0,
"end": 49,
"tags": {
"0": {
"kind": "JSDocParameterTag",
"pos": 8,
"end": 32,
"atToken": {
"kind": "AtToken",
"pos": 8,
"end": 9
},
"tagName": {
"kind": "Identifier",
"pos": 9,
"end": 17,
"text": "argument"
},
"typeExpression": {
"kind": "JSDocTypeExpression",
"pos": 18,
"end": 26,
"type": {
"kind": "NumberKeyword",
"pos": 19,
"end": 25
}
},
"postParameterName": {
"kind": "Identifier",
"pos": 27,
"end": 32,
"text": "name1"
},
"parameterName": {
"kind": "Identifier",
"pos": 27,
"end": 32,
"text": "name1"
},
"comment": "Description"
},
"length": 1,
"pos": 8,
"end": 32
}
}
@@ -1,5 +1,5 @@
tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(28,13): error TS2339: Property 'fn2' does not exist on type 'typeof A'.
tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2339: Property 'fng2' does not exist on type 'typeof A'.
tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts(29,14): error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'?
==== tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAndNonExportedFunctions.ts (2 errors) ====
@@ -35,4 +35,4 @@ tests/cases/conformance/internalModules/exportDeclarations/ModuleWithExportedAnd
!!! error TS2339: Property 'fn2' does not exist on type 'typeof A'.
var fng2 = A.fng2;
~~~~
!!! error TS2339: Property 'fng2' does not exist on type 'typeof A'.
!!! error TS2551: Property 'fng2' does not exist on type 'typeof A'. Did you mean 'fng'?
@@ -1,4 +1,4 @@
tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2339: Property 'methodA' does not exist on type 'B'.
tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2551: Property 'methodA' does not exist on type 'B'. Did you mean 'methodB'?
==== tests/cases/compiler/anonymousClassExpression2.ts (1 errors) ====
@@ -16,7 +16,7 @@ tests/cases/compiler/anonymousClassExpression2.ts(13,18): error TS2339: Property
methodB() {
this.methodA; // error
~~~~~~~
!!! error TS2339: Property 'methodA' does not exist on type 'B'.
!!! error TS2551: Property 'methodA' does not exist on type 'B'. Did you mean 'methodB'?
this.methodB; // ok
}
}
@@ -1,5 +1,5 @@
tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,5): error TS2304: Cannot find name 'c'.
tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS2304: Cannot find name 'tupel'.
tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS2552: Cannot find name 'tupel'. Did you mean 'tuple'?
==== tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts (2 errors) ====
@@ -8,4 +8,4 @@ tests/cases/compiler/assignmentRestElementWithErrorSourceType.ts(2,10): error TS
~
!!! error TS2304: Cannot find name 'c'.
~~~~~
!!! error TS2304: Cannot find name 'tupel'.
!!! error TS2552: Cannot find name 'tupel'. Did you mean 'tuple'?
@@ -1,9 +1,9 @@
tests/cases/compiler/autoLift2.ts(5,14): error TS2339: Property 'foo' does not exist on type 'A'.
tests/cases/compiler/autoLift2.ts(5,17): error TS1005: ';' expected.
tests/cases/compiler/autoLift2.ts(5,19): error TS2304: Cannot find name 'any'.
tests/cases/compiler/autoLift2.ts(5,19): error TS2693: 'any' only refers to a type, but is being used as a value here.
tests/cases/compiler/autoLift2.ts(6,14): error TS2339: Property 'bar' does not exist on type 'A'.
tests/cases/compiler/autoLift2.ts(6,17): error TS1005: ';' expected.
tests/cases/compiler/autoLift2.ts(6,19): error TS2304: Cannot find name 'any'.
tests/cases/compiler/autoLift2.ts(6,19): error TS2693: 'any' only refers to a type, but is being used as a value here.
tests/cases/compiler/autoLift2.ts(12,11): error TS2339: Property 'foo' does not exist on type 'A'.
tests/cases/compiler/autoLift2.ts(14,11): error TS2339: Property 'bar' does not exist on type 'A'.
tests/cases/compiler/autoLift2.ts(16,33): error TS2339: Property 'foo' does not exist on type 'A'.
@@ -21,14 +21,14 @@ tests/cases/compiler/autoLift2.ts(18,33): error TS2339: Property 'bar' does not
~
!!! error TS1005: ';' expected.
~~~
!!! error TS2304: Cannot find name 'any'.
!!! error TS2693: 'any' only refers to a type, but is being used as a value here.
this.bar: any;
~~~
!!! error TS2339: Property 'bar' does not exist on type 'A'.
~
!!! error TS1005: ';' expected.
~~~
!!! error TS2304: Cannot find name 'any'.
!!! error TS2693: 'any' only refers to a type, but is being used as a value here.
}
@@ -1,10 +1,10 @@
tests/cases/compiler/badArrayIndex.ts(1,15): error TS2304: Cannot find name 'number'.
tests/cases/compiler/badArrayIndex.ts(1,15): error TS2693: 'number' only refers to a type, but is being used as a value here.
tests/cases/compiler/badArrayIndex.ts(1,22): error TS1109: Expression expected.
==== tests/cases/compiler/badArrayIndex.ts (2 errors) ====
var results = number[];
~~~~~~
!!! error TS2304: Cannot find name 'number'.
!!! error TS2693: 'number' only refers to a type, but is being used as a value here.
~
!!! error TS1109: Expression expected.
@@ -1,4 +1,4 @@
tests/cases/compiler/baseCheck.ts(9,18): error TS2304: Cannot find name 'loc'.
tests/cases/compiler/baseCheck.ts(9,18): error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'?
tests/cases/compiler/baseCheck.ts(17,53): error TS2346: Supplied parameters do not match any signature of call target.
tests/cases/compiler/baseCheck.ts(17,59): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class.
tests/cases/compiler/baseCheck.ts(18,62): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class.
@@ -20,7 +20,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'.
constructor(x: number) {
super(0, loc);
~~~
!!! error TS2304: Cannot find name 'loc'.
!!! error TS2552: Cannot find name 'loc'. Did you mean 'ELoc'?
}
m() {
+4 -4
View File
@@ -1,13 +1,13 @@
tests/cases/compiler/bases.ts(7,14): error TS2339: Property 'y' does not exist on type 'B'.
tests/cases/compiler/bases.ts(7,15): error TS1005: ';' expected.
tests/cases/compiler/bases.ts(7,17): error TS2304: Cannot find name 'any'.
tests/cases/compiler/bases.ts(7,17): error TS2693: 'any' only refers to a type, but is being used as a value here.
tests/cases/compiler/bases.ts(11,7): error TS2420: Class 'C' incorrectly implements interface 'I'.
Property 'x' is missing in type 'C'.
tests/cases/compiler/bases.ts(12,5): error TS2377: Constructors for derived classes must contain a 'super' call.
tests/cases/compiler/bases.ts(13,9): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class.
tests/cases/compiler/bases.ts(13,14): error TS2339: Property 'x' does not exist on type 'C'.
tests/cases/compiler/bases.ts(13,15): error TS1005: ';' expected.
tests/cases/compiler/bases.ts(13,17): error TS2304: Cannot find name 'any'.
tests/cases/compiler/bases.ts(13,17): error TS2693: 'any' only refers to a type, but is being used as a value here.
tests/cases/compiler/bases.ts(17,9): error TS2339: Property 'x' does not exist on type 'C'.
tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist on type 'C'.
@@ -25,7 +25,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o
~
!!! error TS1005: ';' expected.
~~~
!!! error TS2304: Cannot find name 'any'.
!!! error TS2693: 'any' only refers to a type, but is being used as a value here.
}
}
@@ -44,7 +44,7 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o
~
!!! error TS1005: ';' expected.
~~~
!!! error TS2304: Cannot find name 'any'.
!!! error TS2693: 'any' only refers to a type, but is being used as a value here.
}
~~~~~
!!! error TS2377: Constructors for derived classes must contain a 'super' call.
@@ -1,10 +1,16 @@
tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,1): error TS2304: Cannot find name 'Foo'.
tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,5): error TS2304: Cannot find name 'a'.
tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,7): error TS1110: Type expected.
tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts(1,8): error TS2304: Cannot find name 'b'.
==== tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts (2 errors) ====
==== tests/cases/compiler/callExpressionWithMissingTypeArgument1.ts (4 errors) ====
Foo<a,,b>();
~~~
!!! error TS2304: Cannot find name 'Foo'.
~
!!! error TS2304: Cannot find name 'a'.
~
!!! error TS1110: Type expected.
!!! error TS1110: Type expected.
~
!!! error TS2304: Cannot find name 'b'.
@@ -1,7 +1,7 @@
tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2304: Cannot find name 'any'.
tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts(1,23): error TS2693: 'any' only refers to a type, but is being used as a value here.
==== tests/cases/compiler/cannotInvokeNewOnIndexExpression.ts (1 errors) ====
var test: any[] = new any[1];
~~~
!!! error TS2304: Cannot find name 'any'.
!!! error TS2693: 'any' only refers to a type, but is being used as a value here.
@@ -0,0 +1,17 @@
//// [capturedVarInLoop.ts]
for (var i = 0; i < 10; i++) {
var str = 'x', len = str.length;
let lambda1 = (y) => { };
let lambda2 = () => lambda1(len);
}
//// [capturedVarInLoop.js]
var _loop_1 = function () {
str = 'x', len = str.length;
var lambda1 = function (y) { };
var lambda2 = function () { return lambda1(len); };
};
var str, len;
for (var i = 0; i < 10; i++) {
_loop_1();
}
@@ -0,0 +1,22 @@
=== tests/cases/compiler/capturedVarInLoop.ts ===
for (var i = 0; i < 10; i++) {
>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8))
>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8))
>i : Symbol(i, Decl(capturedVarInLoop.ts, 0, 8))
var str = 'x', len = str.length;
>str : Symbol(str, Decl(capturedVarInLoop.ts, 1, 7))
>len : Symbol(len, Decl(capturedVarInLoop.ts, 1, 18))
>str.length : Symbol(String.length, Decl(lib.d.ts, --, --))
>str : Symbol(str, Decl(capturedVarInLoop.ts, 1, 7))
>length : Symbol(String.length, Decl(lib.d.ts, --, --))
let lambda1 = (y) => { };
>lambda1 : Symbol(lambda1, Decl(capturedVarInLoop.ts, 2, 7))
>y : Symbol(y, Decl(capturedVarInLoop.ts, 2, 19))
let lambda2 = () => lambda1(len);
>lambda2 : Symbol(lambda2, Decl(capturedVarInLoop.ts, 3, 7))
>lambda1 : Symbol(lambda1, Decl(capturedVarInLoop.ts, 2, 7))
>len : Symbol(len, Decl(capturedVarInLoop.ts, 1, 18))
}
@@ -0,0 +1,30 @@
=== tests/cases/compiler/capturedVarInLoop.ts ===
for (var i = 0; i < 10; i++) {
>i : number
>0 : 0
>i < 10 : boolean
>i : number
>10 : 10
>i++ : number
>i : number
var str = 'x', len = str.length;
>str : string
>'x' : "x"
>len : number
>str.length : number
>str : string
>length : number
let lambda1 = (y) => { };
>lambda1 : (y: any) => void
>(y) => { } : (y: any) => void
>y : any
let lambda2 = () => lambda1(len);
>lambda2 : () => void
>() => lambda1(len) : () => void
>lambda1(len) : void
>lambda1 : (y: any) => void
>len : number
}
@@ -0,0 +1,29 @@
tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'.
tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type.
tests/cases/compiler/weird.js(6,13): error TS2346: Supplied parameters do not match any signature of call target.
tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly has an 'any' type.
==== tests/cases/compiler/weird.js (4 errors) ====
someFunction(function(BaseClass) {
~~~~~~~~~~~~
!!! error TS2304: Cannot find name 'someFunction'.
~~~~~~~~~
!!! error TS7006: Parameter 'BaseClass' implicitly has an 'any' type.
'use strict';
const DEFAULT_MESSAGE = "nop!";
class Hello extends BaseClass {
constructor() {
super();
~~~~~~~
!!! error TS2346: Supplied parameters do not match any signature of call target.
this.foo = "bar";
}
_render(error) {
~~~~~
!!! error TS7006: Parameter 'error' implicitly has an 'any' type.
const message = error.message || DEFAULT_MESSAGE;
}
}
});
@@ -0,0 +1,17 @@
=== tests/cases/compiler/weird.js ===
someFunction(function(BaseClass) {
>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22))
class Hello extends BaseClass {
>Hello : Symbol(Hello, Decl(weird.js, 0, 34))
>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22))
constructor() {
this.foo = "bar";
>this.foo : Symbol(Hello.foo, Decl(weird.js, 2, 17))
>this : Symbol(Hello, Decl(weird.js, 0, 34))
>foo : Symbol(Hello.foo, Decl(weird.js, 2, 17))
}
}
});
@@ -0,0 +1,22 @@
=== tests/cases/compiler/weird.js ===
someFunction(function(BaseClass) {
>someFunction(function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }}) : any
>someFunction : any
>function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }} : (BaseClass: any) => void
>BaseClass : any
class Hello extends BaseClass {
>Hello : Hello
>BaseClass : any
constructor() {
this.foo = "bar";
>this.foo = "bar" : "bar"
>this.foo : string
>this : this
>foo : string
>"bar" : "bar"
}
}
});
@@ -1,4 +1,4 @@
tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property.
tests/cases/compiler/a.js(14,10): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property.
==== tests/cases/compiler/a.js (1 errors) ====
@@ -16,7 +16,7 @@ tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member
constructor() {
super();
this.foo = () => 3;
~~~~~~~~~~~~~~~~~~
~~~
!!! error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property.
}
}
@@ -0,0 +1,76 @@
//// [file.tsx]
import React = require('react');
interface ButtonProp {
a: number,
b: string,
children: Button;
}
class Button extends React.Component<ButtonProp, any> {
render() {
let condition: boolean;
if (condition) {
return <InnerButton {...this.props} />
}
else {
return (<InnerButton {...this.props} >
<div>Hello World</div>
</InnerButton>);
}
}
}
interface InnerButtonProp {
a: number
}
class InnerButton extends React.Component<InnerButtonProp, any> {
render() {
return (<button>Hello</button>);
}
}
//// [file.jsx]
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var React = require("react");
var Button = (function (_super) {
__extends(Button, _super);
function Button() {
return _super !== null && _super.apply(this, arguments) || this;
}
Button.prototype.render = function () {
var condition;
if (condition) {
return <InnerButton {...this.props}/>;
}
else {
return (<InnerButton {...this.props}>
<div>Hello World</div>
</InnerButton>);
}
};
return Button;
}(React.Component));
var InnerButton = (function (_super) {
__extends(InnerButton, _super);
function InnerButton() {
return _super !== null && _super.apply(this, arguments) || this;
}
InnerButton.prototype.render = function () {
return (<button>Hello</button>);
};
return InnerButton;
}(React.Component));
@@ -0,0 +1,80 @@
=== tests/cases/conformance/jsx/file.tsx ===
import React = require('react');
>React : Symbol(React, Decl(file.tsx, 0, 0))
interface ButtonProp {
>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32))
a: number,
>a : Symbol(ButtonProp.a, Decl(file.tsx, 2, 22))
b: string,
>b : Symbol(ButtonProp.b, Decl(file.tsx, 3, 14))
children: Button;
>children : Symbol(ButtonProp.children, Decl(file.tsx, 4, 14))
>Button : Symbol(Button, Decl(file.tsx, 6, 1))
}
class Button extends React.Component<ButtonProp, any> {
>Button : Symbol(Button, Decl(file.tsx, 6, 1))
>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55))
>React : Symbol(React, Decl(file.tsx, 0, 0))
>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55))
>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32))
render() {
>render : Symbol(Button.render, Decl(file.tsx, 8, 55))
let condition: boolean;
>condition : Symbol(condition, Decl(file.tsx, 10, 5))
if (condition) {
>condition : Symbol(condition, Decl(file.tsx, 10, 5))
return <InnerButton {...this.props} />
>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1))
>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37))
>this : Symbol(Button, Decl(file.tsx, 6, 1))
>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37))
}
else {
return (<InnerButton {...this.props} >
>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1))
>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37))
>this : Symbol(Button, Decl(file.tsx, 6, 1))
>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37))
<div>Hello World</div>
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45))
>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45))
</InnerButton>);
>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1))
}
}
}
interface InnerButtonProp {
>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1))
a: number
>a : Symbol(InnerButtonProp.a, Decl(file.tsx, 22, 27))
}
class InnerButton extends React.Component<InnerButtonProp, any> {
>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1))
>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55))
>React : Symbol(React, Decl(file.tsx, 0, 0))
>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55))
>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1))
render() {
>render : Symbol(InnerButton.render, Decl(file.tsx, 26, 65))
return (<button>Hello</button>);
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
}
}
@@ -0,0 +1,86 @@
=== tests/cases/conformance/jsx/file.tsx ===
import React = require('react');
>React : typeof React
interface ButtonProp {
>ButtonProp : ButtonProp
a: number,
>a : number
b: string,
>b : string
children: Button;
>children : Button
>Button : Button
}
class Button extends React.Component<ButtonProp, any> {
>Button : Button
>React.Component : React.Component<ButtonProp, any>
>React : typeof React
>Component : typeof React.Component
>ButtonProp : ButtonProp
render() {
>render : () => JSX.Element
let condition: boolean;
>condition : boolean
if (condition) {
>condition : boolean
return <InnerButton {...this.props} />
><InnerButton {...this.props} /> : JSX.Element
>InnerButton : typeof InnerButton
>this.props : ButtonProp & { children?: React.ReactNode; }
>this : this
>props : ButtonProp & { children?: React.ReactNode; }
}
else {
return (<InnerButton {...this.props} >
>(<InnerButton {...this.props} > <div>Hello World</div> </InnerButton>) : JSX.Element
><InnerButton {...this.props} > <div>Hello World</div> </InnerButton> : JSX.Element
>InnerButton : typeof InnerButton
>this.props : ButtonProp & { children?: React.ReactNode; }
>this : this
>props : ButtonProp & { children?: React.ReactNode; }
<div>Hello World</div>
><div>Hello World</div> : JSX.Element
>div : any
>div : any
</InnerButton>);
>InnerButton : typeof InnerButton
}
}
}
interface InnerButtonProp {
>InnerButtonProp : InnerButtonProp
a: number
>a : number
}
class InnerButton extends React.Component<InnerButtonProp, any> {
>InnerButton : InnerButton
>React.Component : React.Component<InnerButtonProp, any>
>React : typeof React
>Component : typeof React.Component
>InnerButtonProp : InnerButtonProp
render() {
>render : () => JSX.Element
return (<button>Hello</button>);
>(<button>Hello</button>) : JSX.Element
><button>Hello</button> : JSX.Element
>button : any
>button : any
}
}
@@ -0,0 +1,33 @@
tests/cases/conformance/jsx/file.tsx(12,30): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten.
==== tests/cases/conformance/jsx/file.tsx (1 errors) ====
import React = require('react');
interface ButtonProp {
a: number,
b: string,
children: Button;
}
class Button extends React.Component<ButtonProp, any> {
render() {
// Error children are specified twice
return (<InnerButton {...this.props} children="hi">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten.
<div>Hello World</div>
</InnerButton>);
}
}
interface InnerButtonProp {
a: number
}
class InnerButton extends React.Component<InnerButtonProp, any> {
render() {
return (<button>Hello</button>);
}
}
@@ -0,0 +1,66 @@
//// [file.tsx]
import React = require('react');
interface ButtonProp {
a: number,
b: string,
children: Button;
}
class Button extends React.Component<ButtonProp, any> {
render() {
// Error children are specified twice
return (<InnerButton {...this.props} children="hi">
<div>Hello World</div>
</InnerButton>);
}
}
interface InnerButtonProp {
a: number
}
class InnerButton extends React.Component<InnerButtonProp, any> {
render() {
return (<button>Hello</button>);
}
}
//// [file.jsx]
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var React = require("react");
var Button = (function (_super) {
__extends(Button, _super);
function Button() {
return _super !== null && _super.apply(this, arguments) || this;
}
Button.prototype.render = function () {
// Error children are specified twice
return (<InnerButton {...this.props} children="hi">
<div>Hello World</div>
</InnerButton>);
};
return Button;
}(React.Component));
var InnerButton = (function (_super) {
__extends(InnerButton, _super);
function InnerButton() {
return _super !== null && _super.apply(this, arguments) || this;
}
InnerButton.prototype.render = function () {
return (<button>Hello</button>);
};
return InnerButton;
}(React.Component));
@@ -2,7 +2,6 @@ tests/cases/conformance/jsx/file.tsx(14,15): error TS2322: Type '{ a: 10; b: "hi
Type '{ a: 10; b: "hi"; }' is not assignable to type 'Prop'.
Property 'children' is missing in type '{ a: 10; b: "hi"; }'.
tests/cases/conformance/jsx/file.tsx(17,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten.
tests/cases/conformance/jsx/file.tsx(25,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten.
tests/cases/conformance/jsx/file.tsx(31,11): error TS2322: Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'IntrinsicAttributes & Prop'.
Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'Prop'.
Types of property 'children' are incompatible.
@@ -29,7 +28,7 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi
Property 'type' is missing in type 'Element[]'.
==== tests/cases/conformance/jsx/file.tsx (7 errors) ====
==== tests/cases/conformance/jsx/file.tsx (6 errors) ====
import React = require('react');
interface Prop {
@@ -61,8 +60,6 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi
}
let k1 =
<Comp a={10} b="hi" {...o} >
~~~~~~~~~~~~~~~~~~~~
!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten.
hi hi hi!
</Comp>;
@@ -1,4 +1,4 @@
tests/cases/conformance/jsx/file.tsx(24,28): error TS2339: Property 'NAme' does not exist on type 'IUser'.
tests/cases/conformance/jsx/file.tsx(24,28): error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'?
tests/cases/conformance/jsx/file.tsx(32,9): error TS2322: Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<FetchUser> & IFetchUserProps & { children?: ReactNode; }'.
Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IFetchUserProps'.
Types of property 'children' are incompatible.
@@ -32,7 +32,7 @@ tests/cases/conformance/jsx/file.tsx(32,9): error TS2322: Type '{ children: ((us
{ user => (
<h1>{ user.NAme }</h1>
~~~~
!!! error TS2339: Property 'NAme' does not exist on type 'IUser'.
!!! error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'?
) }
</FetchUser>
);
@@ -89,7 +89,7 @@ declare class C {
}
declare class D {
x: number;
private constructor(x);
private constructor();
}
declare class E {
x: number;
@@ -135,7 +135,7 @@ declare class BaseB {
}
declare class BaseC {
x: number;
private constructor(x);
private constructor();
createInstance(): void;
static staticInstance(): void;
}
@@ -90,7 +90,7 @@ declare class Baz {
}
declare class Qux {
x: number;
private constructor(x);
private constructor();
}
declare let a: typeof Foo;
declare let b: typeof Baz;
@@ -59,7 +59,7 @@ var D = (function () {
declare class A {
constructor(a: boolean);
protected constructor(a: number);
private constructor(a);
private constructor();
}
declare class B {
protected constructor(a: number);
@@ -1,11 +1,11 @@
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2304: Cannot find name 'number'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2304: Cannot find name 'string'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2304: Cannot find name 'boolean'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(3,17): error TS2693: 'number' only refers to a type, but is being used as a value here.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(4,18): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(5,18): error TS2693: 'boolean' only refers to a type, but is being used as a value here.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(6,18): error TS2304: Cannot find name 'Void'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(7,19): error TS1109: Expression expected.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(8,18): error TS2304: Cannot find name 'Null'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(10,18): error TS2507: Type 'undefined' is not a constructor function type.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2304: Cannot find name 'Undefined'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2552: Cannot find name 'Undefined'. Did you mean 'undefined'?
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(14,18): error TS2507: Type 'typeof E' is not a constructor function type.
@@ -14,13 +14,13 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla
class C extends number { }
~~~~~~
!!! error TS2304: Cannot find name 'number'.
!!! error TS2693: 'number' only refers to a type, but is being used as a value here.
class C2 extends string { }
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
class C3 extends boolean { }
~~~~~~~
!!! error TS2304: Cannot find name 'boolean'.
!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here.
class C4 extends Void { }
~~~~
!!! error TS2304: Cannot find name 'Void'.
@@ -36,7 +36,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla
!!! error TS2507: Type 'undefined' is not a constructor function type.
class C7 extends Undefined { }
~~~~~~~~~
!!! error TS2304: Cannot find name 'Undefined'.
!!! error TS2552: Cannot find name 'Undefined'. Did you mean 'undefined'?
enum E { A }
class C8 extends E { }
@@ -1,6 +1,6 @@
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(4,17): error TS2689: Cannot extend an interface 'I'. Did you mean 'implements'?
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,18): error TS2507: Type '{ foo: any; }' is not a constructor function type.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2304: Cannot find name 'string'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,31): error TS1005: ',' expected.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(8,18): error TS2507: Type '{ foo: string; }' is not a constructor function type.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(11,18): error TS2507: Type 'typeof M' is not a constructor function type.
@@ -20,7 +20,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla
~~~~~~~~~~~~~~~~
!!! error TS2507: Type '{ foo: any; }' is not a constructor function type.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~
!!! error TS1005: ',' expected.
var x: { foo: string; }
@@ -1,5 +1,5 @@
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,18): error TS2507: Type '{ foo: any; }' is not a constructor function type.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2304: Cannot find name 'string'.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,31): error TS1005: ',' expected.
tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(3,18): error TS2507: Type 'undefined[]' is not a constructor function type.
@@ -9,7 +9,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla
~~~~~~~~~~~~~~~~
!!! error TS2507: Type '{ foo: any; }' is not a constructor function type.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~
!!! error TS1005: ',' expected.
@@ -2,7 +2,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,11): error TS1146: D
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,12): error TS1005: '=' expected.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,14): error TS2304: Cannot find name 'name'.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,18): error TS1005: ']' expected.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2304: Cannot find name 'string'.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,25): error TS1005: ',' expected.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,26): error TS1136: Property assignment expected.
tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: Cannot find name 'VariableDeclaration'.
@@ -20,7 +20,7 @@ tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: C
~
!!! error TS1005: ']' expected.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~
!!! error TS1005: ',' expected.
~
@@ -13,9 +13,6 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(30,24): error TS1210:
tests/cases/compiler/collisionArgumentsClassConstructor.ts(31,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(35,24): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(36,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(41,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(44,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(47,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(51,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(52,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(53,25): error TS2396: Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.
@@ -30,15 +27,9 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(67,17): error TS1210:
tests/cases/compiler/collisionArgumentsClassConstructor.ts(68,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(69,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(70,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(75,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(76,31): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(79,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(80,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(84,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
==== tests/cases/compiler/collisionArgumentsClassConstructor.ts (38 errors) ====
==== tests/cases/compiler/collisionArgumentsClassConstructor.ts (29 errors) ====
// Constructors
class c1 {
constructor(i: number, ...arguments) { // error
@@ -110,18 +101,12 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210:
declare class c4 {
constructor(i: number, ...arguments); // No error - no code gen
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
declare class c42 {
constructor(arguments: number, ...rest); // No error - no code gen
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
declare class c4NoError {
constructor(arguments: number); // no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
class c5 {
@@ -178,26 +163,14 @@ tests/cases/compiler/collisionArgumentsClassConstructor.ts(85,17): error TS1210:
declare class c6 {
constructor(i: number, ...arguments); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
constructor(i: string, ...arguments); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
declare class c62 {
constructor(arguments: number, ...rest); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
constructor(arguments: string, ...rest); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
declare class c6NoError {
constructor(arguments: number); // no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
constructor(arguments: string); // no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
@@ -20,20 +20,11 @@ tests/cases/compiler/collisionArgumentsClassMethod.ts(21,22): error TS1210: Inva
tests/cases/compiler/collisionArgumentsClassMethod.ts(22,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(23,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(24,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(29,30): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(30,17): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(31,23): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(33,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(34,29): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(35,16): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(36,16): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(37,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(38,22): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(43,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
tests/cases/compiler/collisionArgumentsClassMethod.ts(46,13): error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
==== tests/cases/compiler/collisionArgumentsClassMethod.ts (33 errors) ====
==== tests/cases/compiler/collisionArgumentsClassMethod.ts (24 errors) ====
class c1 {
public foo(i: number, ...arguments) { //arguments is error
~~~~~~~~~~~~
@@ -107,33 +98,15 @@ tests/cases/compiler/collisionArgumentsClassMethod.ts(46,13): error TS1210: Inva
declare class c2 {
public foo(i: number, ...arguments); // No error - no code gen
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public foo1(arguments: number, ...rest); // No error - no code gen
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public fooNoError(arguments: number); // No error - no code gen
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public f4(i: number, ...arguments); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public f4(i: string, ...arguments); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public f41(arguments: number, ...rest); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public f41(arguments: string, ...rest); // no codegen no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public f4NoError(arguments: number); // no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
public f4NoError(arguments: string); // no error
~~~~~~~~~
!!! error TS1210: Invalid use of 'arguments'. Class definitions are automatically in strict mode.
}
class c3 {
@@ -1,6 +1,6 @@
tests/cases/compiler/complicatedPrivacy.ts(11,24): error TS1054: A 'get' accessor cannot have parameters.
tests/cases/compiler/complicatedPrivacy.ts(35,5): error TS1170: A computed property name in a type literal must directly refer to a built-in symbol.
tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2304: Cannot find name 'number'.
tests/cases/compiler/complicatedPrivacy.ts(35,6): error TS2693: 'number' only refers to a type, but is being used as a value here.
tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo5' has no exported member 'i6'.
@@ -45,7 +45,7 @@ tests/cases/compiler/complicatedPrivacy.ts(73,55): error TS2694: Namespace 'mglo
~~~~~~~~
!!! error TS1170: A computed property name in a type literal must directly refer to a built-in symbol.
~~~~~~
!!! error TS2304: Cannot find name 'number'.
!!! error TS2693: 'number' only refers to a type, but is being used as a value here.
}) {
}
@@ -52,13 +52,13 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,9): error TS
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,16): error TS2304: Cannot find name 'method1'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2304: Cannot find name 'val'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,27): error TS1005: ',' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2304: Cannot find name 'number'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2693: 'number' only refers to a type, but is being used as a value here.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,36): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,9): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,16): error TS2304: Cannot find name 'method2'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,26): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(241,5): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2339: Property 'method1' does not exist on type 'B'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2551: Property 'method1' does not exist on type 'B'. Did you mean 'method2'?
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,9): error TS2390: Constructor implementation is missing.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,21): error TS2369: A parameter property is only allowed in a constructor implementation.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,44): error TS2369: A parameter property is only allowed in a constructor implementation.
@@ -67,14 +67,14 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,9): error TS
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2304: Cannot find name 'Overloads'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2304: Cannot find name 'value'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,31): error TS1005: ',' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,9): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2304: Cannot find name 'Overloads'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,27): error TS1135: Argument expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,33): error TS1005: '(' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,43): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,60): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,65): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,9): error TS2304: Cannot find name 'public'.
@@ -82,7 +82,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error T
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS2304: Cannot find name 'DefaultValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2304: Cannot find name 'value'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,35): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS1128: Declaration or statement expected.
@@ -435,7 +435,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
~
!!! error TS1005: ',' expected.
~~~~~~
!!! error TS2304: Cannot find name 'number'.
!!! error TS2693: 'number' only refers to a type, but is being used as a value here.
~
!!! error TS1005: ';' expected.
return val;
@@ -458,7 +458,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
public method2() {
return this.method1(2);
~~~~~~~
!!! error TS2339: Property 'method1' does not exist on type 'B'.
!!! error TS2551: Property 'method1' does not exist on type 'B'. Did you mean 'method2'?
}
}
@@ -486,7 +486,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
~
!!! error TS1005: ',' expected.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
public Overloads( while : string, ...rest: string[]) { &
~~~~~~
!!! error TS1128: Declaration or statement expected.
@@ -497,11 +497,11 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
~
!!! error TS1005: '(' expected.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~~~
!!! error TS1109: Expression expected.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~
!!! error TS1005: ';' expected.
~
@@ -519,7 +519,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS
~
!!! error TS1109: Expression expected.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~
!!! error TS1005: ';' expected.
}
@@ -1,15 +1,13 @@
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,24): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'.
Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,24): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,24): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,24): error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,25): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'.
Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'.
Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,43): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,36): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,65): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'.
tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (6 errors) ====
@@ -42,29 +40,27 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): err
const b0 = <MainButton {...{onClick: (k) => {console.log(k)}}} extra />; // k has type "left" | "right"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'.
!!! error TS2322: Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'.
const b2 = <MainButton onClick={(k)=>{console.log(k)}} extra />; // k has type "left" | "right"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'.
!!! error TS2322: Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'.
const b3 = <MainButton {...{goTo:"home"}} extra />; // goTo has type"home" | "contact"
~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
~~~~~
!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
const b4 = <MainButton goTo="home" extra />; // goTo has type "home" | "contact"
~~~~~~~~~~~~~~~~~
!!! error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
~~~~~
!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined }
const c1 = <NoOverload {...{onClick: (k) => {console.log(k)}}} extra />; // k has type any
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'.
!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'.
~~~~~
!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'.
export function NoOverload1(linkProps: LinkProps): JSX.Element { return undefined }
const d1 = <NoOverload1 {...{goTo:"home"}} extra />; // goTo has type "home" | "contact"
~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'.
!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
~~~~~
!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'.
@@ -0,0 +1,23 @@
//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences1.tsx] ////
//// [declaration.d.ts]
declare module "classnames";
//// [0.tsx]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps; // any
let k = <button {...buttonProps}>
<span className={cx('class1', { class2: true })} />
</button>;
//// [0.js]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps; // any
let k = React.createElement("button", Object.assign({}, buttonProps),
React.createElement("span", { className: cx('class1', { class2: true }) }));
@@ -0,0 +1,29 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
import * as React from "react";
>React : Symbol(React, Decl(0.tsx, 2, 6))
let buttonProps; // any
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
let k = <button {...buttonProps}>
>k : Symbol(k, Decl(0.tsx, 5, 3))
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
<span className={cx('class1', { class2: true })} />
>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51))
>className : Symbol(className, Decl(0.tsx, 6, 17))
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
>class2 : Symbol(class2, Decl(0.tsx, 6, 43))
</button>;
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,35 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : any
import * as React from "react";
>React : typeof React
let buttonProps; // any
>buttonProps : any
let k = <button {...buttonProps}>
>k : JSX.Element
><button {...buttonProps}> <span className={cx('class1', { class2: true })} /> </button> : JSX.Element
>button : any
>buttonProps : any
<span className={cx('class1', { class2: true })} />
><span className={cx('class1', { class2: true })} /> : JSX.Element
>span : any
>className : any
>cx('class1', { class2: true }) : any
>cx : any
>'class1' : "class1"
>{ class2: true } : { class2: boolean; }
>class2 : boolean
>true : true
</button>;
>button : any
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,23 @@
//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences2.tsx] ////
//// [declaration.d.ts]
declare module "classnames";
//// [0.tsx]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps : {[attributeName: string]: ''}
let k = <button {...buttonProps}>
<span className={cx('class1', { class2: true })} />
</button>;
//// [0.js]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps;
let k = React.createElement("button", Object.assign({}, buttonProps),
React.createElement("span", { className: cx('class1', { class2: true }) }));
@@ -0,0 +1,30 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
import * as React from "react";
>React : Symbol(React, Decl(0.tsx, 2, 6))
let buttonProps : {[attributeName: string]: ''}
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
>attributeName : Symbol(attributeName, Decl(0.tsx, 4, 20))
let k = <button {...buttonProps}>
>k : Symbol(k, Decl(0.tsx, 5, 3))
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
<span className={cx('class1', { class2: true })} />
>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51))
>className : Symbol(className, Decl(0.tsx, 6, 17))
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
>class2 : Symbol(class2, Decl(0.tsx, 6, 43))
</button>;
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,36 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : any
import * as React from "react";
>React : typeof React
let buttonProps : {[attributeName: string]: ''}
>buttonProps : { [attributeName: string]: ""; }
>attributeName : string
let k = <button {...buttonProps}>
>k : JSX.Element
><button {...buttonProps}> <span className={cx('class1', { class2: true })} /> </button> : JSX.Element
>button : any
>buttonProps : { [attributeName: string]: ""; }
<span className={cx('class1', { class2: true })} />
><span className={cx('class1', { class2: true })} /> : JSX.Element
>span : any
>className : any
>cx('class1', { class2: true }) : any
>cx : any
>'class1' : "class1"
>{ class2: true } : { class2: boolean; }
>class2 : boolean
>true : true
</button>;
>button : any
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,23 @@
//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences3.tsx] ////
//// [declaration.d.ts]
declare module "classnames";
//// [0.tsx]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps;
let k = <button {...buttonProps}>
<span className={cx('class1', { class2: true })} />
</button>;
//// [0.js]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps;
let k = React.createElement("button", Object.assign({}, buttonProps),
React.createElement("span", { className: cx('class1', { class2: true }) }));
@@ -0,0 +1,29 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
import * as React from "react";
>React : Symbol(React, Decl(0.tsx, 2, 6))
let buttonProps;
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
let k = <button {...buttonProps}>
>k : Symbol(k, Decl(0.tsx, 5, 3))
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
<span className={cx('class1', { class2: true })} />
>span : Symbol(JSX.IntrinsicElements.span, Decl(react.d.ts, 2460, 51))
>className : Symbol(className, Decl(0.tsx, 6, 17))
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
>class2 : Symbol(class2, Decl(0.tsx, 6, 43))
</button>;
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,35 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : any
import * as React from "react";
>React : typeof React
let buttonProps;
>buttonProps : any
let k = <button {...buttonProps}>
>k : JSX.Element
><button {...buttonProps}> <span className={cx('class1', { class2: true })} /> </button> : JSX.Element
>button : any
>buttonProps : undefined
<span className={cx('class1', { class2: true })} />
><span className={cx('class1', { class2: true })} /> : JSX.Element
>span : any
>className : any
>cx('class1', { class2: true }) : any
>cx : any
>'class1' : "class1"
>{ class2: true } : { class2: boolean; }
>class2 : boolean
>true : true
</button>;
>button : any
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,19 @@
//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences4.tsx] ////
//// [declaration.d.ts]
declare module "classnames";
//// [0.tsx]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps : {[attributeName: string]: ''}
let k = <button {...buttonProps} className={cx('class1', { class2: true })} />;
//// [0.js]
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
import * as React from "react";
let buttonProps;
let k = React.createElement("button", Object.assign({}, buttonProps, { className: cx('class1', { class2: true }) }));
@@ -0,0 +1,24 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
import * as React from "react";
>React : Symbol(React, Decl(0.tsx, 2, 6))
let buttonProps : {[attributeName: string]: ''}
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
>attributeName : Symbol(attributeName, Decl(0.tsx, 4, 20))
let k = <button {...buttonProps} className={cx('class1', { class2: true })} />;
>k : Symbol(k, Decl(0.tsx, 5, 3))
>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43))
>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3))
>className : Symbol(className, Decl(0.tsx, 5, 32))
>cx : Symbol(cx, Decl(0.tsx, 1, 6))
>class2 : Symbol(class2, Decl(0.tsx, 5, 58))
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -0,0 +1,29 @@
=== tests/cases/conformance/jsx/0.tsx ===
///<reference path="declaration.d.ts" />
import * as cx from 'classnames';
>cx : any
import * as React from "react";
>React : typeof React
let buttonProps : {[attributeName: string]: ''}
>buttonProps : { [attributeName: string]: ""; }
>attributeName : string
let k = <button {...buttonProps} className={cx('class1', { class2: true })} />;
>k : JSX.Element
><button {...buttonProps} className={cx('class1', { class2: true })} /> : JSX.Element
>button : any
>buttonProps : { [attributeName: string]: ""; }
>className : any
>cx('class1', { class2: true }) : any
>cx : any
>'class1' : "class1"
>{ class2: true } : { class2: boolean; }
>class2 : boolean
>true : true
=== tests/cases/conformance/jsx/declaration.d.ts ===
declare module "classnames";
No type information for this code.
No type information for this code.
@@ -1,16 +1,16 @@
tests/cases/compiler/createArray.ts(1,12): error TS2304: Cannot find name 'number'.
tests/cases/compiler/createArray.ts(1,12): error TS2693: 'number' only refers to a type, but is being used as a value here.
tests/cases/compiler/createArray.ts(1,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
tests/cases/compiler/createArray.ts(6,6): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
tests/cases/compiler/createArray.ts(7,12): error TS2304: Cannot find name 'boolean'.
tests/cases/compiler/createArray.ts(7,12): error TS2693: 'boolean' only refers to a type, but is being used as a value here.
tests/cases/compiler/createArray.ts(7,19): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
tests/cases/compiler/createArray.ts(8,12): error TS2304: Cannot find name 'string'.
tests/cases/compiler/createArray.ts(8,12): error TS2693: 'string' only refers to a type, but is being used as a value here.
tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
==== tests/cases/compiler/createArray.ts (7 errors) ====
var na=new number[];
~~~~~~
!!! error TS2304: Cannot find name 'number'.
!!! error TS2693: 'number' only refers to a type, but is being used as a value here.
~~
!!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
@@ -22,12 +22,12 @@ tests/cases/compiler/createArray.ts(8,18): error TS1150: 'new T[]' cannot be use
!!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
var ba=new boolean[];
~~~~~~~
!!! error TS2304: Cannot find name 'boolean'.
!!! error TS2693: 'boolean' only refers to a type, but is being used as a value here.
~~
!!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
var sa=new string[];
~~~~~~
!!! error TS2304: Cannot find name 'string'.
!!! error TS2693: 'string' only refers to a type, but is being used as a value here.
~~
!!! error TS1150: 'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.
function f(s:string):number { return 0;
@@ -0,0 +1,72 @@
//// [declarationEmitClassPrivateConstructor.ts]
interface PrivateInterface {
}
export class ExportedClass1 {
private constructor(data: PrivateInterface) { }
}
export class ExportedClass2 {
private constructor(private data: PrivateInterface) { }
}
export class ExportedClass3 {
private constructor(private data: PrivateInterface, private n: number) { }
}
export class ExportedClass4 {
private constructor(private data: PrivateInterface, public n:number) { }
}
//// [declarationEmitClassPrivateConstructor.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ExportedClass1 = (function () {
function ExportedClass1(data) {
}
return ExportedClass1;
}());
exports.ExportedClass1 = ExportedClass1;
var ExportedClass2 = (function () {
function ExportedClass2(data) {
this.data = data;
}
return ExportedClass2;
}());
exports.ExportedClass2 = ExportedClass2;
var ExportedClass3 = (function () {
function ExportedClass3(data, n) {
this.data = data;
this.n = n;
}
return ExportedClass3;
}());
exports.ExportedClass3 = ExportedClass3;
var ExportedClass4 = (function () {
function ExportedClass4(data, n) {
this.data = data;
this.n = n;
}
return ExportedClass4;
}());
exports.ExportedClass4 = ExportedClass4;
//// [declarationEmitClassPrivateConstructor.d.ts]
export declare class ExportedClass1 {
private constructor();
}
export declare class ExportedClass2 {
private data;
private constructor();
}
export declare class ExportedClass3 {
private data;
private n;
private constructor();
}
export declare class ExportedClass4 {
private data;
n: number;
private constructor();
}
@@ -0,0 +1,38 @@
=== tests/cases/compiler/declarationEmitClassPrivateConstructor.ts ===
interface PrivateInterface {
>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0))
}
export class ExportedClass1 {
>ExportedClass1 : Symbol(ExportedClass1, Decl(declarationEmitClassPrivateConstructor.ts, 1, 1))
private constructor(data: PrivateInterface) { }
>data : Symbol(data, Decl(declarationEmitClassPrivateConstructor.ts, 4, 24))
>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0))
}
export class ExportedClass2 {
>ExportedClass2 : Symbol(ExportedClass2, Decl(declarationEmitClassPrivateConstructor.ts, 5, 1))
private constructor(private data: PrivateInterface) { }
>data : Symbol(ExportedClass2.data, Decl(declarationEmitClassPrivateConstructor.ts, 8, 24))
>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0))
}
export class ExportedClass3 {
>ExportedClass3 : Symbol(ExportedClass3, Decl(declarationEmitClassPrivateConstructor.ts, 9, 1))
private constructor(private data: PrivateInterface, private n: number) { }
>data : Symbol(ExportedClass3.data, Decl(declarationEmitClassPrivateConstructor.ts, 12, 24))
>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0))
>n : Symbol(ExportedClass3.n, Decl(declarationEmitClassPrivateConstructor.ts, 12, 55))
}
export class ExportedClass4 {
>ExportedClass4 : Symbol(ExportedClass4, Decl(declarationEmitClassPrivateConstructor.ts, 13, 1))
private constructor(private data: PrivateInterface, public n:number) { }
>data : Symbol(ExportedClass4.data, Decl(declarationEmitClassPrivateConstructor.ts, 16, 24))
>PrivateInterface : Symbol(PrivateInterface, Decl(declarationEmitClassPrivateConstructor.ts, 0, 0))
>n : Symbol(ExportedClass4.n, Decl(declarationEmitClassPrivateConstructor.ts, 16, 55))
}
@@ -0,0 +1,38 @@
=== tests/cases/compiler/declarationEmitClassPrivateConstructor.ts ===
interface PrivateInterface {
>PrivateInterface : PrivateInterface
}
export class ExportedClass1 {
>ExportedClass1 : ExportedClass1
private constructor(data: PrivateInterface) { }
>data : PrivateInterface
>PrivateInterface : PrivateInterface
}
export class ExportedClass2 {
>ExportedClass2 : ExportedClass2
private constructor(private data: PrivateInterface) { }
>data : PrivateInterface
>PrivateInterface : PrivateInterface
}
export class ExportedClass3 {
>ExportedClass3 : ExportedClass3
private constructor(private data: PrivateInterface, private n: number) { }
>data : PrivateInterface
>PrivateInterface : PrivateInterface
>n : number
}
export class ExportedClass4 {
>ExportedClass4 : ExportedClass4
private constructor(private data: PrivateInterface, public n:number) { }
>data : PrivateInterface
>PrivateInterface : PrivateInterface
>n : number
}
@@ -0,0 +1,20 @@
tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts(5,38): error TS4031: Public property 'data' of exported class has or is using private name 'PrivateInterface'.
tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts(10,33): error TS4063: Parameter 'data' of constructor from exported class has or is using private name 'PrivateInterface'.
==== tests/cases/compiler/declarationEmitClassPrivateConstructor2.ts (2 errors) ====
interface PrivateInterface {
}
export class ExportedClass1 {
private constructor(public data: PrivateInterface) { }
~~~~~~~~~~~~~~~~
!!! error TS4031: Public property 'data' of exported class has or is using private name 'PrivateInterface'.
}
export class ExportedClass2 {
protected constructor(data: PrivateInterface) { }
~~~~~~~~~~~~~~~~
!!! error TS4063: Parameter 'data' of constructor from exported class has or is using private name 'PrivateInterface'.
}
@@ -0,0 +1,29 @@
//// [declarationEmitClassPrivateConstructor2.ts]
interface PrivateInterface {
}
export class ExportedClass1 {
private constructor(public data: PrivateInterface) { }
}
export class ExportedClass2 {
protected constructor(data: PrivateInterface) { }
}
//// [declarationEmitClassPrivateConstructor2.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ExportedClass1 = (function () {
function ExportedClass1(data) {
this.data = data;
}
return ExportedClass1;
}());
exports.ExportedClass1 = ExportedClass1;
var ExportedClass2 = (function () {
function ExportedClass2(data) {
}
return ExportedClass2;
}());
exports.ExportedClass2 = ExportedClass2;
@@ -7,5 +7,5 @@ export default 1 + 2;
//// [declarationEmitDefaultExport5.d.ts]
declare var _default: number;
declare const _default: number;
export default _default;
@@ -12,5 +12,5 @@ export default new A();
//// [declarationEmitDefaultExport6.d.ts]
export declare class A {
}
declare var _default: A;
declare const _default: A;
export default _default;
Loaded 100 of 331 files, more files were not shown because too many files have changed in this diff. Show more