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 {