Merge branch 'master' into symbolInfoFormatting

This commit is contained in:
Sheetal Nandi
2014-10-08 18:25:42 -07:00
296 changed files with 5900 additions and 1506 deletions
+8 -3
View File
@@ -84,8 +84,13 @@ module ts {
if (node.name) {
node.name.parent = node;
}
file.semanticErrors.push(createDiagnosticForNode(node.name ? node.name : node,
Diagnostics.Duplicate_identifier_0, getDisplayName(node)));
// Report errors every position with duplicate declaration
// Report errors on previous encountered declarations
forEach(symbol.declarations, (declaration) => {
file.semanticErrors.push(createDiagnosticForNode(declaration.name, Diagnostics.Duplicate_identifier_0, getDisplayName(declaration)));
});
file.semanticErrors.push(createDiagnosticForNode(node.name, Diagnostics.Duplicate_identifier_0, getDisplayName(node)));
symbol = createSymbol(0, name);
}
}
@@ -332,7 +337,7 @@ module ts {
break;
case SyntaxKind.SourceFile:
if (isExternalModule(<SourceFile>node)) {
bindAnonymousDeclaration(node, SymbolFlags.ValueModule, '"' + getModuleNameFromFilename((<SourceFile>node).filename) + '"');
bindAnonymousDeclaration(node, SymbolFlags.ValueModule, '"' + removeFileExtension((<SourceFile>node).filename) + '"');
break;
}
default:
+94 -114
View File
@@ -104,7 +104,8 @@ module ts {
writeSignature: writeSignature,
writeTypeParameter: writeTypeParameter,
writeTypeParametersOfSymbol: writeTypeParametersOfSymbol,
isImplementationOfOverload: isImplementationOfOverload
isImplementationOfOverload: isImplementationOfOverload,
getAliasedSymbol: resolveImport
};
var undefinedSymbol = createSymbol(SymbolFlags.Undefined | SymbolFlags.Property | SymbolFlags.Transient, "undefined");
@@ -2553,7 +2554,7 @@ module ts {
function getStringLiteralType(node: StringLiteralTypeNode): StringLiteralType {
if (hasProperty(stringLiteralTypes, node.text)) return stringLiteralTypes[node.text];
var type = stringLiteralTypes[node.text] = <StringLiteralType>createType(TypeFlags.StringLiteral);
type.text = getSourceTextOfNode(node);
type.text = getTextOfNode(node);
return type;
}
@@ -4322,25 +4323,32 @@ module ts {
}
function signatureHasCorrectArity(node: CallExpression, signature: Signature): boolean {
var args = node.arguments || emptyArray;
var isCorrect = args.length >= signature.minArgumentCount &&
(signature.hasRestParameter || args.length <= signature.parameters.length) &&
(!node.typeArguments || signature.typeParameters && node.typeArguments.length === signature.typeParameters.length);
// For error recovery, since we have parsed OmittedExpressions for any extra commas
// in the argument list, if we see any OmittedExpressions, just return true.
// The reason this is ok is because omitted expressions here are syntactically
// illegal, and will cause a parse error.
// Note: It may be worth keeping the upper bound check on arity, but removing
// the lower bound check if there are omitted expressions.
if (!isCorrect) {
// Technically this type assertion is not safe because args could be initialized to emptyArray
// above.
if ((<NodeArray<Node>>args).hasTrailingComma || forEach(args, arg => arg.kind === SyntaxKind.OmittedExpression)) {
return true;
}
if (!node.arguments) {
// This only happens when we have something of the form:
// new C
//
return signature.minArgumentCount === 0;
}
return isCorrect;
// For IDE scenarios, since we may have an incomplete call, we make two modifications
// to arity checking.
// 1. A trailing comma is tantamount to adding another argument
// 2. If the call is incomplete (no closing paren) allow fewer arguments than expected
var args = node.arguments;
var numberOfArgs = args.hasTrailingComma ? args.length + 1 : args.length;
var hasTooManyArguments = !signature.hasRestParameter && numberOfArgs > signature.parameters.length;
var hasRightNumberOfTypeArguments = !node.typeArguments ||
(signature.typeParameters && node.typeArguments.length === signature.typeParameters.length);
if (hasTooManyArguments || !hasRightNumberOfTypeArguments) {
return false;
}
// If we are missing the close paren, the call is incomplete, and we should skip
// the lower bound check.
var callIsIncomplete = args.end === node.end;
var hasEnoughArguments = numberOfArgs >= signature.minArgumentCount;
return callIsIncomplete || hasEnoughArguments;
}
// If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
@@ -4491,8 +4499,21 @@ module ts {
}
else {
error(node, Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target);
return resolveErrorCall(node);
}
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information that anySignature.
// Pick the first candidate that matches the arity. This way we can get a contextual type for cases like:
// declare function f(a: { xa: number; xb: number; });
// f({ |
if (!fullTypeCheck) {
for (var i = 0, n = candidates.length; i < n; i++) {
if (signatureHasCorrectArity(node, candidates[i])) {
return candidates[i];
}
}
}
return resolveErrorCall(node);
// The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
@@ -5033,10 +5054,21 @@ module ts {
if (leftType.flags & (TypeFlags.Undefined | TypeFlags.Null)) leftType = rightType;
if (rightType.flags & (TypeFlags.Undefined | TypeFlags.Null)) rightType = leftType;
var leftOk = checkArithmeticOperandType(node.left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type);
var rightOk = checkArithmeticOperandType(node.right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type);
if (leftOk && rightOk) {
checkAssignmentOperator(numberType);
var suggestedOperator: SyntaxKind;
// if a user tries to apply a bitwise operator to 2 boolean operands
// try and return them a helpful suggestion
if ((leftType.flags & TypeFlags.Boolean) &&
(rightType.flags & TypeFlags.Boolean) &&
(suggestedOperator = getSuggestedBooleanOperator(node.operator)) !== undefined) {
error(node, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(node.operator), tokenToString(suggestedOperator));
}
else {
// otherwise just check each operand separately and report errors as normal
var leftOk = checkArithmeticOperandType(node.left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type);
var rightOk = checkArithmeticOperandType(node.right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type);
if (leftOk && rightOk) {
checkAssignmentOperator(numberType);
}
}
return numberType;
@@ -5101,6 +5133,22 @@ module ts {
case SyntaxKind.CommaToken:
return rightType;
}
function getSuggestedBooleanOperator(operator: SyntaxKind): SyntaxKind {
switch (operator) {
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return SyntaxKind.BarBarToken;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return SyntaxKind.ExclamationEqualsEqualsToken;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return SyntaxKind.AmpersandAmpersandToken;
default:
return undefined;
}
}
function checkAssignmentOperator(valueType: Type): void {
if (fullTypeCheck && operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) {
@@ -5641,6 +5689,10 @@ module ts {
var isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0;
function reportImplementationExpectedError(node: FunctionDeclaration): void {
if (node.name && node.name.kind === SyntaxKind.Missing) {
return;
}
var seen = false;
var subsequentNode = forEachChild(node.parent, c => {
if (seen) {
@@ -5679,6 +5731,8 @@ module ts {
// when checking exported function declarations across modules check only duplicate implementations
// names and consistency of modifiers are verified when we check local symbol
var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module;
var duplicateFunctionDeclaration = false;
var multipleConstructorImplementation = false;
for (var i = 0; i < declarations.length; i++) {
var node = <FunctionDeclaration>declarations[i];
var inAmbientContext = isInAmbientContext(node);
@@ -5701,10 +5755,10 @@ module ts {
if (node.body && bodyDeclaration) {
if (isConstructor) {
error(node, Diagnostics.Multiple_constructor_implementations_are_not_allowed);
multipleConstructorImplementation = true;
}
else {
error(node, Diagnostics.Duplicate_function_implementation);
duplicateFunctionDeclaration = true;
}
}
else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
@@ -5728,6 +5782,18 @@ module ts {
}
}
if (multipleConstructorImplementation) {
forEach(declarations, declaration => {
error(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed);
});
}
if (duplicateFunctionDeclaration) {
forEach( declarations, declaration => {
error(declaration.name, Diagnostics.Duplicate_function_implementation);
});
}
if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body) {
reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
}
@@ -7068,23 +7134,6 @@ module ts {
return mapToArray(symbols);
}
// True if the given identifier is the name of a type declaration node (class, interface, enum, type parameter, etc)
function isTypeDeclarationName(name: Node): boolean {
return name.kind == SyntaxKind.Identifier &&
isTypeDeclaration(name.parent) &&
(<Declaration>name.parent).name === name;
}
function isTypeDeclaration(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
return true;
}
}
// True if the given identifier is part of a type reference
function isTypeReferenceIdentifier(entityName: EntityName): boolean {
var node: Node = entityName;
@@ -7163,75 +7212,6 @@ module ts {
return false;
}
function isTypeNode(node: Node): boolean {
if (node.kind >= SyntaxKind.FirstTypeNode && node.kind <= SyntaxKind.LastTypeNode) {
return true;
}
switch (node.kind) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.PrefixOperator;
case SyntaxKind.StringLiteral:
// Specialized signatures can have string literals as their parameters' type names
return node.parent.kind === SyntaxKind.Parameter;
// Identifiers and qualified names may be type nodes, depending on their context. Climb
// above them to find the lowest container
case SyntaxKind.Identifier:
// If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
if (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
// Fall through
case SyntaxKind.QualifiedName:
// At this point, node is either a qualified name or an identifier
var parent = node.parent;
if (parent.kind === SyntaxKind.TypeQuery) {
return false;
}
// Do not recursively call isTypeNode on the parent. In the example:
//
// var a: A.B.C;
//
// Calling isTypeNode would consider the qualified name A.B a type node. Only C or
// A.B.C is a type node.
if (parent.kind >= SyntaxKind.FirstTypeNode && parent.kind <= SyntaxKind.LastTypeNode) {
return true;
}
switch (parent.kind) {
case SyntaxKind.TypeParameter:
return node === (<TypeParameterDeclaration>parent).constraint;
case SyntaxKind.Property:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
return node === (<VariableDeclaration>parent).type;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Constructor:
case SyntaxKind.Method:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node === (<FunctionDeclaration>parent).type;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return node === (<SignatureDeclaration>parent).type;
case SyntaxKind.TypeAssertion:
return node === (<TypeAssertion>parent).type;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return (<CallExpression>parent).typeArguments.indexOf(node) >= 0;
}
}
return false;
}
function isInRightSideOfImportOrExportAssignment(node: EntityName) {
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
@@ -7485,7 +7465,7 @@ module ts {
while (!isUniqueLocalName(escapeIdentifier(prefix + name), container)) {
prefix += "_";
}
links.localModuleName = prefix + getSourceTextOfNode(container.name);
links.localModuleName = prefix + getTextOfNode(container.name);
}
return links.localModuleName;
}
+42 -7
View File
@@ -209,11 +209,9 @@ module ts {
export var localizedDiagnosticMessages: Map<string> = undefined;
export function getLocaleSpecificMessage(message: string) {
if (ts.localizedDiagnosticMessages) {
message = localizedDiagnosticMessages[message];
}
return message;
return localizedDiagnosticMessages && localizedDiagnosticMessages[message]
? localizedDiagnosticMessages[message]
: message;
}
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic;
@@ -478,7 +476,7 @@ module ts {
}
}
export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, isAbsolutePathAnUrl: boolean) {
export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean) {
var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") {
@@ -489,7 +487,7 @@ module ts {
// Find the component that differs
for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
if (directoryComponents[joinStartIndex] !== pathComponents[joinStartIndex]) {
if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
break;
}
}
@@ -535,6 +533,43 @@ module ts {
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
var supportedExtensions = [".d.ts", ".ts", ".js"];
export function removeFileExtension(path: string): string {
for (var i = 0; i < supportedExtensions.length; i++) {
var ext = supportedExtensions[i];
if (fileExtensionIs(path, ext)) {
return path.substr(0, path.length - ext.length);
}
}
return path;
}
var escapedCharsRegExp = /[\t\v\f\b\0\r\n\"\\\u2028\u2029\u0085]/g;
var escapedCharsMap: Map<string> = {
"\t": "\\t",
"\v": "\\v",
"\f": "\\f",
"\b": "\\b",
"\0": "\\0",
"\r": "\\r",
"\n": "\\n",
"\"": "\\\"",
"\u2028": "\\u2028", // lineSeparator
"\u2029": "\\u2029", // paragraphSeparator
"\u0085": "\\u0085" // nextLine
};
/** NOTE: This *does not* support the full escape characters, it only supports the subset that can be used in file names
* or string literals. If the information encoded in the map changes, this needs to be revisited. */
export function escapeString(s: string): string {
return escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, c => {
return escapedCharsMap[c] || c;
}) : s;
}
export interface ObjectAllocator {
getNodeConstructor(kind: SyntaxKind): new () => Node;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
@@ -5,6 +5,7 @@ module ts {
Unterminated_string_literal: { code: 1002, category: DiagnosticCategory.Error, key: "Unterminated string literal." },
Identifier_expected: { code: 1003, category: DiagnosticCategory.Error, key: "Identifier expected." },
_0_expected: { code: 1005, category: DiagnosticCategory.Error, key: "'{0}' expected." },
A_file_cannot_have_a_reference_to_itself: { code: 1006, category: DiagnosticCategory.Error, key: "A file cannot have a reference to itself." },
Trailing_comma_not_allowed: { code: 1009, category: DiagnosticCategory.Error, key: "Trailing comma not allowed." },
Asterisk_Slash_expected: { code: 1010, category: DiagnosticCategory.Error, key: "'*/' expected." },
Unexpected_token: { code: 1012, category: DiagnosticCategory.Error, key: "Unexpected token." },
@@ -260,6 +261,7 @@ module ts {
Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: DiagnosticCategory.Error, key: "Property '{0}' is protected in type '{1}' but public in type '{2}'." },
Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." },
Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible through an instance of class '{1}'." },
The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: DiagnosticCategory.Error, key: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4001, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using name '{1}' from private module '{2}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
+9
View File
@@ -10,6 +10,10 @@
"'{0}' expected.": {
"category": "Error",
"code": 1005
},
"A file cannot have a reference to itself.": {
"category": "Error",
"code": 1006
},
"Trailing comma not allowed.": {
"category": "Error",
@@ -1032,6 +1036,10 @@
"category": "Error",
"code": 2446
},
"The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead.": {
"category": "Error",
"code": 2447
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -1355,6 +1363,7 @@
"category": "Error",
"code": 5001
},
"Cannot find the common subdirectory path for the input files.": {
"category": "Error",
"code": 5009
+31 -45
View File
@@ -58,10 +58,10 @@ module ts {
function getOwnEmitOutputFilePath(sourceFile: SourceFile, extension: string) {
if (compilerOptions.outDir) {
var emitOutputFilePathWithoutExtension = getModuleNameFromFilename(getSourceFilePathInNewDir(compilerOptions.outDir, sourceFile));
var emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(compilerOptions.outDir, sourceFile));
}
else {
var emitOutputFilePathWithoutExtension = getModuleNameFromFilename(sourceFile.filename);
var emitOutputFilePathWithoutExtension = removeFileExtension(sourceFile.filename);
}
return emitOutputFilePathWithoutExtension + extension;
@@ -538,7 +538,8 @@ module ts {
sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath,
node.filename,
compilerHost.getCurrentDirectory(),
/*isAbsolutePathAnUrl*/ true));
compilerHost.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true));
sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1;
// The one that can be used from program to get the actual source file
@@ -602,21 +603,6 @@ module ts {
recordSourceMapSpan(comment.end);
}
var escapedCharsRegExp = /[\t\v\f\b\0\r\n\"\u2028\u2029\u0085]/g;
var escapedCharsMap: Map<string> = {
"\t": "\\t",
"\v": "\\v",
"\f": "\\f",
"\b": "\\b",
"\0": "\\0",
"\r": "\\r",
"\n": "\\n",
"\"": "\\\"",
"\u2028": "\\u2028", // lineSeparator
"\u2029": "\\u2029", // paragraphSeparator
"\u0085": "\\u0085" // nextLine
};
function serializeSourceMapContents(version: number, file: string, sourceRoot: string, sources: string[], names: string[], mappings: string) {
if (typeof JSON !== "undefined") {
return JSON.stringify({
@@ -631,14 +617,6 @@ module ts {
return "{\"version\":" + version + ",\"file\":\"" + escapeString(file) + "\",\"sourceRoot\":\"" + escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + escapeString(mappings) + "\"}";
/** This does not support the full escape characters, it only supports the subset that can be used in file names
* or string literals. If the information encoded in the map changes, this needs to be revisited. */
function escapeString(s: string): string {
return escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, c => {
return escapedCharsMap[c] || c;
}) : s;
}
function serializeStringArray(list: string[]): string {
var output = "";
for (var i = 0, n = list.length; i < n; i++) {
@@ -703,7 +681,8 @@ module ts {
getDirectoryPath(normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath
combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
compilerHost.getCurrentDirectory(),
/*isAbsolutePathAnUrl*/ true);
compilerHost.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true);
}
else {
sourceMapData.jsSourceMappingURL = combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);
@@ -3161,7 +3140,7 @@ module ts {
}
}
function resolveScriptReference(sourceFile: SourceFile, reference: FileReference) {
function tryResolveScriptReference(sourceFile: SourceFile, reference: FileReference) {
var referenceFileName = normalizePath(combinePaths(getDirectoryPath(sourceFile.filename), reference.filename));
return program.getSourceFile(referenceFileName);
}
@@ -3175,13 +3154,14 @@ module ts {
? referencedFile.filename // Declaration file, use declaration file name
: shouldEmitToOwnFile(referencedFile, compilerOptions)
? getOwnEmitOutputFilePath(referencedFile, ".d.ts") // Own output file so get the .d.ts file
: getModuleNameFromFilename(compilerOptions.out) + ".d.ts";// Global out file
: removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file
declFileName = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizeSlashes(jsFilePath)),
declFileName,
compilerHost.getCurrentDirectory(),
/*isAbsolutePathAnUrl*/ false);
compilerHost.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ false);
referencePathsOutput += "/// <reference path=\"" + declFileName + "\" />" + newLine;
}
@@ -3191,12 +3171,12 @@ module ts {
if (!compilerOptions.noResolve) {
var addedGlobalFileReference = false;
forEach(root.referencedFiles, fileReference => {
var referencedFile = resolveScriptReference(root, fileReference);
var referencedFile = tryResolveScriptReference(root, fileReference);
// All the references that are not going to be part of same file
if ((referencedFile.flags & NodeFlags.DeclarationFile) || // This is a declare file reference
if (referencedFile && ((referencedFile.flags & NodeFlags.DeclarationFile) || // This is a declare file reference
shouldEmitToOwnFile(referencedFile, compilerOptions) || // This is referenced file is emitting its own js file
!addedGlobalFileReference) { // Or the global out file corresponding to this reference was not added
!addedGlobalFileReference)) { // Or the global out file corresponding to this reference was not added
writeReferencePath(referencedFile);
if (!isExternalModuleOrDeclarationFile(referencedFile)) {
@@ -3216,11 +3196,11 @@ module ts {
// Check what references need to be added
if (!compilerOptions.noResolve) {
forEach(sourceFile.referencedFiles, fileReference => {
var referencedFile = resolveScriptReference(sourceFile, fileReference);
var referencedFile = tryResolveScriptReference(sourceFile, fileReference);
// If the reference file is a declaration file or an external module, emit that reference
if (isExternalModuleOrDeclarationFile(referencedFile) &&
!contains(emittedReferencedFiles, referencedFile)) { // If the file reference was not already emitted
if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) &&
!contains(emittedReferencedFiles, referencedFile))) { // If the file reference was not already emitted
writeReferencePath(referencedFile);
emittedReferencedFiles.push(referencedFile);
@@ -3248,7 +3228,7 @@ module ts {
}
});
declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos);
writeFile(getModuleNameFromFilename(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM);
writeFile(removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM);
}
}
@@ -3262,21 +3242,27 @@ module ts {
}
if (targetSourceFile === undefined) {
// No targetSourceFile is specified (e.g. calling emitter from batch compiler)
forEach(program.getSourceFiles(), sourceFile => {
if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, ".js");
emitFile(jsFilePath, sourceFile);
}
});
}
else {
// Emit only one file specified in targetFilename. This is mainly used in compilerOnSave feature
var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, ".js");
emitFile(jsFilePath, targetSourceFile);
}
if (compilerOptions.out) {
emitFile(compilerOptions.out);
if (compilerOptions.out) {
emitFile(compilerOptions.out);
}
} else {
// targetSourceFile is specified (e.g calling emitter from language service)
if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {
// If shouldEmitToOwnFile is true or targetSourceFile is an external module file, then emit targetSourceFile in its own output file
var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, ".js");
emitFile(jsFilePath, targetSourceFile);
} else {
// If shouldEmitToOwnFile is false, then emit all, non-external-module file, into one single output file
emitFile(compilerOptions.out);
}
}
// Sort and make the unique list of diagnostics
+132 -41
View File
@@ -17,22 +17,11 @@ module ts {
return node;
}
var moduleExtensions = [".d.ts", ".ts", ".js"];
interface ReferenceComments {
referencedFiles: FileReference[];
amdDependencies: string[];
}
export function getModuleNameFromFilename(filename: string) {
for (var i = 0; i < moduleExtensions.length; i++) {
var ext = moduleExtensions[i];
var len = filename.length - ext.length;
if (len > 0 && filename.substr(len) === ext) return filename.substr(0, len);
}
return filename;
}
export function getSourceFileOfNode(node: Node): SourceFile {
while (node && node.kind !== SyntaxKind.SourceFile) node = node.parent;
return <SourceFile>node;
@@ -54,11 +43,11 @@ module ts {
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
}
export function getSourceTextOfNodeFromSourceText(sourceText: string, node: Node): string {
export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string {
return sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
}
export function getSourceTextOfNode(node: Node): string {
export function getTextOfNode(node: Node): string {
var text = getSourceFileOfNode(node).text;
return text.substring(skipTrivia(text, node.pos), node.end);
}
@@ -75,7 +64,7 @@ module ts {
// Return display name of an identifier
export function identifierToString(identifier: Identifier) {
return identifier.kind === SyntaxKind.Missing ? "(Missing)" : getSourceTextOfNode(identifier);
return identifier.kind === SyntaxKind.Missing ? "(Missing)" : getTextOfNode(identifier);
}
export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic {
@@ -402,6 +391,100 @@ module ts {
return false;
}
/**
* Note: this function only works when given a node with valid parent pointers.
*/
export function isTypeNode(node: Node): boolean {
if (node.kind >= SyntaxKind.FirstTypeNode && node.kind <= SyntaxKind.LastTypeNode) {
return true;
}
switch (node.kind) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.PrefixOperator;
case SyntaxKind.StringLiteral:
// Specialized signatures can have string literals as their parameters' type names
return node.parent.kind === SyntaxKind.Parameter;
// Identifiers and qualified names may be type nodes, depending on their context. Climb
// above them to find the lowest container
case SyntaxKind.Identifier:
// If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
if (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
// Fall through
case SyntaxKind.QualifiedName:
// At this point, node is either a qualified name or an identifier
var parent = node.parent;
if (parent.kind === SyntaxKind.TypeQuery) {
return false;
}
// Do not recursively call isTypeNode on the parent. In the example:
//
// var a: A.B.C;
//
// Calling isTypeNode would consider the qualified name A.B a type node. Only C or
// A.B.C is a type node.
if (parent.kind >= SyntaxKind.FirstTypeNode && parent.kind <= SyntaxKind.LastTypeNode) {
return true;
}
switch (parent.kind) {
case SyntaxKind.TypeParameter:
return node === (<TypeParameterDeclaration>parent).constraint;
case SyntaxKind.Property:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
return node === (<VariableDeclaration>parent).type;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Constructor:
case SyntaxKind.Method:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node === (<FunctionDeclaration>parent).type;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return node === (<SignatureDeclaration>parent).type;
case SyntaxKind.TypeAssertion:
return node === (<TypeAssertion>parent).type;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return (<CallExpression>parent).typeArguments && (<CallExpression>parent).typeArguments.indexOf(node) >= 0;
}
}
return false;
}
/**
* Note: this function only works when given a node with valid parent pointers.
*
* returns true if the given identifier is the name of a type declaration node (class, interface, enum, type parameter, etc)
*/
export function isTypeDeclarationName(name: Node): boolean {
return name.kind == SyntaxKind.Identifier &&
isTypeDeclaration(name.parent) &&
(<Declaration>name.parent).name === name;
}
export function isTypeDeclaration(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
return true;
}
}
export function getContainingFunction(node: Node): SignatureDeclaration {
while (true) {
node = node.parent;
@@ -1013,7 +1096,10 @@ module ts {
return finishNode(node);
}
error(Diagnostics.Identifier_expected);
return <Identifier>createMissingNode();
var node = <Identifier>createMissingNode();
node.text = "";
return node;
}
function parseIdentifier(): Identifier {
@@ -1073,7 +1159,7 @@ module ts {
case ParsingContext.TypeParameters:
return isIdentifier();
case ParsingContext.ArgumentExpressions:
return isExpression();
return token === SyntaxKind.CommaToken || isExpression();
case ParsingContext.ArrayLiteralMembers:
return token === SyntaxKind.CommaToken || isExpression();
case ParsingContext.Parameters:
@@ -1226,18 +1312,6 @@ module ts {
error(Diagnostics._0_expected, ",");
}
else if (isListTerminator(kind)) {
// Check if the last token was a comma.
if (commaStart >= 0) {
if (!allowTrailingComma) {
if (file.syntacticErrors.length === errorCountBeforeParsingList) {
// Report a grammar error so we don't affect lookahead
grammarErrorAtPos(commaStart, scanner.getStartPos() - commaStart, Diagnostics.Trailing_comma_not_allowed);
}
}
// Always preserve a trailing comma by marking it on the NodeArray
result.hasTrailingComma = true;
}
break;
}
else {
@@ -1248,6 +1322,23 @@ module ts {
nextToken();
}
}
// Recording the trailing comma is deliberately done after the previous
// loop, and not just if we see a list terminator. This is because the list
// may have ended incorrectly, but it is still important to know if there
// was a trailing comma.
// Check if the last token was a comma.
if (commaStart >= 0) {
if (!allowTrailingComma) {
if (file.syntacticErrors.length === errorCountBeforeParsingList) {
// Report a grammar error so we don't affect lookahead
grammarErrorAtPos(commaStart, scanner.getStartPos() - commaStart, Diagnostics.Trailing_comma_not_allowed);
}
}
// Always preserve a trailing comma by marking it on the NodeArray
result.hasTrailingComma = true;
}
result.end = getNodeEnd();
parsingContext = saveParsingContext;
return result;
@@ -2306,9 +2397,6 @@ module ts {
else {
parseExpected(SyntaxKind.OpenParenToken);
}
// It is an error to have a trailing comma in an argument list. However, the checker
// needs evidence of a trailing comma in order to give good results for signature help.
// That is why we do not allow a trailing comma, but we "preserve" a trailing comma.
callExpr.arguments = parseDelimitedList(ParsingContext.ArgumentExpressions,
parseArgumentExpression, /*allowTrailingComma*/ false);
parseExpected(SyntaxKind.CloseParenToken);
@@ -2536,9 +2624,6 @@ module ts {
parseExpected(SyntaxKind.NewKeyword);
node.func = parseCallAndAccess(parsePrimaryExpression(), /* inNewExpression */ true);
if (parseOptional(SyntaxKind.OpenParenToken) || token === SyntaxKind.LessThanToken && (node.typeArguments = tryParse(parseTypeArgumentsAndOpenParen))) {
// It is an error to have a trailing comma in an argument list. However, the checker
// needs evidence of a trailing comma in order to give good results for signature help.
// That is why we do not allow a trailing comma, but we "preserve" a trailing comma.
node.arguments = parseDelimitedList(ParsingContext.ArgumentExpressions,
parseArgumentExpression, /*allowTrailingComma*/ false);
parseExpected(SyntaxKind.CloseParenToken);
@@ -2946,7 +3031,7 @@ module ts {
parseExpected(SyntaxKind.ColonToken);
if (labelledStatementInfo.nodeIsNestedInLabel(node.label, /*requireIterationStatement*/ false, /*stopAtFunctionBoundary*/ true)) {
grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getSourceTextOfNodeFromSourceText(sourceText, node.label));
grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNodeFromSourceText(sourceText, node.label));
}
labelledStatementInfo.addLabel(node.label);
@@ -3548,7 +3633,7 @@ module ts {
}
return finishNode(node);
}
function parseAndCheckEnumDeclaration(pos: number, flags: NodeFlags): EnumDeclaration {
function isIntegerLiteral(expression: Expression): boolean {
function isInteger(literalExpression: LiteralExpression): boolean {
@@ -3826,15 +3911,17 @@ module ts {
}
else {
var matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
var start = range.pos;
var end = range.end;
var length = end - start;
if (!matchResult) {
var start = range.pos;
var length = range.end - start;
errorAtPos(start, length, Diagnostics.Invalid_reference_directive_syntax);
}
else {
referencedFiles.push({
pos: range.pos,
end: range.end,
pos: start,
end: end,
filename: matchResult[3]
});
}
@@ -3951,6 +4038,9 @@ module ts {
else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = Diagnostics.File_0_not_found;
}
else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) {
diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself;
}
}
else {
if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) {
@@ -4009,7 +4099,8 @@ module ts {
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
processSourceFile(normalizePath(combinePaths(basePath, ref.filename)), /* isDefaultLib */ false, file, ref.pos, ref.end);
var referencedFilename = isRootedDiskPath(ref.filename) ? ref.filename : combinePaths(basePath, ref.filename);
processSourceFile(normalizePath(referencedFilename), /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
+1 -1
View File
@@ -9,7 +9,7 @@
/// <reference path="commandLineParser.ts"/>
module ts {
var version = "1.1.0.0";
var version = "1.3.0.0";
/**
* Checks to see if the locale is in the appropriate format,
+1
View File
@@ -662,6 +662,7 @@ module ts {
getEnumMemberValue(node: EnumMember): number;
isValidPropertyAccess(node: PropertyAccess, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
}
export interface SymbolWriter {
+80 -39
View File
@@ -416,10 +416,14 @@ module FourSlash {
}
private raiseError(message: string) {
message = "Marker: " + currentTestState.lastKnownMarker + "\n" + message;
message = this.messageAtLastKnownMarker(message);
throw new Error(message);
}
private messageAtLastKnownMarker(message: string) {
return "Marker: " + currentTestState.lastKnownMarker + "\n" + message;
}
private getDiagnostics(fileName: string): ts.Diagnostic[] {
var syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName);
var semanticErrors = this.languageService.getSemanticDiagnostics(fileName);
@@ -757,8 +761,12 @@ module FourSlash {
return this.languageService.getImplementorsAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
private assertionMessage(name: string, actualValue: any, expectedValue: any) {
return "\nActual " + name + ":\n\t" + actualValue + "\nExpected value:\n\t" + expectedValue;
}
public verifyQuickInfo(negative: boolean, expectedText?: string, expectedDocumentation?: string) {
[expectedText, expectedDocumentation].forEach(str => {
[expectedText, expectedDocumentation].forEach(str => {
if (str) {
this.scenarioActions.push('<ShowQuickInfo />');
this.scenarioActions.push('<VerifyQuickInfoTextContains IgnoreSpacing="true" Text="' + escapeXmlAttributeValue(str) + '" ' + (negative ? 'ExpectsFailure="true"' : '') + ' />');
@@ -771,14 +779,14 @@ module FourSlash {
if (negative) {
if (expectedText !== undefined) {
assert.notEqual(actualQuickInfoText, expectedText, assertionMessage("quick info text"));
assert.notEqual(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
if (expectedDocumentation != undefined) {
assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, assertionMessage("quick info doc comment"));
assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, this.messageAtLastKnownMarker("quick info doc comment"));
}
} else {
if (expectedText !== undefined) {
assert.equal(actualQuickInfoText, expectedText, assertionMessage("quick info text"));
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
if (expectedDocumentation != undefined) {
assert.equal(actualQuickInfoDocumentation, expectedDocumentation, assertionMessage("quick info doc"));
@@ -786,7 +794,39 @@ module FourSlash {
}
}
public verifyQuickInfoExists(negative: number) {
public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) {
var renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition);
if (renameInfo.canRename) {
var references = this.languageService.findRenameLocations(
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments);
var ranges = this.getRanges();
if (ranges.length !== references.length) {
this.raiseError(this.assertionMessage("Rename locations", references.length, ranges.length));
}
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
references = references.sort((r1, r2) => r1.textSpan.start() - r2.textSpan.start());
for (var i = 0, n = ranges.length; i < n; i++) {
var reference = references[i];
var range = ranges[i];
if (reference.textSpan.start() !== range.start ||
reference.textSpan.end() !== range.end) {
this.raiseError(this.assertionMessage("Rename location",
"[" + reference.textSpan.start() + "," + reference.textSpan.end() + ")",
"[" + range.start + "," + range.end + ")"));
}
}
}
else {
this.raiseError("Expected rename to succeed, but it actually failed.");
}
}
public verifyQuickInfoExists(negative: boolean) {
this.taoInvalidReason = 'verifyQuickInfoExists NYI';
var actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
@@ -872,6 +912,13 @@ module FourSlash {
assert.equal(actual, expected);
}
public verifySignatureHelpArgumentCount(expected: number) {
this.taoInvalidReason = 'verifySignatureHelpArgumentCount NYI';
var signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
var actual = signatureHelpItems.argumentCount;
assert.equal(actual, expected);
}
public verifySignatureHelpPresent(shouldBePresent = true) {
this.taoInvalidReason = 'verifySignatureHelpPresent NYI';
@@ -925,29 +972,16 @@ module FourSlash {
this.validate("error", message, renameInfo.localizedErrorMessage);
}
//private getFormalParameter() {
// var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
// return help.formal;
//}
private getActiveSignatureHelpItem() {
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
// If the signature hasn't been narrowed down yet (e.g. no parameters have yet been entered),
// 'activeFormal' will be -1 (even if there is only 1 signature). Signature help will show the
// first signature in the signature group, so go with that
var index = help.selectedItemIndex < 0 ? 0 : help.selectedItemIndex;
var index = help.selectedItemIndex;
return help.items[index];
}
private getActiveParameter(): ts.SignatureHelpParameter {
var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
var item = help.items[help.selectedItemIndex];
// Same logic as in getActiveSignatureHelp - this value might be -1 until a parameter value actually gets typed
var currentParam = help.argumentIndex < 0 ? 0 : help.argumentIndex;
var currentParam = help.argumentIndex;
return item.parameters[currentParam];
}
@@ -1435,6 +1469,21 @@ module FourSlash {
}
}
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
this.taoInvalidReason = 'verifyDefinititionsInfo NYI';
var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var actualDefinitionName = definitions && definitions.length ? definitions[0].name : "";
var actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : "";
if (negative) {
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Container Name"));
} else {
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Container Name"));
}
}
public getMarkers(): Marker[] {
// Return a copy of the list
return this.testData.markers.slice(0);
@@ -1563,7 +1612,7 @@ module FourSlash {
private verifyClassifications(expected: { classificationType: string; text: string }[], actual: ts.ClassifiedSpan[]) {
if (actual.length !== expected.length) {
this.raiseError('verifySyntacticClassification failed - expected total classifications to be ' + expected.length + ', but was ' + actual.length);
this.raiseError('verifyClassifications failed - expected total classifications to be ' + expected.length + ', but was ' + actual.length);
}
for (var i = 0; i < expected.length; i++) {
@@ -1572,7 +1621,7 @@ module FourSlash {
var expectedType: string = (<any>ts.ClassificationTypeNames)[expectedClassification.classificationType];
if (expectedType !== actualClassification.classificationType) {
this.raiseError('verifySyntacticClassification failed - expected classifications type to be ' +
this.raiseError('verifyClassifications failed - expected classifications type to be ' +
expectedType + ', but was ' +
actualClassification.classificationType);
}
@@ -1580,7 +1629,7 @@ module FourSlash {
var actualSpan = actualClassification.textSpan;
var actualText = this.activeFile.content.substr(actualSpan.start(), actualSpan.length());
if (expectedClassification.text !== actualText) {
this.raiseError('verifySyntacticClassification failed - expected classificatied text to be ' +
this.raiseError('verifyClassifications failed - expected classificatied text to be ' +
expectedClassification.text + ', but was ' +
actualText);
}
@@ -2080,9 +2129,6 @@ module FourSlash {
xmlData.push(xml);
}
// Cache these between executions so we don't have to re-parse them for every test
var fourslashSourceFile: ts.SourceFile = undefined;
export function runFourSlashTestContent(content: string, fileName: string): TestXmlData {
// Parse out the files and their metadata
var testData = parseTestData(content, fileName);
@@ -2090,21 +2136,16 @@ module FourSlash {
currentTestState = new TestState(testData);
var result = '';
var fourslashFilename = 'fourslash.ts';
var tsFn = 'tests/cases/fourslash/' + fourslashFilename;
fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), ts.ScriptTarget.ES5, /*version*/ "0", /*isOpen*/ false);
var files: { [filename: string]: ts.SourceFile; } = {};
files[Harness.Compiler.getCanonicalFileName(fourslashFilename)] = fourslashSourceFile;
files[Harness.Compiler.getCanonicalFileName(fileName)] = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5, /*version*/ "0", /*isOpen*/ false);
files[Harness.Compiler.getCanonicalFileName(Harness.Compiler.defaultLibFileName)] = Harness.Compiler.defaultLibSourceFile;
var host = Harness.Compiler.createCompilerHost(files, (fn, contents) => result = contents);
var program = ts.createProgram([fourslashFilename, fileName], { out: "fourslashTestOutput.js" }, host);
var host = Harness.Compiler.createCompilerHost([{ unitName: Harness.Compiler.fourslashFilename, content: undefined },
{ unitName: fileName, content: content }],
(fn, contents) => result = contents,
ts.ScriptTarget.ES5,
sys.useCaseSensitiveFileNames);
var program = ts.createProgram([Harness.Compiler.fourslashFilename, fileName], { out: "fourslashTestOutput.js" }, host);
var checker = ts.createTypeChecker(program, /*fullTypeCheckMode*/ true);
checker.checkProgram();
var errs = checker.getDiagnostics(files[fileName]);
var errs = checker.getDiagnostics(program.getSourceFile(fileName));
if (errs.length > 0) {
throw new Error('Error compiling ' + fileName + ': ' + errs.map(e => e.messageText).join('\r\n'));
}
+44 -8
View File
@@ -534,18 +534,47 @@ module Harness {
export var defaultLibFileName = 'lib.d.ts';
export var defaultLibSourceFile = ts.createSourceFile(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.ES5, /*version:*/ "0");
// Cache these between executions so we don't have to re-parse them for every test
export var fourslashFilename = 'fourslash.ts';
export var fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
export function createCompilerHost(filemap: { [filename: string]: ts.SourceFile; }, writeFile: (fn: string, contents: string, writeByteOrderMark:boolean) => void): ts.CompilerHost {
export function createCompilerHost(inputFiles: { unitName: string; content: string; }[],
writeFile: (fn: string, contents: string, writeByteOrderMark: boolean) => void,
scriptTarget: ts.ScriptTarget,
useCaseSensitiveFileNames: boolean): ts.CompilerHost {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
function getCanonicalFileName(fileName: string): string {
return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
var filemap: { [filename: string]: ts.SourceFile; } = {};
// Register input files
function register(file: { unitName: string; content: string; }) {
if (file.content !== undefined) {
var filename = Path.switchToForwardSlashes(file.unitName);
filemap[getCanonicalFileName(filename)] = ts.createSourceFile(filename, file.content, scriptTarget, /*version:*/ "0");
}
};
inputFiles.forEach(register);
return {
getCurrentDirectory: sys.getCurrentDirectory,
getCancellationToken: (): any => undefined,
getSourceFile: (fn, languageVersion) => {
if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
return filemap[getCanonicalFileName(fn)];
} else {
}
else if (fn === fourslashFilename) {
var tsFn = 'tests/cases/fourslash/' + fourslashFilename;
fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), scriptTarget, /*version*/ "0", /*isOpen*/ false);
return fourslashSourceFile;
}
else {
var lib = defaultLibFileName;
if (fn === defaultLibFileName) {
return defaultLibSourceFile;
@@ -557,7 +586,7 @@ module Harness {
getDefaultLibFilename: () => defaultLibFileName,
writeFile: writeFile,
getCanonicalFileName: getCanonicalFileName,
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: ()=> sys.newLine
};
}
@@ -614,7 +643,7 @@ module Harness {
}
public compileFiles(inputFiles: { unitName: string; content: string }[],
otherFiles: { unitName: string; content?: string }[],
otherFiles: { unitName: string; content: string }[],
onComplete: (result: CompilerResult, checker: ts.TypeChecker) => void,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions) {
@@ -628,9 +657,10 @@ module Harness {
settingsCallback(null);
}
var useCaseSensitiveFileNames = sys.useCaseSensitiveFileNames;
this.settings.forEach(setting => {
switch (setting.flag.toLowerCase()) {
// "filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outDir", "noimplicitany", "noresolve"
// "filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve"
case "module":
case "modulegentarget":
if (typeof setting.value === 'string') {
@@ -706,10 +736,13 @@ module Harness {
options.removeComments = setting.value === 'false';
break;
case 'usecasesensitivefilenames':
useCaseSensitiveFileNames = setting.value === 'true';
break;
case 'mapsourcefiles':
case 'maproot':
case 'generatedeclarationfiles':
case 'usecasesensitivefileresolution':
case 'gatherDiagnostics':
case 'codepage':
case 'createFileLog':
@@ -748,7 +781,10 @@ module Harness {
var fileOutputs: GeneratedFile[] = [];
var programFiles = inputFiles.map(file => file.unitName);
var program = ts.createProgram(programFiles, options, createCompilerHost(filemap, (fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark })));
var program = ts.createProgram(programFiles, options, createCompilerHost(inputFiles.concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target,
useCaseSensitiveFileNames));
var hadParseErrors = program.getDiagnostics().length > 0;
@@ -1034,7 +1070,7 @@ module Harness {
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outDir", "noimplicitany", "noresolve", "newline", "newlines", "emitbom", "errortruncation"];
var fileMetadataNames = ["filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve", "newline", "newlines", "emitbom", "errortruncation", "usecasesensitivefilenames"];
function extractCompilerSettings(content: string): CompilerSetting[] {
+2 -1
View File
@@ -226,7 +226,8 @@ class ProjectRunner extends RunnerBase {
? filename
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(filename);
var diskRelativeName = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, diskFileName, getCurrentDirectory(), false);
var diskRelativeName = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, diskFileName,
getCurrentDirectory(), Harness.Compiler.getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
if (ts.isRootedDiskPath(diskRelativeName) || diskRelativeName.substr(0, 3) === "../") {
// If the generated output file resides in the parent folder or is rooted path,
// we need to instead create files that can live in the project reference folder
+1 -1
View File
@@ -76,7 +76,7 @@ class TypeWriterWalker {
private log(node: ts.Node, type: ts.Type): void {
var actualPos = ts.skipTrivia(this.currentSourceFile.text, node.pos);
var lineAndCharacter = this.currentSourceFile.getLineAndCharacterFromPosition(actualPos);
var sourceText = ts.getSourceTextOfNodeFromSourceText(this.currentSourceFile.text, node);
var sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node);
// If we got an unknown type, we temporarily want to fall back to just pretending the name
// (source text) of the node is the type. This is to align with the old typeWriter to make
-2
View File
@@ -1,8 +1,6 @@
///<reference path='references.ts' />
module TypeScript {
export var LocalizedDiagnosticMessages: ts.Map<any> = null;
export class Location {
private _fileName: string;
private _lineMap: LineMap;
@@ -1,363 +0,0 @@
module TypeScript.Services {
export class NavigationBarItemGetter {
private hasGlobalNode = false;
private getIndent(node: ISyntaxNode): number {
var indent = this.hasGlobalNode ? 1 : 0;
var current = node.parent;
while (current != null) {
if (current.kind() == SyntaxKind.ModuleDeclaration || current.kind() === SyntaxKind.FunctionDeclaration) {
indent++;
}
current = current.parent;
}
return indent;
}
private getKindModifiers(modifiers: TypeScript.ISyntaxToken[]): string {
var result: string[] = [];
for (var i = 0, n = modifiers.length; i < n; i++) {
result.push(modifiers[i].text());
}
return result.length > 0 ? result.join(',') : ts.ScriptElementKindModifier.none;
}
public getItems(node: TypeScript.SourceUnitSyntax): ts.NavigationBarItem[] {
return this.getItemsWorker(() => this.getTopLevelNodes(node), n => this.createTopLevelItem(n));
}
private getChildNodes(nodes: IModuleElementSyntax[]): ISyntaxNode[] {
var childNodes: ISyntaxNode[] = [];
for (var i = 0, n = nodes.length; i < n; i++) {
var node = <ISyntaxNode>nodes[i];
if (node.kind() === SyntaxKind.FunctionDeclaration) {
childNodes.push(node);
}
else if (node.kind() === SyntaxKind.VariableStatement) {
var variableDeclaration = (<VariableStatementSyntax>node).variableDeclaration;
childNodes.push.apply(childNodes, variableDeclaration.variableDeclarators);
}
}
return childNodes;
}
private getTopLevelNodes(node: SourceUnitSyntax): ISyntaxNode[] {
var topLevelNodes: ISyntaxNode[] = [];
topLevelNodes.push(node);
this.addTopLevelNodes(node.moduleElements, topLevelNodes);
return topLevelNodes;
}
private addTopLevelNodes(nodes: IModuleElementSyntax[], topLevelNodes: ISyntaxNode[]): void {
for (var i = 0, n = nodes.length; i < n; i++) {
var node = nodes[i];
switch (node.kind()) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
topLevelNodes.push(node);
break;
case SyntaxKind.ModuleDeclaration:
var moduleDeclaration = <ModuleDeclarationSyntax>node;
topLevelNodes.push(node);
this.addTopLevelNodes(moduleDeclaration.moduleElements, topLevelNodes);
break;
case SyntaxKind.FunctionDeclaration:
var functionDeclaration = <FunctionDeclarationSyntax>node;
if (this.isTopLevelFunctionDeclaration(functionDeclaration)) {
topLevelNodes.push(node);
this.addTopLevelNodes(functionDeclaration.block.statements, topLevelNodes);
}
break;
}
}
}
public isTopLevelFunctionDeclaration(functionDeclaration: FunctionDeclarationSyntax) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
return functionDeclaration.block && ArrayUtilities.any(functionDeclaration.block.statements, s => s.kind() === SyntaxKind.FunctionDeclaration);
}
private getItemsWorker(getNodes: () => ISyntaxNode[], createItem: (n: ISyntaxNode) => ts.NavigationBarItem): ts.NavigationBarItem[] {
var items: ts.NavigationBarItem[] = [];
var keyToItem = createIntrinsicsObject<ts.NavigationBarItem>();
var nodes = getNodes();
for (var i = 0, n = nodes.length; i < n; i++) {
var child = nodes[i];
var item = createItem(child);
if (item != null) {
if (item.text.length > 0) {
var key = item.text + "-" + item.kind;
var itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
this.merge(itemWithSameName, item);
}
else {
keyToItem[key] = item;
items.push(item);
}
}
}
}
return items;
}
private merge(target: ts.NavigationBarItem, source: ts.NavigationBarItem) {
// First, add any spans in the source to the target.
target.spans.push.apply(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
target.childItems = [];
}
// Next, recursively merge or add any children in the source as appropriate.
outer:
for (var i = 0, n = source.childItems.length; i < n; i++) {
var sourceChild = source.childItems[i];
for (var j = 0, m = target.childItems.length; j < m; j++) {
var targetChild = target.childItems[j];
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
this.merge(targetChild, sourceChild);
continue outer;
}
}
// Didn't find a match, just add this child to the list.
target.childItems.push(sourceChild);
}
}
}
private getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TypeScript.TextSpan[], childItems: ts.NavigationBarItem[]= [], indent: number = 0): ts.NavigationBarItem {
return {
text: text,
kind: kind,
kindModifiers: kindModifiers,
spans: spans,
childItems: childItems,
indent: indent,
bolded: false,
grayed: false
};
}
private createChildItem(node: ISyntaxNode): ts.NavigationBarItem {
switch (node.kind()) {
case SyntaxKind.Parameter:
var parameter = <ParameterSyntax>node;
if (parameter.modifiers.length === 0) {
return null;
}
return this.getNavigationBarItem(parameter.identifier.text(), ts.ScriptElementKind.memberVariableElement, this.getKindModifiers(parameter.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.MemberFunctionDeclaration:
var memberFunction = <MemberFunctionDeclarationSyntax>node;
return this.getNavigationBarItem(memberFunction.propertyName.text(), ts.ScriptElementKind.memberFunctionElement, this.getKindModifiers(memberFunction.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.GetAccessor:
var getAccessor = <GetAccessorSyntax>node;
return this.getNavigationBarItem(getAccessor.propertyName.text(), ts.ScriptElementKind.memberGetAccessorElement, this.getKindModifiers(getAccessor.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.SetAccessor:
var setAccessor = <SetAccessorSyntax>node;
return this.getNavigationBarItem(setAccessor.propertyName.text(), ts.ScriptElementKind.memberSetAccessorElement, this.getKindModifiers(setAccessor.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.IndexSignature:
var indexSignature = <IndexSignatureSyntax>node;
return this.getNavigationBarItem("[]", ts.ScriptElementKind.indexSignatureElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.EnumElement:
var enumElement = <EnumElementSyntax>node;
return this.getNavigationBarItem(enumElement.propertyName.text(), ts.ScriptElementKind.memberVariableElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.CallSignature:
var callSignature = <CallSignatureSyntax>node;
return this.getNavigationBarItem("()", ts.ScriptElementKind.callSignatureElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.ConstructSignature:
var constructSignature = <ConstructSignatureSyntax>node;
return this.getNavigationBarItem("new()", ts.ScriptElementKind.constructSignatureElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.MethodSignature:
var methodSignature = <MethodSignatureSyntax>node;
return this.getNavigationBarItem(methodSignature.propertyName.text(), ts.ScriptElementKind.memberFunctionElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.PropertySignature:
var propertySignature = <PropertySignatureSyntax>node;
return this.getNavigationBarItem(propertySignature.propertyName.text(), ts.ScriptElementKind.memberVariableElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
case SyntaxKind.FunctionDeclaration:
var functionDeclaration = <FunctionDeclarationSyntax>node;
if (!this.isTopLevelFunctionDeclaration(functionDeclaration)) {
return this.getNavigationBarItem(functionDeclaration.identifier.text(), ts.ScriptElementKind.functionElement, this.getKindModifiers(functionDeclaration.modifiers), [TextSpan.fromBounds(start(node), end(node))]);
}
break;
case SyntaxKind.MemberVariableDeclaration:
var memberVariableDeclaration = <MemberVariableDeclarationSyntax>node;
return this.getNavigationBarItem(memberVariableDeclaration.variableDeclarator.propertyName.text(), ts.ScriptElementKind.memberVariableElement, this.getKindModifiers(memberVariableDeclaration.modifiers), [TextSpan.fromBounds(start(memberVariableDeclaration.variableDeclarator), end(memberVariableDeclaration.variableDeclarator))]);
case SyntaxKind.VariableDeclarator:
var variableDeclarator = <VariableDeclaratorSyntax>node;
return this.getNavigationBarItem(variableDeclarator.propertyName.text(), ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(variableDeclarator), end(variableDeclarator))]);
case SyntaxKind.ConstructorDeclaration:
var constructorDeclaration = <ConstructorDeclarationSyntax>node;
return this.getNavigationBarItem("constructor", ts.ScriptElementKind.constructorImplementationElement, ts.ScriptElementKindModifier.none, [TextSpan.fromBounds(start(node), end(node))]);
}
return null;
}
private createTopLevelItem(node: ISyntaxNode): ts.NavigationBarItem {
switch (node.kind()) {
case SyntaxKind.SourceUnit:
return this.createSourceUnitItem(<SourceUnitSyntax>node);
case SyntaxKind.ClassDeclaration:
return this.createClassItem(<ClassDeclarationSyntax>node);
case SyntaxKind.EnumDeclaration:
return this.createEnumItem(<EnumDeclarationSyntax>node);
case SyntaxKind.InterfaceDeclaration:
return this.createIterfaceItem(<InterfaceDeclarationSyntax>node);
case SyntaxKind.ModuleDeclaration:
return this.createModuleItem(<ModuleDeclarationSyntax>node);
case SyntaxKind.FunctionDeclaration:
return this.createFunctionItem(<FunctionDeclarationSyntax>node);
}
return null;
}
private getModuleNames(node: TypeScript.ModuleDeclarationSyntax): string[] {
var result: string[] = [];
if (node.stringLiteral) {
result.push(node.stringLiteral.text());
}
else {
this.getModuleNamesHelper(node.name, result);
}
return result;
}
private getModuleNamesHelper(name: TypeScript.INameSyntax, result: string[]): void {
if (name.kind() === TypeScript.SyntaxKind.QualifiedName) {
var qualifiedName = <TypeScript.QualifiedNameSyntax>name;
this.getModuleNamesHelper(qualifiedName.left, result);
result.push(qualifiedName.right.text());
}
else {
result.push((<TypeScript.ISyntaxToken>name).text());
}
}
private createModuleItem(node: ModuleDeclarationSyntax): ts.NavigationBarItem {
var moduleNames = this.getModuleNames(node);
var childItems = this.getItemsWorker(() => this.getChildNodes(node.moduleElements), n => this.createChildItem(n));
return this.getNavigationBarItem(moduleNames.join("."),
ts.ScriptElementKind.moduleElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
private createFunctionItem(node: FunctionDeclarationSyntax) {
var childItems = this.getItemsWorker(() => node.block.statements, n => this.createChildItem(n));
return this.getNavigationBarItem(node.identifier.text(),
ts.ScriptElementKind.functionElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
private createSourceUnitItem(node: SourceUnitSyntax): ts.NavigationBarItem {
var childItems = this.getItemsWorker(() => this.getChildNodes(node.moduleElements), n => this.createChildItem(n));
if (childItems === null || childItems.length === 0) {
return null;
}
this.hasGlobalNode = true;
return this.getNavigationBarItem("<global>",
ts.ScriptElementKind.moduleElement,
ts.ScriptElementKindModifier.none,
[TextSpan.fromBounds(start(node), end(node))],
childItems);
}
private createClassItem(node: ClassDeclarationSyntax): ts.NavigationBarItem {
var constructor = <ConstructorDeclarationSyntax>ArrayUtilities.firstOrDefault(
node.classElements, n => n.kind() === SyntaxKind.ConstructorDeclaration);
// Add the constructor parameters in as children of hte class (for property parameters).
var nodes: ISyntaxNode[] = constructor
? (<ISyntaxNode[]>constructor.callSignature.parameterList.parameters).concat(node.classElements)
: node.classElements;
var childItems = this.getItemsWorker(() => nodes, n => this.createChildItem(n));
return this.getNavigationBarItem(
node.identifier.text(),
ts.ScriptElementKind.classElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
private createEnumItem(node: TypeScript.EnumDeclarationSyntax): ts.NavigationBarItem {
var childItems = this.getItemsWorker(() => node.enumElements, n => this.createChildItem(n));
return this.getNavigationBarItem(
node.identifier.text(),
ts.ScriptElementKind.enumElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
private createIterfaceItem(node: TypeScript.InterfaceDeclarationSyntax): ts.NavigationBarItem {
var childItems = this.getItemsWorker(() => node.body.typeMembers, n => this.createChildItem(n));
return this.getNavigationBarItem(
node.identifier.text(),
ts.ScriptElementKind.interfaceElement,
this.getKindModifiers(node.modifiers),
[TextSpan.fromBounds(start(node), end(node))],
childItems,
this.getIndent(node));
}
}
}
+426
View File
@@ -0,0 +1,426 @@
/// <reference path='services.ts' />
/// <reference path="text/textSpan.ts" />
module ts.NavigationBar {
export function getNavigationBarItems(sourceFile: SourceFile): ts.NavigationBarItem[] {
// If the source file has any child items, then it included in the tree
// and takes lexical ownership of all other top-level items.
var hasGlobalNode = false;
return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem);
function getIndent(node: Node): number {
// If we have a global node in the tree,
// then it adds an extra layer of depth to all subnodes.
var indent = hasGlobalNode ? 1 : 0;
var current = node.parent;
while (current) {
switch (current.kind) {
case SyntaxKind.ModuleDeclaration:
// If we have a module declared as A.B.C, it is more "intuitive"
// to say it only has a single layer of depth
do {
current = current.parent;
}
while (current.kind === SyntaxKind.ModuleDeclaration);
// fall through
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.FunctionDeclaration:
indent++;
}
current = current.parent;
}
return indent;
}
function getChildNodes(nodes: Node[]): Node[] {
var childNodes: Node[] = [];
for (var i = 0, n = nodes.length; i < n; i++) {
var node = nodes[i];
if (node.kind === SyntaxKind.ClassDeclaration ||
node.kind === SyntaxKind.EnumDeclaration ||
node.kind === SyntaxKind.InterfaceDeclaration ||
node.kind === SyntaxKind.ModuleDeclaration ||
node.kind === SyntaxKind.FunctionDeclaration) {
childNodes.push(node);
}
else if (node.kind === SyntaxKind.VariableStatement) {
childNodes.push.apply(childNodes, (<VariableStatement>node).declarations);
}
}
return sortNodes(childNodes);
}
function getTopLevelNodes(node: SourceFile): Node[] {
var topLevelNodes: Node[] = [];
topLevelNodes.push(node);
addTopLevelNodes(node.statements, topLevelNodes);
return topLevelNodes;
}
function sortNodes(nodes: Node[]): Node[] {
return nodes.slice(0).sort((n1: Declaration, n2: Declaration) => {
if (n1.name && n2.name) {
return n1.name.text.localeCompare(n2.name.text);
}
else if (n1.name) {
return 1;
}
else if (n2.name) {
-1;
}
else {
return n1.kind - n2.kind;
}
});
}
function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void {
nodes = sortNodes(nodes);
for (var i = 0, n = nodes.length; i < n; i++) {
var node = nodes[i];
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
topLevelNodes.push(node);
break;
case SyntaxKind.ModuleDeclaration:
var moduleDeclaration = <ModuleDeclaration>node;
topLevelNodes.push(node);
addTopLevelNodes((<Block>getInnermostModule(moduleDeclaration).body).statements, topLevelNodes);
break;
case SyntaxKind.FunctionDeclaration:
var functionDeclaration = <FunctionDeclaration>node;
if (isTopLevelFunctionDeclaration(functionDeclaration)) {
topLevelNodes.push(node);
addTopLevelNodes((<Block>functionDeclaration.body).statements, topLevelNodes);
}
break;
}
}
}
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionDeclaration) {
if (functionDeclaration.kind === SyntaxKind.FunctionDeclaration) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
if (functionDeclaration.body && functionDeclaration.body.kind === SyntaxKind.FunctionBlock) {
if (forEach((<Block>functionDeclaration.body).statements,
s => s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text))) {
return true;
}
// Or if it is not parented by another function. i.e all functions
// at module scope are 'top level'.
if (functionDeclaration.parent.kind !== SyntaxKind.FunctionBlock) {
return true;
}
}
}
return false;
}
function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] {
var items: ts.NavigationBarItem[] = [];
var keyToItem: Map<NavigationBarItem> = {};
for (var i = 0, n = nodes.length; i < n; i++) {
var child = nodes[i];
var item = createItem(child);
if (item !== undefined) {
if (item.text.length > 0) {
var key = item.text + "-" + item.kind + "-" + item.indent;
var itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
merge(itemWithSameName, item);
}
else {
keyToItem[key] = item;
items.push(item);
}
}
}
}
return items;
}
function merge(target: ts.NavigationBarItem, source: ts.NavigationBarItem) {
// First, add any spans in the source to the target.
target.spans.push.apply(target.spans, source.spans);
if (source.childItems) {
if (!target.childItems) {
target.childItems = [];
}
// Next, recursively merge or add any children in the source as appropriate.
outer:
for (var i = 0, n = source.childItems.length; i < n; i++) {
var sourceChild = source.childItems[i];
for (var j = 0, m = target.childItems.length; j < m; j++) {
var targetChild = target.childItems[j];
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
merge(targetChild, sourceChild);
continue outer;
}
}
// Didn't find a match, just add this child to the list.
target.childItems.push(sourceChild);
}
}
}
function createChildItem(node: Node): ts.NavigationBarItem {
switch (node.kind) {
case SyntaxKind.Parameter:
if ((node.flags & NodeFlags.Modifier) === 0) {
return undefined;
}
return createItem(node, getTextOfNode((<ParameterDeclaration>node).name), ts.ScriptElementKind.memberVariableElement);
case SyntaxKind.Method:
return createItem(node, getTextOfNode((<MethodDeclaration>node).name), ts.ScriptElementKind.memberFunctionElement);
case SyntaxKind.GetAccessor:
return createItem(node, getTextOfNode((<AccessorDeclaration>node).name), ts.ScriptElementKind.memberGetAccessorElement);
case SyntaxKind.SetAccessor:
return createItem(node, getTextOfNode((<AccessorDeclaration>node).name), ts.ScriptElementKind.memberSetAccessorElement);
case SyntaxKind.IndexSignature:
return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement);
case SyntaxKind.EnumMember:
return createItem(node, getTextOfNode((<EnumMember>node).name), ts.ScriptElementKind.memberVariableElement);
case SyntaxKind.CallSignature:
return createItem(node, "()", ts.ScriptElementKind.callSignatureElement);
case SyntaxKind.ConstructSignature:
return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement);
case SyntaxKind.Property:
return createItem(node, getTextOfNode((<PropertyDeclaration>node).name), ts.ScriptElementKind.memberVariableElement);
case SyntaxKind.FunctionDeclaration:
return createItem(node, getTextOfNode((<FunctionDeclaration>node).name), ts.ScriptElementKind.functionElement);
case SyntaxKind.VariableDeclaration:
return createItem(node, getTextOfNode((<VariableDeclaration>node).name), ts.ScriptElementKind.variableElement);
case SyntaxKind.Constructor:
return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement);
}
return undefined;
function createItem(node: Node, name: string, scriptElementKind: string): NavigationBarItem {
return getNavigationBarItem(name, scriptElementKind, getNodeModifiers(node), [getNodeSpan(node)]);
}
}
function isEmpty(text: string) {
return !text || text.trim() === "";
}
function getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TypeScript.TextSpan[], childItems: ts.NavigationBarItem[] = [], indent: number = 0): ts.NavigationBarItem {
if (isEmpty(text)) {
return undefined;
}
return {
text: text,
kind: kind,
kindModifiers: kindModifiers,
spans: spans,
childItems: childItems,
indent: indent,
bolded: false,
grayed: false
};
}
function createTopLevelItem(node: Node): ts.NavigationBarItem {
switch (node.kind) {
case SyntaxKind.SourceFile:
return createSourceFileItem(<SourceFile>node);
case SyntaxKind.ClassDeclaration:
return createClassItem(<ClassDeclaration>node);
case SyntaxKind.EnumDeclaration:
return createEnumItem(<EnumDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
return createIterfaceItem(<InterfaceDeclaration>node);
case SyntaxKind.ModuleDeclaration:
return createModuleItem(<ModuleDeclaration>node);
case SyntaxKind.FunctionDeclaration:
return createFunctionItem(<FunctionDeclaration>node);
}
return undefined;
function getModuleName(moduleDeclaration: ModuleDeclaration): string {
// We want to maintain quotation marks.
if (moduleDeclaration.name.kind === SyntaxKind.StringLiteral) {
return getTextOfNode(moduleDeclaration.name);
}
// Otherwise, we need to aggregate each identifier to build up the qualified name.
var result: string[] = [];
result.push(moduleDeclaration.name.text);
while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) {
moduleDeclaration = <ModuleDeclaration>moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
return result.join(".");
}
function createModuleItem(node: ModuleDeclaration): NavigationBarItem {
var moduleName = getModuleName(node);
var childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
return getNavigationBarItem(moduleName,
ts.ScriptElementKind.moduleElement,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
function createFunctionItem(node: FunctionDeclaration) {
if (node.name && node.body && node.body.kind === SyntaxKind.FunctionBlock) {
var childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
return getNavigationBarItem(node.name.text,
ts.ScriptElementKind.functionElement,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
return undefined;
}
function createSourceFileItem(node: SourceFile): ts.NavigationBarItem {
var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
if (childItems === undefined || childItems.length === 0) {
return undefined;
}
hasGlobalNode = true;
var rootName = isExternalModule(node) ?
"\"" + escapeString(getBaseFilename(removeFileExtension(normalizePath(node.filename)))) + "\"" :
"<global>"
return getNavigationBarItem(rootName,
ts.ScriptElementKind.moduleElement,
ts.ScriptElementKindModifier.none,
[getNodeSpan(node)],
childItems);
}
function createClassItem(node: ClassDeclaration): ts.NavigationBarItem {
var childItems: NavigationBarItem[];
if (node.members) {
var constructor = <ConstructorDeclaration>forEach(node.members, member => {
return member.kind === SyntaxKind.Constructor && member;
});
// Add the constructor parameters in as children of the class (for property parameters).
var nodes: Node[] = constructor
? constructor.parameters.concat(node.members)
: node.members;
var childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.classElement,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
function createEnumItem(node: EnumDeclaration): ts.NavigationBarItem {
var childItems = getItemsWorker(sortNodes(node.members), createChildItem);
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.enumElement,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
function createIterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem {
var childItems = getItemsWorker(sortNodes(node.members), createChildItem);
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.interfaceElement,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
}
function getInnermostModule(node: ModuleDeclaration): ModuleDeclaration {
while (node.body.kind === SyntaxKind.ModuleDeclaration) {
node = <ModuleDeclaration>node.body;
}
return node;
}
function getNodeSpan(node: Node) {
return node.kind === SyntaxKind.SourceFile
? TypeScript.TextSpan.fromBounds(node.getFullStart(), node.getEnd())
: TypeScript.TextSpan.fromBounds(node.getStart(), node.getEnd());
}
function getTextOfNode(node: Node): string {
return getTextOfNodeFromSourceText(sourceFile.text, node);
}
}
}
+49 -7
View File
@@ -33,19 +33,32 @@ module ts {
export module OutliningElementsCollector {
export function collectElements(sourceFile: SourceFile): OutliningSpan[] {
var elements: OutliningSpan[] = [];
var collapseText = "...";
function addOutlineRange(hintSpanNode: Node, startElement: Node, endElement: Node) {
function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) {
if (hintSpanNode && startElement && endElement) {
var span: OutliningSpan = {
textSpan: TypeScript.TextSpan.fromBounds(startElement.pos, endElement.end),
hintSpan: TypeScript.TextSpan.fromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: "...",
autoCollapse: false
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function autoCollapse(node: Node) {
switch (node.kind) {
case SyntaxKind.ModuleBlock:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
return false;
}
return true;
}
var depth = 0;
var maxDepth = 20;
function walk(n: Node): void {
@@ -54,15 +67,44 @@ module ts {
}
switch (n.kind) {
case SyntaxKind.Block:
var parent = n.parent;
var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collaps the block, but consider its hint span
// to be the entire span of the parent.
if (parent.kind === SyntaxKind.DoStatement ||
parent.kind === SyntaxKind.ForInStatement ||
parent.kind === SyntaxKind.ForStatement ||
parent.kind === SyntaxKind.IfStatement ||
parent.kind === SyntaxKind.WhileStatement ||
parent.kind === SyntaxKind.WithStatement) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
}
else {
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
var span = TypeScript.TextSpan.fromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
}
break;
case SyntaxKind.FunctionBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.TryBlock:
case SyntaxKind.TryBlock:
case SyntaxKind.CatchBlock:
case SyntaxKind.FinallyBlock:
var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutlineRange(n.parent, openBrace, closeBrace);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
@@ -71,12 +113,12 @@ module ts {
case SyntaxKind.SwitchStatement:
var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutlineRange(n, openBrace, closeBrace);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
case SyntaxKind.ArrayLiteral:
var openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile);
var closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
addOutlineRange(n, openBracket, closeBracket);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
}
depth++;
+278 -93
View File
@@ -6,7 +6,7 @@
/// <reference path='syntax\incrementalParser.ts' />
/// <reference path='outliningElementsCollector.ts' />
/// <reference path='getScriptLexicalStructureWalker.ts' />
/// <reference path='navigationBar.ts' />
/// <reference path='breakpoints.ts' />
/// <reference path='indentation.ts' />
/// <reference path='signatureHelp.ts' />
@@ -676,27 +676,47 @@ module ts {
if (!this.namedDeclarations) {
var sourceFile = this;
var namedDeclarations: Declaration[] = [];
var isExternalModule = ts.isExternalModule(sourceFile);
forEachChild(sourceFile, function visit(node: Node): boolean {
forEachChild(sourceFile, function visit(node: Node): void {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.Method:
var functionDeclaration = <FunctionDeclaration>node;
if (functionDeclaration.name && functionDeclaration.name.kind !== SyntaxKind.Missing) {
var lastDeclaration = namedDeclarations.length > 0 ?
namedDeclarations[namedDeclarations.length - 1] :
undefined;
// Check whether this declaration belongs to an "overload group".
if (lastDeclaration && functionDeclaration.symbol === lastDeclaration.symbol) {
// Overwrite the last declaration if it was an overload
// and this one is an implementation.
if (functionDeclaration.body && !(<FunctionDeclaration>lastDeclaration).body) {
namedDeclarations[namedDeclarations.length - 1] = functionDeclaration;
}
}
else {
namedDeclarations.push(node);
}
forEachChild(node, visit);
}
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.Method:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeLiteral:
if ((<Declaration>node).name) {
namedDeclarations.push(<Declaration>node);
}
forEachChild(node, visit);
break;
// fall through
case SyntaxKind.Constructor:
case SyntaxKind.VariableStatement:
case SyntaxKind.ModuleBlock:
case SyntaxKind.FunctionBlock:
@@ -704,19 +724,17 @@ module ts {
break;
case SyntaxKind.Parameter:
// Only consider properties defined as constructor parameters
if (!(node.flags & NodeFlags.AccessibilityModifier)) {
// Only consider properties defined as constructor parameters
break;
}
// fall through
case SyntaxKind.VariableDeclaration:
case SyntaxKind.EnumMember:
case SyntaxKind.Property:
namedDeclarations.push(<Declaration>node);
break;
}
// do not go any deeper
return undefined;
});
this.namedDeclarations = namedDeclarations;
@@ -835,6 +853,8 @@ module ts {
getSignatureAtPosition(fileName: string, position: number): SignatureInfo;
getRenameInfo(fileName: string, position: number): RenameInfo;
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[];
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[];
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[];
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[];
@@ -926,6 +946,11 @@ module ts {
newText: string;
}
export interface RenameLocation {
textSpan: TypeScript.TextSpan;
fileName: string;
}
export interface ReferenceEntry {
textSpan: TypeScript.TextSpan;
fileName: string;
@@ -1184,6 +1209,8 @@ module ts {
static primitiveType = "primitive type";
static label = "label";
static alias = "alias"
}
export class ScriptElementKindModifier {
@@ -1839,6 +1866,20 @@ module ts {
}
/// Helpers
export function getNodeModifiers(node: Node): string {
var flags = node.flags;
var result: string[] = [];
if (flags & NodeFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier);
if (flags & NodeFlags.Protected) result.push(ScriptElementKindModifier.protectedMemberModifier);
if (flags & NodeFlags.Public) result.push(ScriptElementKindModifier.publicMemberModifier);
if (flags & NodeFlags.Static) result.push(ScriptElementKindModifier.staticModifier);
if (flags & NodeFlags.Export) result.push(ScriptElementKindModifier.exportedModifier);
if (isInAmbientContext(node)) result.push(ScriptElementKindModifier.ambientModifier);
return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none;
}
function getTargetLabel(referenceNode: Node, labelName: string): Identifier {
while (referenceNode) {
if (referenceNode.kind === SyntaxKind.LabeledStatement && (<LabeledStatement>referenceNode).label.text === labelName) {
@@ -1972,8 +2013,8 @@ module ts {
var writer: (filename: string, data: string, writeByteOrderMark: boolean) => void = undefined;
// Check if the localized messages json is set, otherwise query the host for it
if (!TypeScript.LocalizedDiagnosticMessages) {
TypeScript.LocalizedDiagnosticMessages = host.getLocalizedDiagnosticMessages();
if (!localizedDiagnosticMessages) {
localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages();
}
function getSourceFile(filename: string): SourceFile {
@@ -2445,9 +2486,16 @@ module ts {
}
// TODO: this is a hack for now, we need a proper walking mechanism to verify that we have the correct node
var mappedNode = getNodeAtPosition(sourceFile, TypeScript.end(node) - 1);
if (isPunctuation(mappedNode.kind)) {
mappedNode = mappedNode.parent;
var precedingToken = findTokenOnLeftOfPosition(sourceFile, TypeScript.end(node));
var mappedNode: Node;
if (!precedingToken) {
mappedNode = sourceFile;
}
else if (isPunctuation(precedingToken.kind)) {
mappedNode = precedingToken.parent;
}
else {
mappedNode = precedingToken;
}
Debug.assert(mappedNode, "Could not map a Fidelity node to an AST node");
@@ -2469,6 +2517,12 @@ module ts {
if (mappedNode.kind === SyntaxKind.Identifier || mappedNode.kind === SyntaxKind.QualifiedName || mappedNode.kind === SyntaxKind.PropertyAccess) {
var symbol = typeInfoResolver.getSymbolInfo(mappedNode);
// This is an alias, follow what it aliases
if (symbol && symbol.flags & SymbolFlags.Import) {
symbol = typeInfoResolver.getAliasedSymbol(symbol);
}
if (symbol && symbol.flags & SymbolFlags.HasExports) {
// Extract module or enum members
forEachValue(symbol.exports, symbol => {
@@ -2519,7 +2573,7 @@ module ts {
else {
isMemberCompletion = false;
/// TODO filter meaning based on the current context
var symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace;
var symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Import;
var symbols = typeInfoResolver.getSymbolsInScope(mappedNode, symbolMeanings);
getCompletionEntriesFromSymbols(symbols, activeCompletionSession);
@@ -2608,6 +2662,7 @@ module ts {
if (result === ScriptElementKind.unknown) {
if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement;
if (flags & SymbolFlags.EnumMember) return ScriptElementKind.variableElement;
if (flags & SymbolFlags.Import) return ScriptElementKind.alias;
}
return result;
@@ -2675,25 +2730,10 @@ module ts {
: ScriptElementKindModifier.none;
}
function getNodeModifiers(node: Node): string {
var flags = node.flags;
var result: string[] = [];
if (flags & NodeFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier);
if (flags & NodeFlags.Protected) result.push(ScriptElementKindModifier.protectedMemberModifier);
if (flags & NodeFlags.Public) result.push(ScriptElementKindModifier.publicMemberModifier);
if (flags & NodeFlags.Static) result.push(ScriptElementKindModifier.staticModifier);
if (flags & NodeFlags.Export) result.push(ScriptElementKindModifier.exportedModifier);
if (isInAmbientContext(node)) result.push(ScriptElementKindModifier.ambientModifier);
return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none;
}
function getSymbolDisplayPartsDocumentationAndSymbolKind(symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node, typeResolver: TypeChecker, location: Node) {
var displayParts: SymbolDisplayPart[] = [];
var documentation: SymbolDisplayPart[];
var symbolFlags = typeResolver.getRootSymbol(symbol).flags;
var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags);
var hasAddedSymbolInfo: boolean;
// Class at constructor site need to be shown as constructor apart from property,method, vars
@@ -2952,14 +2992,19 @@ module ts {
function getQuickInfoAtPosition(fileName: string, position: number): QuickInfo {
synchronizeHostData();
fileName = TypeScript.switchToForwardSlashes(fileName);
var sourceFile = getSourceFile(fileName);
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingPropertyName(sourceFile, position);
if (!node) {
return undefined;
}
var symbol = typeInfoResolver.getSymbolInfo(node);
if (!symbol) {
return undefined;
}
var symbol = typeInfoResolver.getSymbolInfo(node);
if (!symbol) {
@@ -3059,7 +3104,7 @@ module ts {
filename = TypeScript.switchToForwardSlashes(filename);
var sourceFile = getSourceFile(filename);
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingPropertyName(sourceFile, position);
if (!node) {
return undefined;
}
@@ -3074,7 +3119,8 @@ module ts {
/// Triple slash reference comments
var comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined);
if (comment) {
var targetFilename = normalizePath(combinePaths(getDirectoryPath(filename), comment.filename));
var targetFilename = isRootedDiskPath(comment.filename) ? comment.filename : combinePaths(getDirectoryPath(filename), comment.filename);
targetFilename = normalizePath(targetFilename);
if (program.getSourceFile(targetFilename)) {
return [{
fileName: targetFilename,
@@ -3099,7 +3145,7 @@ module ts {
var result: DefinitionInfo[] = [];
var declarations = symbol.getDeclarations();
var symbolName = typeInfoResolver.symbolToString(symbol, node);
var symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
var symbolKind = getSymbolKind(symbol);
var containerSymbol = symbol.parent;
var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : "";
@@ -3123,14 +3169,14 @@ module ts {
filename = TypeScript.switchToForwardSlashes(filename);
var sourceFile = getSourceFile(filename);
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingWord(sourceFile, position);
if (!node) {
return undefined;
}
if (node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.SuperKeyword ||
isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) {
return getReferencesForNode(node, [sourceFile]);
return getReferencesForNode(node, [sourceFile], /*findInStrings:*/ false, /*findInComments:*/ false);
}
switch (node.kind) {
@@ -3562,13 +3608,21 @@ module ts {
}
}
function getReferencesAtPosition(filename: string, position: number): ReferenceEntry[] {
function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] {
return findReferences(fileName, position, findInStrings, findInComments);
}
function getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
return findReferences(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false);
}
function findReferences(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReferenceEntry[] {
synchronizeHostData();
filename = TypeScript.switchToForwardSlashes(filename);
var sourceFile = getSourceFile(filename);
fileName = TypeScript.switchToForwardSlashes(fileName);
var sourceFile = getSourceFile(fileName);
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingPropertyName(sourceFile, position);
if (!node) {
return undefined;
}
@@ -3582,10 +3636,11 @@ module ts {
return undefined;
}
return getReferencesForNode(node, program.getSourceFiles());
Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.NumericLiteral || node.kind === SyntaxKind.StringLiteral);
return getReferencesForNode(node, program.getSourceFiles(), findInStrings, findInComments);
}
function getReferencesForNode(node: Node, sourceFiles: SourceFile[]): ReferenceEntry[] {
function getReferencesForNode(node: Node, sourceFiles: SourceFile[], findInStrings: boolean, findInComments: boolean): ReferenceEntry[] {
// Labels
if (isLabelName(node)) {
if (isJumpStatementTarget(node)) {
@@ -3635,7 +3690,7 @@ module ts {
if (scope) {
result = [];
getReferencesInNode(scope, symbol, symbolName, node, searchMeaning, result);
getReferencesInNode(scope, symbol, symbolName, node, searchMeaning, findInStrings, findInComments, result);
}
else {
forEach(sourceFiles, sourceFile => {
@@ -3643,7 +3698,7 @@ module ts {
if (lookUp(sourceFile.identifiers, symbolName)) {
result = result || [];
getReferencesInNode(sourceFile, symbol, symbolName, node, searchMeaning, result);
getReferencesInNode(sourceFile, symbol, symbolName, node, searchMeaning, findInStrings, findInComments, result);
}
});
}
@@ -3751,7 +3806,7 @@ module ts {
forEach(possiblePositions, position => {
cancellationToken.throwIfCancellationRequested();
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingWord(sourceFile, position);
if (!node || node.getWidth() !== labelName.length) {
return;
}
@@ -3795,8 +3850,16 @@ module ts {
* tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
* searchLocation: a node where the search value
*/
function getReferencesInNode(container: Node, searchSymbol: Symbol, searchText: string, searchLocation: Node, searchMeaning: SearchMeaning, result: ReferenceEntry[]): void {
function getReferencesInNode(container: Node,
searchSymbol: Symbol,
searchText: string,
searchLocation: Node,
searchMeaning: SearchMeaning,
findInStrings: boolean,
findInComments: boolean,
result: ReferenceEntry[]): void {
var sourceFile = container.getSourceFile();
var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</
var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd());
@@ -3807,8 +3870,19 @@ module ts {
forEach(possiblePositions, position => {
cancellationToken.throwIfCancellationRequested();
var referenceLocation = getNodeAtPosition(sourceFile, position);
var referenceLocation = getTouchingPropertyName(sourceFile, position);
if (!isValidReferencePosition(referenceLocation, searchText)) {
// This wasn't the start of a token. Check to see if it might be a
// match in a comment or string if that's what the caller is asking
// for.
if ((findInStrings && isInString(position)) ||
(findInComments && isInComment(position))) {
result.push({
fileName: sourceFile.filename,
textSpan: new TypeScript.TextSpan(position, searchText.length),
isWriteAccess: false
});
}
return;
}
@@ -3829,6 +3903,32 @@ module ts {
}
});
}
function isInString(position: number) {
var token = getTokenAtPosition(sourceFile, position);
return token && token.kind === SyntaxKind.StringLiteral && position > token.getStart();
}
function isInComment(position: number) {
var token = getTokenAtPosition(sourceFile, position);
if (token && position < token.getStart()) {
// First, we have to see if this position actually landed in a comment.
var commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
// Then we want to make sure that it wasn't in a "///<" directive comment
// We don't want to unintentionally update a file name.
return forEach(commentRanges, c => {
if (c.pos < position && position < c.end) {
var commentText = sourceFile.text.substring(c.pos, c.end);
if (!tripleSlashDirectivePrefixRegex.test(commentText)) {
return true;
}
}
});
}
return false;
}
}
function getReferencesForSuperKeyword(superKeyword: Node): ReferenceEntry[]{
@@ -3859,7 +3959,7 @@ module ts {
forEach(possiblePositions, position => {
cancellationToken.throwIfCancellationRequested();
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingWord(sourceFile, position);
if (!node || node.kind !== SyntaxKind.SuperKeyword) {
return;
@@ -3925,7 +4025,7 @@ module ts {
forEach(possiblePositions, position => {
cancellationToken.throwIfCancellationRequested();
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingWord(sourceFile, position);
if (!node || node.kind !== SyntaxKind.ThisKeyword) {
return;
}
@@ -3983,7 +4083,7 @@ module ts {
}
function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, result: Symbol[]): void {
if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
if (symbol && symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
forEach(symbol.getDeclarations(), declaration => {
if (declaration.kind === SyntaxKind.ClassDeclaration) {
getPropertySymbolFromTypeReference((<ClassDeclaration>declaration).baseType);
@@ -3998,14 +4098,15 @@ module ts {
function getPropertySymbolFromTypeReference(typeReference: TypeReferenceNode) {
if (typeReference) {
// TODO: move to getTypeOfNode instead
var typeReferenceSymbol = typeInfoResolver.getSymbolInfo(typeReference.typeName);
if (typeReferenceSymbol) {
var propertySymbol = typeReferenceSymbol.members[propertyName];
if (propertySymbol) result.push(typeReferenceSymbol.members[propertyName]);
var type = typeInfoResolver.getTypeOfNode(typeReference);
if (type) {
var propertySymbol = typeInfoResolver.getPropertyOfType(type, propertyName);
if (propertySymbol) {
result.push(propertySymbol);
}
// Visit the typeReference as well to see if it directly or indirectly use that property
getPropertySymbolsFromBaseTypes(typeReferenceSymbol, propertyName, result);
getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result);
}
}
}
@@ -4320,7 +4421,8 @@ module ts {
filename = TypeScript.switchToForwardSlashes(filename);
var compilerOptions = program.getCompilerOptions();
var targetSourceFile = program.getSourceFile(filename); // Current selected file to be output
var emitToSingleFile = ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions);
// If --out flag is not specified, shouldEmitToOwnFile is true. Otherwise shouldEmitToOwnFile is false.
var shouldEmitToOwnFile = ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions);
var emitDeclaration = compilerOptions.declaration;
var emitOutput: EmitOutput = {
outputFiles: [],
@@ -4341,7 +4443,7 @@ module ts {
var syntacticDiagnostics: Diagnostic[] = [];
var containSyntacticErrors = false;
if (emitToSingleFile) {
if (shouldEmitToOwnFile) {
// Check only the file we want to emit
containSyntacticErrors = containErrors(program.getDiagnostics(targetSourceFile));
} else {
@@ -4368,7 +4470,7 @@ module ts {
// Perform semantic and force a type check before emit to ensure that all symbols are updated
// EmitFiles will report if there is an error from TypeChecker and Emitter
// Depend whether we will have to emit into a single file or not either emit only selected file in the project, emit all files into a single file
var emitFilesResult = emitToSingleFile ? getFullTypeCheckChecker().emitFiles(targetSourceFile) : getFullTypeCheckChecker().emitFiles();
var emitFilesResult = getFullTypeCheckChecker().emitFiles(targetSourceFile);
emitOutput.emitOutputStatus = emitFilesResult.emitResultStatus;
// Reset writer back to undefined to make sure that we produce an error message if CompilerHost.writeFile method is called when we are not in getEmitOutput
@@ -4527,10 +4629,10 @@ module ts {
return TypeScript.Services.Breakpoints.getBreakpointLocation(syntaxtree, position);
}
function getNavigationBarItems(filename: string) {
function getNavigationBarItems(filename: string): NavigationBarItem[] {
filename = TypeScript.switchToForwardSlashes(filename);
var syntaxTree = getSyntaxTree(filename);
return new TypeScript.Services.NavigationBarItemGetter().getItems(syntaxTree.sourceUnit());
return NavigationBar.getNavigationBarItems(getCurrentSourceFile(filename));
}
function getSemanticClassifications(fileName: string, span: TypeScript.TextSpan): ClassifiedSpan[] {
@@ -4544,7 +4646,7 @@ module ts {
return result;
function classifySymbol(symbol: Symbol) {
function classifySymbol(symbol: Symbol, isInTypePosition: boolean) {
var flags = symbol.getFlags();
if (flags & SymbolFlags.Class) {
@@ -4553,14 +4655,16 @@ module ts {
else if (flags & SymbolFlags.Enum) {
return ClassificationTypeNames.enumName;
}
else if (flags & SymbolFlags.Interface) {
return ClassificationTypeNames.interfaceName;
}
else if (flags & SymbolFlags.Module) {
return ClassificationTypeNames.moduleName;
}
else if (flags & SymbolFlags.TypeParameter) {
return ClassificationTypeNames.typeParameterName;
else if (isInTypePosition) {
if (flags & SymbolFlags.Interface) {
return ClassificationTypeNames.interfaceName;
}
else if (flags & SymbolFlags.TypeParameter) {
return ClassificationTypeNames.typeParameterName;
}
}
}
@@ -4570,7 +4674,7 @@ module ts {
if (node.kind === SyntaxKind.Identifier && node.getWidth() > 0) {
var symbol = typeInfoResolver.getSymbolInfo(node);
if (symbol) {
var type = classifySymbol(symbol);
var type = classifySymbol(symbol, isTypeNode(node) || isTypeDeclarationName(node));
if (type) {
result.push({
textSpan: new TypeScript.TextSpan(node.getStart(), node.getWidth()),
@@ -4739,7 +4843,7 @@ module ts {
var sourceFile = getCurrentSourceFile(filename);
var result: TypeScript.TextSpan[] = [];
var token = getTokenAtPosition(sourceFile, position);
var token = getTouchingToken(sourceFile, position);
if (token.getStart(sourceFile) === position) {
var matchKind = getMatchingTokenKind(token);
@@ -5023,7 +5127,7 @@ module ts {
fileName = TypeScript.switchToForwardSlashes(fileName);
var sourceFile = getSourceFile(fileName);
var node = getNodeAtPosition(sourceFile, position);
var node = getTouchingWord(sourceFile, position);
// Can only rename an identifier.
if (node && node.kind === SyntaxKind.Identifier) {
@@ -5087,6 +5191,7 @@ module ts {
getBreakpointStatementAtPosition: getBreakpointStatementAtPosition,
getNavigateToItems: getNavigateToItems,
getRenameInfo: getRenameInfo,
findRenameLocations: findRenameLocations,
getNavigationBarItems: getNavigationBarItems,
getOutliningSpans: getOutliningSpans,
getTodoComments: getTodoComments,
@@ -5108,26 +5213,58 @@ module ts {
/// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
/// we have a series of divide operator. this list allows us to be more accurate by ruling out
/// locations where a regexp cannot exist.
var noRegexTable: boolean[];
if (!noRegexTable) {
noRegexTable = [];
noRegexTable[SyntaxKind.Identifier] = true;
noRegexTable[SyntaxKind.StringLiteral] = true;
noRegexTable[SyntaxKind.NumericLiteral] = true;
noRegexTable[SyntaxKind.RegularExpressionLiteral] = true;
noRegexTable[SyntaxKind.ThisKeyword] = true;
noRegexTable[SyntaxKind.PlusPlusToken] = true;
noRegexTable[SyntaxKind.MinusMinusToken] = true;
noRegexTable[SyntaxKind.CloseParenToken] = true;
noRegexTable[SyntaxKind.CloseBracketToken] = true;
noRegexTable[SyntaxKind.CloseBraceToken] = true;
noRegexTable[SyntaxKind.TrueKeyword] = true;
noRegexTable[SyntaxKind.FalseKeyword] = true;
var noRegexTable: boolean[] = [];
noRegexTable[SyntaxKind.Identifier] = true;
noRegexTable[SyntaxKind.StringLiteral] = true;
noRegexTable[SyntaxKind.NumericLiteral] = true;
noRegexTable[SyntaxKind.RegularExpressionLiteral] = true;
noRegexTable[SyntaxKind.ThisKeyword] = true;
noRegexTable[SyntaxKind.PlusPlusToken] = true;
noRegexTable[SyntaxKind.MinusMinusToken] = true;
noRegexTable[SyntaxKind.CloseParenToken] = true;
noRegexTable[SyntaxKind.CloseBracketToken] = true;
noRegexTable[SyntaxKind.CloseBraceToken] = true;
noRegexTable[SyntaxKind.TrueKeyword] = true;
noRegexTable[SyntaxKind.FalseKeyword] = true;
function isAccessibilityModifier(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return true;
}
return false;
}
/** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
function canFollow(keyword1: SyntaxKind, keyword2: SyntaxKind) {
if (isAccessibilityModifier(keyword1)) {
if (keyword2 === SyntaxKind.GetKeyword ||
keyword2 === SyntaxKind.SetKeyword ||
keyword2 === SyntaxKind.ConstructorKeyword ||
keyword2 === SyntaxKind.StaticKeyword) {
// Allow things like "public get", "public constructor" and "public static".
// These are all legal.
return true;
}
// Any other keyword following "public" is actually an identifier an not a real
// keyword.
return false;
}
// Assume any other keyword combination is legal. This can be refined in the future
// if there are more cases we want the classifier to be better at.
return true;
}
function getClassificationsForLine(text: string, lexState: EndOfLineState): ClassificationResult {
var offset = 0;
var lastTokenOrCommentEnd = 0;
var token = SyntaxKind.Unknown;
var lastNonTriviaToken = SyntaxKind.Unknown;
// If we're in a string literal, then prepend: "\
@@ -5157,8 +5294,27 @@ module ts {
entries: []
};
var token = SyntaxKind.Unknown;
// We can run into an unfortunate interaction between the lexical and syntactic classifier
// when the user is typing something generic. Consider the case where the user types:
//
// Foo<number
//
// From the lexical classifier's perspective, 'number' is a keyword, and so the word will
// be classified as such. However, from the syntactic classifier's tree-based perspective
// this is simply an expression with the identifier 'number' on the RHS of the less than
// token. So the classification will go back to being an identifier. The moment the user
// types again, number will become a keyword, then an identifier, etc. etc.
//
// To try to avoid this problem, we avoid classifying contextual keywords as keywords
// when the user is potentially typing something generic. We just can't do a good enough
// job at the lexical level, and so well leave it up to the syntactic classifier to make
// the determination.
//
// In order to determine if the user is potentially typing something generic, we use a
// weak heuristic where we track < and > tokens. It's a weak heuristic, but should
// work well enough in practice.
var angleBracketStack = 0;
do {
token = scanner.scan();
@@ -5171,6 +5327,35 @@ module ts {
else if (lastNonTriviaToken === SyntaxKind.DotToken && isKeyword(token)) {
token = SyntaxKind.Identifier;
}
else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) {
// We have two keywords in a row. Only treat the second as a keyword if
// it's a sequence that could legally occur in the language. Otherwise
// treat it as an identifier. This way, if someone writes "private var"
// we recognize that 'var' is actually an identifier here.
token = SyntaxKind.Identifier;
}
else if (lastNonTriviaToken === SyntaxKind.Identifier &&
token === SyntaxKind.LessThanToken) {
// Could be the start of something generic. Keep track of that by bumping
// up the current count of generic contexts we may be in.
angleBracketStack++;
}
else if (token === SyntaxKind.GreaterThanToken && angleBracketStack > 0) {
// If we think we're currently in something generic, then mark that that
// generic entity is complete.
angleBracketStack--;
}
else if (token === SyntaxKind.AnyKeyword ||
token === SyntaxKind.StringKeyword ||
token === SyntaxKind.NumberKeyword ||
token === SyntaxKind.BooleanKeyword) {
if (angleBracketStack > 0) {
// If it looks like we're could be in something generic, don't classify this
// as a keyword. We may just get overwritten by the syntactic classifier,
// causing a noisy experience for the user.
token = SyntaxKind.Identifier;
}
}
lastNonTriviaToken = token;
}
+18 -8
View File
@@ -99,6 +99,12 @@ module ts {
*/
getRenameInfo(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string, textSpan: { start: number, length: number } }[]
*/
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
@@ -165,7 +171,7 @@ module ts {
}
/// TODO: delete this, it is only needed until the VS interface is updated
enum LanguageVersion {
export enum LanguageVersion {
EcmaScript3 = 0,
EcmaScript5 = 1,
}
@@ -341,12 +347,6 @@ module ts {
}
var options = compilationSettingsToCompilerOptions(<CompilerOptions>JSON.parse(<any>settingsJson));
/// TODO: this should be pushed into VS.
/// We can not ask the LS instance to resolve, as this will lead to asking the host about files it does not know about,
/// something it is not designed to handle. for now make sure we never get a "noresolve == false".
/// This value should not matter, as the host runs resolution logic independently
options.noResolve = true;
return options;
}
@@ -372,6 +372,7 @@ module ts {
if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") {
return null;
}
try {
return JSON.parse(diagnosticMessagesJson);
}
@@ -498,7 +499,8 @@ module ts {
start: diagnostic.start,
length: diagnostic.length,
/// TODO: no need for the tolowerCase call
category: DiagnosticCategory[diagnostic.category].toLowerCase()
category: DiagnosticCategory[diagnostic.category].toLowerCase(),
code: diagnostic.code
};
}
@@ -643,6 +645,14 @@ module ts {
});
}
public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string {
return this.forwardJSONCall(
"findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")",
() => {
return this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments);
});
}
/// GET BRACE MATCHING
public getBraceMatchingAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
+75 -67
View File
@@ -172,15 +172,15 @@ module ts.SignatureHelp {
return undefined;
}
var argumentList = getContainingArgumentList(startingToken);
var argumentInfo = getContainingArgumentInfo(startingToken);
cancellationToken.throwIfCancellationRequested();
// Semantic filtering of signature help
if (!argumentList) {
if (!argumentInfo) {
return undefined;
}
var call = <CallExpression>argumentList.parent;
var call = <CallExpression>argumentInfo.list.parent;
var candidates = <Signature[]>[];
var resolvedSignature = typeInfoResolver.getResolvedSignature(call, candidates);
cancellationToken.throwIfCancellationRequested();
@@ -189,13 +189,13 @@ module ts.SignatureHelp {
return undefined;
}
return createSignatureHelpItems(candidates, resolvedSignature, argumentList);
return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo);
/**
* If node is an argument, returns its index in the argument list.
* If not, returns -1.
*/
function getImmediatelyContainingArgumentList(node: Node): Node {
function getImmediatelyContainingArgumentInfo(node: Node): ListItemInfo {
if (node.parent.kind !== SyntaxKind.CallExpression && node.parent.kind !== SyntaxKind.NewExpression) {
return undefined;
}
@@ -216,10 +216,14 @@ module ts.SignatureHelp {
var parent = <CallExpression>node.parent;
// Find out if 'node' is an argument, a type argument, or neither
if (node.kind === SyntaxKind.LessThanToken || node.kind === SyntaxKind.OpenParenToken) {
// Find the list that starts right *after* the < or ( token
// Find the list that starts right *after* the < or ( token.
// If the user has just opened a list, consider this item 0.
var list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile);
Debug.assert(list);
return list;
return {
list: list,
listItemIndex: 0
};
}
if (node.kind === SyntaxKind.GreaterThanToken
@@ -228,18 +232,24 @@ module ts.SignatureHelp {
return undefined;
}
return findContainingList(node);
return findListItemInfo(node);
}
function getContainingArgumentList(node: Node): Node {
function getContainingArgumentInfo(node: Node): ListItemInfo {
for (var n = node; n.kind !== SyntaxKind.SourceFile; n = n.parent) {
if (n.kind === SyntaxKind.FunctionBlock) {
return undefined;
}
var argumentList = getImmediatelyContainingArgumentList(n);
if (argumentList) {
return argumentList;
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
if (n.pos < n.parent.pos || n.end > n.parent.end) {
Debug.fail("Node of kind " + SyntaxKind[n.kind] + " is not a subspan of its parent of kind " + SyntaxKind[n.parent.kind]);
}
var argumentInfo = getImmediatelyContainingArgumentInfo(n);
if (argumentInfo) {
return argumentInfo;
}
@@ -248,7 +258,35 @@ module ts.SignatureHelp {
return undefined;
}
function createSignatureHelpItems(candidates: Signature[], bestSignature: Signature, argumentListOrTypeArgumentList: Node): SignatureHelpItems {
/**
* The selectedItemIndex could be negative for several reasons.
* 1. There are too many arguments for all of the overloads
* 2. None of the overloads were type compatible
* The solution here is to try to pick the best overload by picking
* either the first one that has an appropriate number of parameters,
* or the one with the most parameters.
*/
function selectBestInvalidOverloadIndex(candidates: Signature[], argumentCount: number): number {
var maxParamsSignatureIndex = -1;
var maxParams = -1;
for (var i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) {
return i;
}
if (candidate.parameters.length > maxParams) {
maxParams = candidate.parameters.length;
maxParamsSignatureIndex = i;
}
}
return maxParamsSignatureIndex;
}
function createSignatureHelpItems(candidates: Signature[], bestSignature: Signature, argumentInfoOrTypeArgumentInfo: ListItemInfo): SignatureHelpItems {
var argumentListOrTypeArgumentList = argumentInfoOrTypeArgumentInfo.list;
var items: SignatureHelpItem[] = map(candidates, candidateSignature => {
var parameters = candidateSignature.parameters;
var parameterHelpItems: SignatureHelpParameter[] = parameters.length === 0 ? emptyArray : map(parameters, p => {
@@ -321,11 +359,6 @@ module ts.SignatureHelp {
};
});
var selectedItemIndex = candidates.indexOf(bestSignature);
if (selectedItemIndex < 0) {
selectedItemIndex = 0;
}
// We use full start and skip trivia on the end because we want to include trivia on
// both sides. For example,
//
@@ -338,63 +371,38 @@ module ts.SignatureHelp {
var applicableSpanEnd = skipTrivia(sourceFile.text, argumentListOrTypeArgumentList.end, /*stopAfterLineBreak*/ false);
var applicableSpan = new TypeScript.TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
var state = getSignatureHelpCurrentArgumentState(sourceFile, position, applicableSpanStart);
// The listItemIndex we got back includes commas. Our goal is to return the index of the proper
// item (not including commas). Here are some examples:
// 1. foo(a, b, c $) -> the listItemIndex is 4, we want to return 2
// 2. foo(a, b, $ c) -> listItemIndex is 3, we want to return 2
// 3. foo($a) -> listItemIndex is 0, we want to return 0
//
// In general, we want to subtract the number of commas before the current index.
// But if we are on a comma, we also want to pretend we are on the argument *following*
// the comma. That amounts to taking the ceiling of half the index.
var argumentIndex = (argumentInfoOrTypeArgumentInfo.listItemIndex + 1) >> 1;
// argumentCount is the number of commas plus one, unless the list is completely empty,
// in which case there are 0.
var argumentCount = argumentListOrTypeArgumentList.getChildCount() === 0
? 0
: 1 + countWhere(argumentListOrTypeArgumentList.getChildren(), arg => arg.kind === SyntaxKind.CommaToken);
var selectedItemIndex = candidates.indexOf(bestSignature);
if (selectedItemIndex < 0) {
selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount);
}
return {
items: items,
applicableSpan: applicableSpan,
selectedItemIndex: selectedItemIndex,
argumentIndex: state.argumentIndex,
argumentCount: state.argumentCount
argumentIndex: argumentIndex,
argumentCount: argumentCount
};
}
}
function getSignatureHelpCurrentArgumentState(sourceFile: SourceFile, position: number, applicableSpanStart: number): { argumentIndex: number; argumentCount: number } {
var tokenPrecedingSpanStart = findPrecedingToken(applicableSpanStart, sourceFile);
if (!tokenPrecedingSpanStart) {
return undefined;
}
if (tokenPrecedingSpanStart.kind !== SyntaxKind.OpenParenToken && tokenPrecedingSpanStart.kind !== SyntaxKind.LessThanToken) {
// The span start must have moved backward in the file (for example if the open paren was backspaced)
return undefined;
}
var tokenPrecedingCurrentPosition = findPrecedingToken(position, sourceFile);
var call = <CallExpression>tokenPrecedingSpanStart.parent;
Debug.assert(call.kind === SyntaxKind.CallExpression || call.kind === SyntaxKind.NewExpression, "wrong call kind " + SyntaxKind[call.kind]);
if (tokenPrecedingCurrentPosition.kind === SyntaxKind.CloseParenToken || tokenPrecedingCurrentPosition.kind === SyntaxKind.GreaterThanToken) {
if (tokenPrecedingCurrentPosition.parent === call) {
// This call expression is complete. Stop signature help.
return undefined;
}
}
var argumentListOrTypeArgumentList = getChildListThatStartsWithOpenerToken(call, tokenPrecedingSpanStart, sourceFile);
// Debug.assert(argumentListOrTypeArgumentList.getChildCount() === 0 || argumentListOrTypeArgumentList.getChildCount() % 2 === 1, "Even number of children");
// The call might be finished, but incorrectly. Check if we are still within the bounds of the call
if (position > skipTrivia(sourceFile.text, argumentListOrTypeArgumentList.end, /*stopAfterLineBreak*/ false)) {
return undefined;
}
var numberOfCommas = countWhere(argumentListOrTypeArgumentList.getChildren(), arg => arg.kind === SyntaxKind.CommaToken);
var argumentCount = numberOfCommas + 1;
if (argumentCount <= 1) {
return { argumentIndex: 0, argumentCount: argumentCount };
}
var indexOfNodeContainingPosition = findListItemIndexContainingPosition(argumentListOrTypeArgumentList, position);
// indexOfNodeContainingPosition checks that position is between pos and end of each child, so it is
// possible that we are to the right of all children. Assume that we are still within
// the applicable span and that we are typing the last argument
// Alternatively, we could be in range of one of the arguments, in which case we need to divide
// by 2 to exclude commas. Use bit shifting in order to take the floor of the division.
var argumentIndex = indexOfNodeContainingPosition < 0 ? argumentCount - 1 : indexOfNodeContainingPosition >> 1;
return { argumentIndex: argumentIndex, argumentCount: argumentCount };
}
function getChildListThatStartsWithOpenerToken(parent: Node, openerToken: Node, sourceFile: SourceFile): Node {
var children = parent.getChildren(sourceFile);
var indexOfOpenerToken = children.indexOf(openerToken);
+67 -28
View File
@@ -27,11 +27,18 @@ module ts {
// for the position of the relevant node (or comma).
var syntaxList = forEach(node.parent.getChildren(), c => {
// find syntax list that covers the span of the node
if (c.kind == SyntaxKind.SyntaxList && c.pos <= node.pos && c.end >= node.end) {
if (c.kind === SyntaxKind.SyntaxList && c.pos <= node.pos && c.end >= node.end) {
return c;
}
});
// syntaxList should not be undefined here. If it is, there is a problem. Find out if
// there at least is a child that is a list.
if (!syntaxList) {
Debug.assert(findChildOfKind(node.parent, SyntaxKind.SyntaxList),
"Node of kind " + SyntaxKind[node.parent.kind] + " has no list children");
}
return syntaxList;
}
@@ -50,34 +57,54 @@ module ts {
return -1;
}
/** Get a token that contains the position. This is guaranteed to return a token, the position can be in the
* leading trivia or within the token text.
*/
export function getTokenAtPosition(sourceFile: SourceFile, position: number) {
var current: Node = sourceFile;
outer: while (true) {
// find the child that has this
for (var i = 0, n = current.getChildCount(); i < n; i++) {
var child = current.getChildAt(i);
if (child.getFullStart() <= position && position < child.getEnd()) {
current = child;
continue outer;
}
}
return current;
}
/* Gets the token whose text has range [start, end) and
* position >= start and (position < end or (position === end && token is keyword or identifier))
*/
export function getTouchingWord(sourceFile: SourceFile, position: number): Node {
return getTouchingToken(sourceFile, position, isWord);
}
/** Get the token whose text contains the position, or the containing node. */
export function getNodeAtPosition(sourceFile: SourceFile, position: number) {
/* Gets the token whose text has range [start, end) and position >= start
* and (position < end or (position === end && token is keyword or identifier or numeric\string litera))
*/
export function getTouchingPropertyName(sourceFile: SourceFile, position: number): Node {
return getTouchingToken(sourceFile, position, isPropertyName);
}
/** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */
export function getTouchingToken(sourceFile: SourceFile, position: number, includeItemAtEndPosition?: (n: Node) => boolean): Node {
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition);
}
/** Returns a token if position is in [start-of-leading-trivia, end) */
export function getTokenAtPosition(sourceFile: SourceFile, position: number): Node {
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined);
}
/** Get the token whose text contains the position */
function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean): Node {
var current: Node = sourceFile;
outer: while (true) {
// find the child that has this
for (var i = 0, n = current.getChildCount(); i < n; i++) {
if (isToken(current)) {
// exit early
return current;
}
// find the child that contains 'position'
for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) {
var child = current.getChildAt(i);
if (child.getStart() <= position && position < child.getEnd()) {
current = child;
continue outer;
var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile);
if (start <= position) {
if (position < child.getEnd()) {
current = child;
continue outer;
}
else if (includeItemAtEndPosition && child.getEnd() === position) {
var previousToken = findPrecedingToken(position, sourceFile, child);
if (previousToken && includeItemAtEndPosition(previousToken)) {
return previousToken;
}
}
}
}
return current;
@@ -130,8 +157,8 @@ module ts {
}
}
export function findPrecedingToken(position: number, sourceFile: SourceFile): Node {
return find(sourceFile);
export function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node): Node {
return find(startNode || sourceFile);
function findRightmostToken(n: Node): Node {
if (isToken(n)) {
@@ -167,7 +194,7 @@ module ts {
}
}
Debug.assert(n.kind === SyntaxKind.SourceFile);
Debug.assert(startNode || n.kind === SyntaxKind.SourceFile);
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
@@ -202,7 +229,19 @@ module ts {
return n.kind !== SyntaxKind.SyntaxList || n.getChildCount() !== 0;
}
function isToken(n: Node): boolean {
export function isToken(n: Node): boolean {
return n.kind >= SyntaxKind.FirstToken && n.kind <= SyntaxKind.LastToken;
}
function isKeyword(n: Node): boolean {
return n.kind >= SyntaxKind.FirstKeyword && n.kind <= SyntaxKind.LastKeyword;
}
function isWord(n: Node): boolean {
return n.kind === SyntaxKind.Identifier || isKeyword(n);
}
function isPropertyName(n: Node): boolean {
return n.kind === SyntaxKind.StringLiteral || n.kind === SyntaxKind.NumericLiteral || isWord(n);
}
}