mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge branch 'master' into completionFixes
Conflicts: src/services/services.ts
This commit is contained in:
+1459
-772
File diff suppressed because it is too large
Load Diff
@@ -82,7 +82,7 @@ module ts {
|
||||
return array1.concat(array2);
|
||||
}
|
||||
|
||||
export function uniqueElements<T>(array: T[]): T[] {
|
||||
export function deduplicate<T>(array: T[]): T[] {
|
||||
if (array) {
|
||||
var result: T[] = [];
|
||||
for (var i = 0, len = array.length; i < len; i++) {
|
||||
|
||||
@@ -114,6 +114,7 @@ module ts {
|
||||
Cannot_compile_external_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile external modules unless the '--module' flag is provided." },
|
||||
Filename_0_differs_from_already_included_filename_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "Filename '{0}' differs from already included filename '{1}' only in casing" },
|
||||
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
|
||||
An_enum_member_cannot_have_a_numeric_name: { code: 1151, category: DiagnosticCategory.Error, key: "An enum member cannot have a numeric name." },
|
||||
Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." },
|
||||
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
|
||||
Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." },
|
||||
@@ -180,8 +181,6 @@ module ts {
|
||||
The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: DiagnosticCategory.Error, key: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
|
||||
Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: DiagnosticCategory.Error, key: "Invalid left-hand side of assignment expression." },
|
||||
Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: DiagnosticCategory.Error, key: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." },
|
||||
No_best_common_type_exists_between_0_1_and_2: { code: 2366, category: DiagnosticCategory.Error, key: "No best common type exists between '{0}', '{1}', and '{2}'." },
|
||||
No_best_common_type_exists_between_0_and_1: { code: 2367, category: DiagnosticCategory.Error, key: "No best common type exists between '{0}' and '{1}'." },
|
||||
Type_parameter_name_cannot_be_0: { code: 2368, category: DiagnosticCategory.Error, key: "Type parameter name cannot be '{0}'" },
|
||||
A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: DiagnosticCategory.Error, key: "A parameter property is only allowed in a constructor implementation." },
|
||||
A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: DiagnosticCategory.Error, key: "A rest parameter must be of an array type." },
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"category": "Error",
|
||||
"code": 1005
|
||||
},
|
||||
"A file cannot have a reference to itself.": {
|
||||
"A file cannot have a reference to itself.": {
|
||||
"category": "Error",
|
||||
"code": 1006
|
||||
},
|
||||
@@ -187,7 +187,7 @@
|
||||
"category": "Error",
|
||||
"code": 1066
|
||||
},
|
||||
"Unexpected token. A constructor, method, accessor, or property was expected." : {
|
||||
"Unexpected token. A constructor, method, accessor, or property was expected.": {
|
||||
"category": "Error",
|
||||
"code": 1068
|
||||
},
|
||||
@@ -444,9 +444,13 @@
|
||||
"code": 1149
|
||||
},
|
||||
"'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead.": {
|
||||
"category": "Error",
|
||||
"code": 1150
|
||||
},
|
||||
"category": "Error",
|
||||
"code": 1150
|
||||
},
|
||||
"An enum member cannot have a numeric name.": {
|
||||
"category": "Error",
|
||||
"code": 1151
|
||||
},
|
||||
|
||||
"Duplicate identifier '{0}'.": {
|
||||
"category": "Error",
|
||||
@@ -556,7 +560,7 @@
|
||||
"category": "Error",
|
||||
"code": 2326
|
||||
},
|
||||
"Property '{0}' is optional in type '{1}' but required in type '{2}'.": {
|
||||
"Property '{0}' is optional in type '{1}' but required in type '{2}'.": {
|
||||
"category": "Error",
|
||||
"code": 2327
|
||||
},
|
||||
@@ -712,14 +716,6 @@
|
||||
"category": "Error",
|
||||
"code": 2365
|
||||
},
|
||||
"No best common type exists between '{0}', '{1}', and '{2}'.": {
|
||||
"category": "Error",
|
||||
"code": 2366
|
||||
},
|
||||
"No best common type exists between '{0}' and '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 2367
|
||||
},
|
||||
"Type parameter name cannot be '{0}'": {
|
||||
"category": "Error",
|
||||
"code": 2368
|
||||
|
||||
+36
-26
@@ -4,8 +4,11 @@
|
||||
/// <reference path="parser.ts"/>
|
||||
|
||||
module ts {
|
||||
interface EmitTextWriter extends SymbolWriter {
|
||||
interface EmitTextWriter {
|
||||
write(s: string): void;
|
||||
writeLine(): void;
|
||||
increaseIndent(): void;
|
||||
decreaseIndent(): void;
|
||||
getText(): string;
|
||||
rawWrite(s: string): void;
|
||||
writeLiteral(s: string): void;
|
||||
@@ -15,6 +18,9 @@ module ts {
|
||||
getIndent(): number;
|
||||
}
|
||||
|
||||
interface EmitTextWriterWithSymbolWriter extends EmitTextWriter, SymbolWriter{
|
||||
}
|
||||
|
||||
var indentStrings: string[] = ["", " "];
|
||||
export function getIndentString(level: number) {
|
||||
if (indentStrings[level] === undefined) {
|
||||
@@ -28,7 +34,7 @@ module ts {
|
||||
}
|
||||
|
||||
export function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
|
||||
if (!(sourceFile.flags & NodeFlags.DeclarationFile)) {
|
||||
if (!isDeclarationFile(sourceFile)) {
|
||||
if ((isExternalModule(sourceFile) || !compilerOptions.out) && !fileExtensionIs(sourceFile.filename, ".js")) {
|
||||
return true;
|
||||
}
|
||||
@@ -38,7 +44,7 @@ module ts {
|
||||
}
|
||||
|
||||
export function isExternalModuleOrDeclarationFile(sourceFile: SourceFile) {
|
||||
return isExternalModule(sourceFile) || (sourceFile.flags & NodeFlags.DeclarationFile) !== 0;
|
||||
return isExternalModule(sourceFile) || isDeclarationFile(sourceFile);
|
||||
}
|
||||
|
||||
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compilerOnSave feature
|
||||
@@ -103,7 +109,7 @@ module ts {
|
||||
};
|
||||
}
|
||||
|
||||
function createTextWriter(trackSymbol: (symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags)=> void): EmitTextWriter {
|
||||
function createTextWriter(): EmitTextWriter {
|
||||
var output = "";
|
||||
var indent = 0;
|
||||
var lineStart = true;
|
||||
@@ -149,17 +155,8 @@ module ts {
|
||||
}
|
||||
}
|
||||
|
||||
function writeKind(text: string, kind: SymbolDisplayPartKind) {
|
||||
write(text);
|
||||
}
|
||||
function writeSymbol(text: string, symbol: Symbol) {
|
||||
write(text);
|
||||
}
|
||||
return {
|
||||
write: write,
|
||||
trackSymbol: trackSymbol,
|
||||
writeKind: writeKind,
|
||||
writeSymbol: writeSymbol,
|
||||
rawWrite: rawWrite,
|
||||
writeLiteral: writeLiteral,
|
||||
writeLine: writeLine,
|
||||
@@ -170,7 +167,6 @@ module ts {
|
||||
getLine: () => lineCount + 1,
|
||||
getColumn: () => lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1,
|
||||
getText: () => output,
|
||||
clear: () => { }
|
||||
};
|
||||
}
|
||||
|
||||
@@ -318,7 +314,7 @@ module ts {
|
||||
}
|
||||
|
||||
function emitJavaScript(jsFilePath: string, root?: SourceFile) {
|
||||
var writer = createTextWriter(trackSymbol);
|
||||
var writer = createTextWriter();
|
||||
var write = writer.write;
|
||||
var writeLine = writer.writeLine;
|
||||
var increaseIndent = writer.increaseIndent;
|
||||
@@ -374,8 +370,6 @@ module ts {
|
||||
/** Sourcemap data that will get encoded */
|
||||
var sourceMapData: SourceMapData;
|
||||
|
||||
function trackSymbol(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags) { }
|
||||
|
||||
function initializeEmitterWithSourceMaps() {
|
||||
var sourceMapDir: string; // The directory in which sourcemap will be
|
||||
|
||||
@@ -2314,7 +2308,7 @@ module ts {
|
||||
}
|
||||
|
||||
function emitDeclarations(jsFilePath: string, root?: SourceFile) {
|
||||
var writer = createTextWriter(trackSymbol);
|
||||
var writer = createTextWriterWithSymbolWriter();
|
||||
var write = writer.write;
|
||||
var writeLine = writer.writeLine;
|
||||
var increaseIndent = writer.increaseIndent;
|
||||
@@ -2338,11 +2332,24 @@ module ts {
|
||||
typeName?: Identifier
|
||||
}
|
||||
|
||||
function createTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter {
|
||||
var writer = <EmitTextWriterWithSymbolWriter>createTextWriter();
|
||||
writer.trackSymbol = trackSymbol;
|
||||
writer.writeKeyword = writer.write;
|
||||
writer.writeOperator = writer.write;
|
||||
writer.writePunctuation = writer.write;
|
||||
writer.writeSpace = writer.write;
|
||||
writer.writeStringLiteral = writer.writeLiteral;
|
||||
writer.writeParameter = writer.write;
|
||||
writer.writeSymbol = writer.write;
|
||||
return writer;
|
||||
}
|
||||
|
||||
function writeAsychronousImportDeclarations(importDeclarations: ImportDeclaration[]) {
|
||||
var oldWriter = writer;
|
||||
forEach(importDeclarations, aliasToWrite => {
|
||||
var aliasEmitInfo = forEach(aliasDeclarationEmitInfo, declEmitInfo => declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined);
|
||||
writer = createTextWriter(trackSymbol);
|
||||
writer = createTextWriterWithSymbolWriter();
|
||||
for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) {
|
||||
writer.increaseIndent();
|
||||
}
|
||||
@@ -2861,7 +2868,7 @@ module ts {
|
||||
}
|
||||
return {
|
||||
diagnosticMessage: diagnosticMessage,
|
||||
errorNode: node.parameters[0],
|
||||
errorNode: <Node>node.parameters[0],
|
||||
typeName: node.name
|
||||
};
|
||||
}
|
||||
@@ -2882,7 +2889,7 @@ module ts {
|
||||
}
|
||||
return {
|
||||
diagnosticMessage: diagnosticMessage,
|
||||
errorNode: node.name,
|
||||
errorNode: <Node>node.name,
|
||||
typeName: undefined
|
||||
};
|
||||
}
|
||||
@@ -3253,14 +3260,17 @@ module ts {
|
||||
if (compilerOptions.out) {
|
||||
emitFile(compilerOptions.out);
|
||||
}
|
||||
} else {
|
||||
// targetSourceFile is specified (e.g calling emitter from language service)
|
||||
}
|
||||
else {
|
||||
// targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic 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
|
||||
// If shouldEmitToOwnFile returns 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
|
||||
}
|
||||
else if (!isDeclarationFile(targetSourceFile) && compilerOptions.out) {
|
||||
// Otherwise, if --out is specified and targetSourceFile is not a declaration file,
|
||||
// Emit all, non-external-module file, into one single output file
|
||||
emitFile(compilerOptions.out);
|
||||
}
|
||||
}
|
||||
|
||||
+99
-12
@@ -111,6 +111,10 @@ module ts {
|
||||
return file.externalModuleIndicator !== undefined;
|
||||
}
|
||||
|
||||
export function isDeclarationFile(file: SourceFile): boolean {
|
||||
return (file.flags & NodeFlags.DeclarationFile) !== 0;
|
||||
}
|
||||
|
||||
export function isPrologueDirective(node: Node): boolean {
|
||||
return node.kind === SyntaxKind.ExpressionStatement && (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
|
||||
}
|
||||
@@ -221,6 +225,10 @@ module ts {
|
||||
return child((<ArrayTypeNode>node).elementType);
|
||||
case SyntaxKind.TupleType:
|
||||
return children((<TupleTypeNode>node).elementTypes);
|
||||
case SyntaxKind.UnionType:
|
||||
return children((<UnionTypeNode>node).types);
|
||||
case SyntaxKind.ParenType:
|
||||
return child((<ParenTypeNode>node).type);
|
||||
case SyntaxKind.ArrayLiteral:
|
||||
return children((<ArrayLiteral>node).elements);
|
||||
case SyntaxKind.ObjectLiteral:
|
||||
@@ -1072,7 +1080,7 @@ module ts {
|
||||
return isParameter();
|
||||
case ParsingContext.TypeArguments:
|
||||
case ParsingContext.TupleElementTypes:
|
||||
return isType();
|
||||
return token === SyntaxKind.CommaToken || isType();
|
||||
}
|
||||
|
||||
Debug.fail("Non-exhaustive case in 'isListElement'.");
|
||||
@@ -1654,6 +1662,14 @@ module ts {
|
||||
return finishNode(node);
|
||||
}
|
||||
|
||||
function parseParenType(): ParenTypeNode {
|
||||
var node = <ParenTypeNode>createNode(SyntaxKind.ParenType);
|
||||
parseExpected(SyntaxKind.OpenParenToken);
|
||||
node.type = parseType();
|
||||
parseExpected(SyntaxKind.CloseParenToken);
|
||||
return finishNode(node);
|
||||
}
|
||||
|
||||
function parseFunctionType(signatureKind: SyntaxKind): TypeLiteralNode {
|
||||
var node = <TypeLiteralNode>createNode(SyntaxKind.TypeLiteral);
|
||||
var member = <SignatureDeclaration>createNode(signatureKind);
|
||||
@@ -1687,10 +1703,7 @@ module ts {
|
||||
case SyntaxKind.OpenBracketToken:
|
||||
return parseTupleType();
|
||||
case SyntaxKind.OpenParenToken:
|
||||
case SyntaxKind.LessThanToken:
|
||||
return parseFunctionType(SyntaxKind.CallSignature);
|
||||
case SyntaxKind.NewKeyword:
|
||||
return parseFunctionType(SyntaxKind.ConstructSignature);
|
||||
return parseParenType();
|
||||
default:
|
||||
if (isIdentifier()) {
|
||||
return parseTypeReference();
|
||||
@@ -1714,20 +1727,20 @@ module ts {
|
||||
case SyntaxKind.NewKeyword:
|
||||
return true;
|
||||
case SyntaxKind.OpenParenToken:
|
||||
// Only consider an ( as the start of a type if we have () or (id
|
||||
// We don't want to consider things like (1) as a function type.
|
||||
// Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
|
||||
// or something that starts a type. We don't want to consider things like '(1)' a type.
|
||||
return lookAhead(() => {
|
||||
nextToken();
|
||||
return token === SyntaxKind.CloseParenToken || isParameter();
|
||||
return token === SyntaxKind.CloseParenToken || isParameter() || isType();
|
||||
});
|
||||
default:
|
||||
return isIdentifier();
|
||||
}
|
||||
}
|
||||
|
||||
function parseType(): TypeNode {
|
||||
function parsePrimaryType(): TypeNode {
|
||||
var type = parseNonArrayType();
|
||||
while (type && !scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) {
|
||||
while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) {
|
||||
parseExpected(SyntaxKind.CloseBracketToken);
|
||||
var node = <ArrayTypeNode>createNode(SyntaxKind.ArrayType, type.pos);
|
||||
node.elementType = type;
|
||||
@@ -1736,6 +1749,64 @@ module ts {
|
||||
return type;
|
||||
}
|
||||
|
||||
function parseUnionType(): TypeNode {
|
||||
var type = parsePrimaryType();
|
||||
if (token === SyntaxKind.BarToken) {
|
||||
var types = <NodeArray<TypeNode>>[type];
|
||||
types.pos = type.pos;
|
||||
while (parseOptional(SyntaxKind.BarToken)) {
|
||||
types.push(parsePrimaryType());
|
||||
}
|
||||
types.end = getNodeEnd();
|
||||
var node = <UnionTypeNode>createNode(SyntaxKind.UnionType, type.pos);
|
||||
node.types = types;
|
||||
type = finishNode(node);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
function isFunctionType(): boolean {
|
||||
return token === SyntaxKind.LessThanToken || token === SyntaxKind.OpenParenToken && lookAhead(() => {
|
||||
nextToken();
|
||||
if (token === SyntaxKind.CloseParenToken || token === SyntaxKind.DotDotDotToken) {
|
||||
// ( )
|
||||
// ( ...
|
||||
return true;
|
||||
}
|
||||
if (isIdentifier() || isModifier(token)) {
|
||||
nextToken();
|
||||
if (token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken ||
|
||||
token === SyntaxKind.QuestionToken || token === SyntaxKind.EqualsToken ||
|
||||
isIdentifier() || isModifier(token)) {
|
||||
// ( id :
|
||||
// ( id ,
|
||||
// ( id ?
|
||||
// ( id =
|
||||
// ( modifier id
|
||||
return true;
|
||||
}
|
||||
if (token === SyntaxKind.CloseParenToken) {
|
||||
nextToken();
|
||||
if (token === SyntaxKind.EqualsGreaterThanToken) {
|
||||
// ( id ) =>
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
function parseType(): TypeNode {
|
||||
if (isFunctionType()) {
|
||||
return parseFunctionType(SyntaxKind.CallSignature);
|
||||
}
|
||||
if (token === SyntaxKind.NewKeyword) {
|
||||
return parseFunctionType(SyntaxKind.ConstructSignature);
|
||||
}
|
||||
return parseUnionType();
|
||||
}
|
||||
|
||||
function parseTypeAnnotation(): TypeNode {
|
||||
return parseOptional(SyntaxKind.ColonToken) ? parseType() : undefined;
|
||||
}
|
||||
@@ -2322,13 +2393,29 @@ module ts {
|
||||
function parseTypeArguments(): NodeArray<TypeNode> {
|
||||
var typeArgumentListStart = scanner.getTokenPos();
|
||||
var errorCountBeforeTypeParameterList = file.syntacticErrors.length;
|
||||
var result = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
|
||||
// We pass parseSingleTypeArgument instead of parseType as the element parser
|
||||
// because parseSingleTypeArgument knows how to parse a missing type argument.
|
||||
// This is useful for signature help. parseType has the disadvantage that when
|
||||
// it sees a missing type, it changes the LookAheadMode to Error, and the result
|
||||
// is a broken binary expression, which breaks signature help.
|
||||
var result = parseBracketedList(ParsingContext.TypeArguments, parseSingleTypeArgument, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
|
||||
if (!result.length && file.syntacticErrors.length === errorCountBeforeTypeParameterList) {
|
||||
grammarErrorAtPos(typeArgumentListStart, scanner.getStartPos() - typeArgumentListStart, Diagnostics.Type_argument_list_cannot_be_empty);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseSingleTypeArgument(): TypeNode {
|
||||
if (token === SyntaxKind.CommaToken) {
|
||||
var errorStart = scanner.getTokenPos();
|
||||
var errorLength = scanner.getTextPos() - errorStart;
|
||||
grammarErrorAtPos(errorStart, errorLength, Diagnostics.Type_expected);
|
||||
return createNode(SyntaxKind.Missing);
|
||||
}
|
||||
|
||||
return parseType();
|
||||
}
|
||||
|
||||
function parsePrimaryExpression(): Expression {
|
||||
switch (token) {
|
||||
case SyntaxKind.ThisKeyword:
|
||||
@@ -4031,7 +4118,7 @@ module ts {
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (node.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || file.flags & NodeFlags.DeclarationFile)) {
|
||||
else if (node.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
|
||||
// TypeScript 1.0 spec (April 2014): 12.1.6
|
||||
// An AmbientExternalModuleDeclaration declares an external module.
|
||||
// This type of declaration is permitted only in the global module.
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ var sys: System = (function () {
|
||||
return fileStream.ReadText();
|
||||
}
|
||||
catch (e) {
|
||||
throw e.number === -2147024809 ? new Error(ts.Diagnostics.Unsupported_file_encoding.key) : e;
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
fileStream.Close();
|
||||
|
||||
+7
-2
@@ -142,14 +142,19 @@ module ts {
|
||||
// otherwise use toLowerCase as a canonical form.
|
||||
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
|
||||
}
|
||||
|
||||
|
||||
// returned by CScript sys environment
|
||||
var unsupportedFileEncodingErrorCode = -2147024809;
|
||||
|
||||
function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
|
||||
try {
|
||||
var text = sys.readFile(filename, options.charset);
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
onError(e.message);
|
||||
onError(e.number === unsupportedFileEncodingErrorCode ?
|
||||
getDiagnosticText(Diagnostics.Unsupported_file_encoding) :
|
||||
e.message);
|
||||
}
|
||||
text = "";
|
||||
}
|
||||
|
||||
+70
-62
@@ -154,6 +154,8 @@ module ts {
|
||||
TypeLiteral,
|
||||
ArrayType,
|
||||
TupleType,
|
||||
UnionType,
|
||||
ParenType,
|
||||
// Expression
|
||||
ArrayLiteral,
|
||||
ObjectLiteral,
|
||||
@@ -224,7 +226,7 @@ module ts {
|
||||
FirstFutureReservedWord = ImplementsKeyword,
|
||||
LastFutureReservedWord = YieldKeyword,
|
||||
FirstTypeNode = TypeReference,
|
||||
LastTypeNode = TupleType,
|
||||
LastTypeNode = ParenType,
|
||||
FirstPunctuation = OpenBraceToken,
|
||||
LastPunctuation = CaretEqualsToken,
|
||||
FirstToken = EndOfFileToken,
|
||||
@@ -337,6 +339,14 @@ module ts {
|
||||
elementTypes: NodeArray<TypeNode>;
|
||||
}
|
||||
|
||||
export interface UnionTypeNode extends TypeNode {
|
||||
types: NodeArray<TypeNode>;
|
||||
}
|
||||
|
||||
export interface ParenTypeNode extends TypeNode {
|
||||
type: TypeNode;
|
||||
}
|
||||
|
||||
export interface StringLiteralTypeNode extends TypeNode {
|
||||
text: string;
|
||||
}
|
||||
@@ -634,28 +644,25 @@ module ts {
|
||||
getParentOfSymbol(symbol: Symbol): Symbol;
|
||||
getTypeOfSymbol(symbol: Symbol): Type;
|
||||
getPropertiesOfType(type: Type): Symbol[];
|
||||
getPropertyOfType(type: Type, propetyName: string): Symbol;
|
||||
getPropertyOfType(type: Type, propertyName: string): Symbol;
|
||||
getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
|
||||
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
|
||||
getReturnTypeOfSignature(signature: Signature): Type;
|
||||
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
|
||||
getSymbolInfo(node: Node): Symbol;
|
||||
getTypeOfNode(node: Node): Type;
|
||||
getApparentType(type: Type): ApparentType;
|
||||
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
|
||||
writeType(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
|
||||
writeSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
|
||||
getSymbolDisplayBuilder(): SymbolDisplayBuilder;
|
||||
getFullyQualifiedName(symbol: Symbol): string;
|
||||
getAugmentedPropertiesOfApparentType(type: Type): Symbol[];
|
||||
getRootSymbol(symbol: Symbol): Symbol;
|
||||
getAugmentedPropertiesOfType(type: Type): Symbol[];
|
||||
getRootSymbols(symbol: Symbol): Symbol[];
|
||||
getContextualType(node: Node): Type;
|
||||
getResolvedSignature(node: CallExpression, candidatesOutArray?: Signature[]): Signature;
|
||||
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature;
|
||||
writeSignature(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
writeTypeParameter(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
writeTypeParametersOfSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
|
||||
isImplementationOfOverload(node: FunctionDeclaration): boolean;
|
||||
isUndefinedSymbol(symbol: Symbol): boolean;
|
||||
isArgumentsSymbol(symbol: Symbol): boolean;
|
||||
|
||||
// Returns the constant value of this enum member, or 'undefined' if the enum member has a
|
||||
// computed value.
|
||||
@@ -665,8 +672,25 @@ module ts {
|
||||
getAliasedSymbol(symbol: Symbol): Symbol;
|
||||
}
|
||||
|
||||
export interface SymbolDisplayBuilder {
|
||||
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
|
||||
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
|
||||
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
|
||||
}
|
||||
|
||||
export interface SymbolWriter {
|
||||
writeKind(text: string, kind: SymbolDisplayPartKind): void;
|
||||
writeKeyword(text: string): void;
|
||||
writeOperator(text: string): void;
|
||||
writePunctuation(text: string): void;
|
||||
writeSpace(text: string): void;
|
||||
writeStringLiteral(text: string): void;
|
||||
writeParameter(text: string): void;
|
||||
writeSymbol(text: string, symbol: Symbol): void;
|
||||
writeLine(): void;
|
||||
increaseIndent(): void;
|
||||
@@ -687,6 +711,7 @@ module ts {
|
||||
WriteArrowStyleSignature = 0x00000008, // Write arrow style signature
|
||||
WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc)
|
||||
WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature
|
||||
InElementType = 0x00000040, // Writing an array or union element type
|
||||
}
|
||||
|
||||
export enum SymbolFormatFlags {
|
||||
@@ -695,6 +720,9 @@ module ts {
|
||||
// eg. class C<T> { p: T } <-- Show p as C<T>.p here
|
||||
// var a: C<number>;
|
||||
// var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
|
||||
UseOnlyExternalAliasing = 0x00000002, // Use only external alias information to get the symbol name in the given context
|
||||
// eg. module m { export class c { } } import x = m.c;
|
||||
// When this flag is specified m.c will be used to refer to the class instead of alias symbol x
|
||||
}
|
||||
|
||||
export enum SymbolAccessibility {
|
||||
@@ -762,11 +790,11 @@ module ts {
|
||||
Instantiated = 0x00800000, // Instantiated symbol
|
||||
Merged = 0x01000000, // Merged symbol (created during program binding)
|
||||
Transient = 0x02000000, // Transient symbol (created during type check)
|
||||
Prototype = 0x04000000, // Symbol for the prototype property (without source code representation)
|
||||
|
||||
Undefined = 0x08000000, // Symbol for the undefined
|
||||
Prototype = 0x04000000, // Prototype property (no source representation)
|
||||
UnionProperty = 0x08000000, // Property in union type
|
||||
|
||||
Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
|
||||
|
||||
Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter,
|
||||
Namespace = ValueModule | NamespaceModule,
|
||||
Module = ValueModule | NamespaceModule,
|
||||
@@ -824,6 +852,7 @@ module ts {
|
||||
mapper?: TypeMapper; // Type mapper for instantiation alias
|
||||
referenced?: boolean; // True if alias symbol has been referenced as a value
|
||||
exportAssignSymbol?: Symbol; // Symbol exported from external module
|
||||
unionType?: UnionType; // Containing union type for union property
|
||||
}
|
||||
|
||||
export interface TransientSymbol extends Symbol, SymbolLinks { }
|
||||
@@ -846,14 +875,15 @@ module ts {
|
||||
}
|
||||
|
||||
export interface NodeLinks {
|
||||
resolvedType?: Type; // Cached type of type node
|
||||
resolvedSignature?: Signature; // Cached signature of signature node or call expression
|
||||
resolvedSymbol?: Symbol; // Cached name resolution result
|
||||
flags?: NodeCheckFlags; // Set of flags specific to Node
|
||||
enumMemberValue?: number; // Constant value of enum member
|
||||
resolvedType?: Type; // Cached type of type node
|
||||
resolvedSignature?: Signature; // Cached signature of signature node or call expression
|
||||
resolvedSymbol?: Symbol; // Cached name resolution result
|
||||
flags?: NodeCheckFlags; // Set of flags specific to Node
|
||||
enumMemberValue?: number; // Constant value of enum member
|
||||
isIllegalTypeReferenceInConstraint?: boolean; // Is type reference in constraint refers to the type parameter from the same list
|
||||
isVisible?: boolean; // Is this node visible
|
||||
localModuleName?: string; // Local name for module instance
|
||||
isVisible?: boolean; // Is this node visible
|
||||
localModuleName?: string; // Local name for module instance
|
||||
assignmentChecks?: Map<boolean>; // Cache of assignment checks
|
||||
}
|
||||
|
||||
export enum TypeFlags {
|
||||
@@ -871,13 +901,14 @@ module ts {
|
||||
Interface = 0x00000800, // Interface
|
||||
Reference = 0x00001000, // Generic type reference
|
||||
Tuple = 0x00002000, // Tuple
|
||||
Anonymous = 0x00004000, // Anonymous
|
||||
FromSignature = 0x00008000, // Created for signature assignment check
|
||||
Union = 0x00004000, // Union
|
||||
Anonymous = 0x00008000, // Anonymous
|
||||
FromSignature = 0x00010000, // Created for signature assignment check
|
||||
|
||||
Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null,
|
||||
Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null,
|
||||
StringLike = String | StringLiteral,
|
||||
NumberLike = Number | Enum,
|
||||
ObjectType = Class | Interface | Reference | Tuple | Anonymous
|
||||
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
|
||||
}
|
||||
|
||||
// Properties common to all types
|
||||
@@ -900,12 +931,6 @@ module ts {
|
||||
// Object types (TypeFlags.ObjectType)
|
||||
export interface ObjectType extends Type { }
|
||||
|
||||
export interface ApparentType extends Type {
|
||||
// This property is not used. It is just to make the type system think ApparentType
|
||||
// is a strict subtype of Type.
|
||||
_apparentTypeBrand: any;
|
||||
}
|
||||
|
||||
// Class and interface types (TypeFlags.Class and TypeFlags.Interface)
|
||||
export interface InterfaceType extends ObjectType {
|
||||
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
|
||||
@@ -935,8 +960,13 @@ module ts {
|
||||
baseArrayType: TypeReference; // Array<T> where T is best common type of element types
|
||||
}
|
||||
|
||||
// Resolved object type
|
||||
export interface ResolvedObjectType extends ObjectType {
|
||||
export interface UnionType extends Type {
|
||||
types: Type[]; // Constituent types
|
||||
resolvedProperties: SymbolTable; // Cache of resolved properties
|
||||
}
|
||||
|
||||
// Resolved object or union type
|
||||
export interface ResolvedType extends ObjectType, UnionType {
|
||||
members: SymbolTable; // Properties by name
|
||||
properties: Symbol[]; // Properties
|
||||
callSignatures: Signature[]; // Call signatures of type
|
||||
@@ -967,6 +997,7 @@ module ts {
|
||||
hasStringLiterals: boolean; // True if specialized
|
||||
target?: Signature; // Instantiation target
|
||||
mapper?: TypeMapper; // Instantiation mapper
|
||||
unionSignatures?: Signature[]; // Underlying signatures of a union signature
|
||||
erasedSignatureCache?: Signature; // Erased version of signature (deferred)
|
||||
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
|
||||
}
|
||||
@@ -981,9 +1012,11 @@ module ts {
|
||||
}
|
||||
|
||||
export interface InferenceContext {
|
||||
typeParameters: TypeParameter[];
|
||||
inferences: Type[][];
|
||||
inferredTypes: Type[];
|
||||
typeParameters: TypeParameter[]; // Type parameters for which inferences are made
|
||||
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
|
||||
inferenceCount: number; // Incremented for every inference made (whether new or not)
|
||||
inferences: Type[][]; // Inferences made for each type parameter
|
||||
inferredTypes: Type[]; // Inferred type for each type parameter
|
||||
}
|
||||
|
||||
export interface DiagnosticMessage {
|
||||
@@ -1212,32 +1245,7 @@ module ts {
|
||||
tab = 0x09, // \t
|
||||
verticalTab = 0x0B, // \v
|
||||
}
|
||||
|
||||
export enum SymbolDisplayPartKind {
|
||||
aliasName,
|
||||
className,
|
||||
enumName,
|
||||
fieldName,
|
||||
interfaceName,
|
||||
keyword,
|
||||
lineBreak,
|
||||
numericLiteral,
|
||||
stringLiteral,
|
||||
localName,
|
||||
methodName,
|
||||
moduleName,
|
||||
operator,
|
||||
parameterName,
|
||||
propertyName,
|
||||
punctuation,
|
||||
space,
|
||||
text,
|
||||
typeParameterName,
|
||||
enumMemberName,
|
||||
functionName,
|
||||
regularExpressionLiteral,
|
||||
}
|
||||
|
||||
|
||||
export interface CancellationToken {
|
||||
isCancellationRequested(): boolean;
|
||||
}
|
||||
|
||||
@@ -61,9 +61,11 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
var otherFiles: { unitName: string; content: string }[];
|
||||
var harnessCompiler: Harness.Compiler.HarnessCompiler;
|
||||
|
||||
var declToBeCompiled: { unitName: string; content: string }[] = [];
|
||||
var declOtherFiles: { unitName: string; content: string }[] = [];
|
||||
var declResult: Harness.Compiler.CompilerResult;
|
||||
var declFileCompilationResult: {
|
||||
declInputFiles: { unitName: string; content: string }[];
|
||||
declOtherFiles: { unitName: string; content: string }[];
|
||||
declResult: Harness.Compiler.CompilerResult;
|
||||
};
|
||||
|
||||
var createNewInstance = false;
|
||||
|
||||
@@ -147,9 +149,7 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
toBeCompiled = undefined;
|
||||
otherFiles = undefined;
|
||||
harnessCompiler = undefined;
|
||||
declToBeCompiled = undefined;
|
||||
declOtherFiles = undefined;
|
||||
declResult = undefined;
|
||||
declFileCompilationResult = undefined;
|
||||
});
|
||||
|
||||
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
|
||||
@@ -173,61 +173,18 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
|
||||
// Source maps?
|
||||
it('Correct sourcemap content for ' + fileName, () => {
|
||||
if (result.sourceMapRecord) {
|
||||
if (options.sourceMap) {
|
||||
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.ts$/, '.sourcemap.txt'), () => {
|
||||
return result.sourceMapRecord;
|
||||
return result.getSourceMapRecord();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Compile .d.ts files
|
||||
it('Correct compiler generated.d.ts for ' + fileName, () => {
|
||||
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
|
||||
throw new Error('There were no errors and declFiles generated did not match number of js files generated');
|
||||
}
|
||||
|
||||
// if the .d.ts is non-empty, confirm it compiles correctly as well
|
||||
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
|
||||
function addDtsFile(file: { unitName: string; content: string }, dtsFiles: { unitName: string; content: string }[]) {
|
||||
if (Harness.Compiler.isDTS(file.unitName)) {
|
||||
dtsFiles.push(file);
|
||||
}
|
||||
else {
|
||||
var declFile = findResultCodeFile(file.unitName);
|
||||
// Look if there is --out file corresponding to this ts file
|
||||
if (!declFile && options.out) {
|
||||
declFile = findResultCodeFile(options.out);
|
||||
if (!declFile || findUnit(declFile.fileName, declToBeCompiled) ||
|
||||
findUnit(declFile.fileName, declOtherFiles)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (declFile) {
|
||||
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function findResultCodeFile(fileName: string) {
|
||||
return ts.forEach(result.declFilesCode,
|
||||
declFile => declFile.fileName === (fileName.substr(0, fileName.length - ".ts".length) + ".d.ts")
|
||||
? declFile : undefined);
|
||||
}
|
||||
|
||||
function findUnit(fileName: string, units: { unitName: string; content: string }[]) {
|
||||
return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEach(toBeCompiled, file => addDtsFile(file, declToBeCompiled));
|
||||
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
|
||||
harnessCompiler.compileFiles(declToBeCompiled, declOtherFiles, function (compileResult) {
|
||||
declResult = compileResult;
|
||||
}, function (settings) {
|
||||
harnessCompiler.setCompilerSettings(tcSettings);
|
||||
});
|
||||
}
|
||||
declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
|
||||
harnessCompiler.setCompilerSettings(tcSettings);
|
||||
}, options);
|
||||
});
|
||||
|
||||
|
||||
@@ -267,10 +224,10 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
}
|
||||
}
|
||||
|
||||
if (declResult && declResult.errors.length) {
|
||||
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
|
||||
jsCode += '\r\n\r\n//// [DtsFileErrors]\r\n';
|
||||
jsCode += '\r\n\r\n';
|
||||
jsCode += getErrorBaseline(declToBeCompiled, declOtherFiles, declResult);
|
||||
jsCode += getErrorBaseline(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles, declFileCompilationResult.declResult);
|
||||
}
|
||||
|
||||
if (jsCode.length > 0) {
|
||||
|
||||
@@ -146,7 +146,7 @@ module FourSlash {
|
||||
|
||||
function convertGlobalOptionsToCompilationSettings(globalOptions: { [idx: string]: string }): ts.CompilationSettings {
|
||||
var settings: ts.CompilationSettings = {};
|
||||
// Convert all property in globalOptions into ts.CompilationSettings
|
||||
// Convert all property in globalOptions into ts.CompilationSettings
|
||||
for (var prop in globalOptions) {
|
||||
if (globalOptions.hasOwnProperty(prop)) {
|
||||
switch (prop) {
|
||||
@@ -1610,9 +1610,11 @@ module FourSlash {
|
||||
Harness.IO.log(this.getNameOrDottedNameSpan(pos));
|
||||
}
|
||||
|
||||
private verifyClassifications(expected: { classificationType: string; text: string }[], actual: ts.ClassifiedSpan[]) {
|
||||
private verifyClassifications(expected: { classificationType: string; text: string; textSpan?: TextSpan }[], actual: ts.ClassifiedSpan[]) {
|
||||
if (actual.length !== expected.length) {
|
||||
this.raiseError('verifyClassifications 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 +
|
||||
jsonMismatchString());
|
||||
}
|
||||
|
||||
for (var i = 0; i < expected.length; i++) {
|
||||
@@ -1623,17 +1625,38 @@ module FourSlash {
|
||||
if (expectedType !== actualClassification.classificationType) {
|
||||
this.raiseError('verifyClassifications failed - expected classifications type to be ' +
|
||||
expectedType + ', but was ' +
|
||||
actualClassification.classificationType);
|
||||
actualClassification.classificationType +
|
||||
jsonMismatchString());
|
||||
}
|
||||
|
||||
var expectedSpan = expectedClassification.textSpan;
|
||||
var actualSpan = actualClassification.textSpan;
|
||||
|
||||
if (expectedSpan) {
|
||||
var expectedLength = expectedSpan.end - expectedSpan.start;
|
||||
|
||||
if (expectedSpan.start !== actualSpan.start() || expectedLength !== actualSpan.length()) {
|
||||
this.raiseError("verifyClassifications failed - expected span of text to be " +
|
||||
"{start=" + expectedSpan.start + ", length=" + expectedLength + "}, but was " +
|
||||
"{start=" + actualSpan.start() + ", length=" + actualSpan.length() + "}" +
|
||||
jsonMismatchString());
|
||||
}
|
||||
}
|
||||
|
||||
var actualText = this.activeFile.content.substr(actualSpan.start(), actualSpan.length());
|
||||
if (expectedClassification.text !== actualText) {
|
||||
this.raiseError('verifyClassifications failed - expected classificatied text to be ' +
|
||||
this.raiseError('verifyClassifications failed - expected classified text to be ' +
|
||||
expectedClassification.text + ', but was ' +
|
||||
actualText);
|
||||
actualText +
|
||||
jsonMismatchString());
|
||||
}
|
||||
}
|
||||
|
||||
function jsonMismatchString() {
|
||||
return sys.newLine +
|
||||
"expected: '" + sys.newLine + JSON.stringify(expected, (k,v) => v, 2) + "'" + sys.newLine +
|
||||
"actual: '" + sys.newLine + JSON.stringify(actual, (k, v) => v, 2) + "'";
|
||||
}
|
||||
}
|
||||
|
||||
public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) {
|
||||
@@ -1984,7 +2007,8 @@ module FourSlash {
|
||||
var newlinePos = text.indexOf('\n');
|
||||
if (newlinePos === -1) {
|
||||
return text;
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
if (text.charAt(newlinePos - 1) === '\r') {
|
||||
newlinePos--;
|
||||
}
|
||||
|
||||
+86
-13
@@ -139,6 +139,7 @@ module Harness {
|
||||
deleteFile(filename: string): void;
|
||||
listFiles(path: string, filter: RegExp, options?: { recursive?: boolean }): string[];
|
||||
log(text: string): void;
|
||||
getMemoryUsage? (): number;
|
||||
}
|
||||
|
||||
module IOImpl {
|
||||
@@ -275,6 +276,13 @@ module Harness {
|
||||
|
||||
return filesInFolder(path);
|
||||
}
|
||||
|
||||
export var getMemoryUsage: typeof IO.getMemoryUsage = () => {
|
||||
if (global.gc) {
|
||||
global.gc();
|
||||
}
|
||||
return process.memoryUsage().heapUsed;
|
||||
}
|
||||
}
|
||||
|
||||
export module Network {
|
||||
@@ -804,15 +812,81 @@ module Harness {
|
||||
});
|
||||
this.lastErrors = errors;
|
||||
|
||||
var result = new CompilerResult(fileOutputs, errors, []);
|
||||
// Covert the source Map data into the baseline
|
||||
result.updateSourceMapRecord(program, emitResult ? emitResult.sourceMaps : undefined);
|
||||
var result = new CompilerResult(fileOutputs, errors, program, sys.getCurrentDirectory(), emitResult ? emitResult.sourceMaps : undefined);
|
||||
onComplete(result, checker);
|
||||
|
||||
// reset what newline means in case the last test changed it
|
||||
sys.newLine = '\r\n';
|
||||
return options;
|
||||
}
|
||||
|
||||
public compileDeclarationFiles(inputFiles: { unitName: string; content: string; }[],
|
||||
otherFiles: { unitName: string; content: string; }[],
|
||||
result: CompilerResult,
|
||||
settingsCallback?: (settings: ts.CompilerOptions) => void,
|
||||
options?: ts.CompilerOptions) {
|
||||
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
|
||||
throw new Error('There were no errors and declFiles generated did not match number of js files generated');
|
||||
}
|
||||
|
||||
// if the .d.ts is non-empty, confirm it compiles correctly as well
|
||||
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
|
||||
var declInputFiles: { unitName: string; content: string }[] = [];
|
||||
var declOtherFiles: { unitName: string; content: string }[] = [];
|
||||
var declResult: Harness.Compiler.CompilerResult;
|
||||
|
||||
ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
|
||||
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
|
||||
this.compileFiles(declInputFiles, declOtherFiles, function (compileResult) {
|
||||
declResult = compileResult;
|
||||
}, settingsCallback, options);
|
||||
|
||||
return { declInputFiles: declInputFiles, declOtherFiles: declOtherFiles, declResult: declResult };
|
||||
}
|
||||
|
||||
function addDtsFile(file: { unitName: string; content: string }, dtsFiles: { unitName: string; content: string }[]) {
|
||||
if (isDTS(file.unitName)) {
|
||||
dtsFiles.push(file);
|
||||
}
|
||||
else if (isTS(file.unitName)) {
|
||||
var declFile = findResultCodeFile(file.unitName);
|
||||
if (!findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
|
||||
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
|
||||
}
|
||||
}
|
||||
|
||||
function findResultCodeFile(fileName: string) {
|
||||
var dTsFileName = ts.forEach(result.program.getSourceFiles(), sourceFile => {
|
||||
if (sourceFile.filename === fileName) {
|
||||
// Is this file going to be emitted separately
|
||||
var sourceFileName: string;
|
||||
if (ts.isExternalModule(sourceFile) || !options.out) {
|
||||
if (options.outDir) {
|
||||
var sourceFilePath = ts.getNormalizedPathFromPathComponents(ts.getNormalizedPathComponents(sourceFile.filename, result.currentDirectoryForProgram));
|
||||
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
|
||||
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
|
||||
}
|
||||
else {
|
||||
sourceFileName = sourceFile.filename;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Goes to single --out file
|
||||
sourceFileName = options.out;
|
||||
}
|
||||
|
||||
return ts.removeFileExtension(sourceFileName) + ".d.ts";
|
||||
}
|
||||
});
|
||||
|
||||
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
|
||||
}
|
||||
|
||||
function findUnit(fileName: string, units: { unitName: string; content: string; }[]) {
|
||||
return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getMinimalDiagnostic(err: ts.Diagnostic): HarnessDiagnostic {
|
||||
@@ -948,10 +1022,6 @@ module Harness {
|
||||
}
|
||||
*/
|
||||
|
||||
/** Recreate the harness compiler instance to its default settings */
|
||||
export function recreate(options?: { useMinimalDefaultLib: boolean; noImplicitAny: boolean; }) {
|
||||
}
|
||||
|
||||
/** The harness' compiler instance used when tests are actually run. Reseting or changing settings of this compiler instance must be done within a test case (i.e., describe/it) */
|
||||
var harnessCompiler: HarnessCompiler;
|
||||
|
||||
@@ -991,6 +1061,10 @@ module Harness {
|
||||
return str.substr(str.length - end.length) === end;
|
||||
}
|
||||
|
||||
export function isTS(fileName: string) {
|
||||
return stringEndsWith(fileName, '.ts');
|
||||
}
|
||||
|
||||
export function isDTS(fileName: string) {
|
||||
return stringEndsWith(fileName, '.d.ts');
|
||||
}
|
||||
@@ -1009,10 +1083,10 @@ module Harness {
|
||||
public errors: HarnessDiagnostic[] = [];
|
||||
public declFilesCode: GeneratedFile[] = [];
|
||||
public sourceMaps: GeneratedFile[] = [];
|
||||
public sourceMapRecord: string;
|
||||
|
||||
/** @param fileResults an array of strings for the fileName and an ITextWriter with its code */
|
||||
constructor(fileResults: GeneratedFile[], errors: HarnessDiagnostic[], sourceMapRecordLines: string[]) {
|
||||
constructor(fileResults: GeneratedFile[], errors: HarnessDiagnostic[], public program: ts.Program,
|
||||
public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[]) {
|
||||
var lines: string[] = [];
|
||||
|
||||
fileResults.forEach(emittedFile => {
|
||||
@@ -1030,12 +1104,11 @@ module Harness {
|
||||
});
|
||||
|
||||
this.errors = errors;
|
||||
this.sourceMapRecord = sourceMapRecordLines.join('\r\n');
|
||||
}
|
||||
|
||||
public updateSourceMapRecord(program: ts.Program, sourceMapData: ts.SourceMapData[]) {
|
||||
if (sourceMapData) {
|
||||
this.sourceMapRecord = Harness.SourceMapRecoder.getSourceMapRecord(sourceMapData, program, this.files);
|
||||
public getSourceMapRecord() {
|
||||
if (this.sourceMapData) {
|
||||
return Harness.SourceMapRecoder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -419,6 +419,16 @@ class ProjectRunner extends RunnerBase {
|
||||
// })
|
||||
//});
|
||||
}
|
||||
|
||||
after(() => {
|
||||
// Mocha holds onto the closure environment of the describe callback even after the test is done.
|
||||
// Therefore we have to clean out large objects after the test is done.
|
||||
nodeCompilerResult = undefined;
|
||||
amdCompilerResult = undefined;
|
||||
testCase = undefined;
|
||||
testFileText = undefined;
|
||||
testCaseJustName = undefined;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
// ///<reference path='fourslashRunner.ts' />
|
||||
/// <reference path='projectsRunner.ts' />
|
||||
/// <reference path='rwcRunner.ts' />
|
||||
/// <reference path='unittestrunner.ts' />
|
||||
|
||||
function runTests(runners: RunnerBase[]) {
|
||||
if (reverse) {
|
||||
@@ -67,9 +66,6 @@ if (testConfigFile !== '') {
|
||||
case 'fourslash-generated':
|
||||
runners.push(new GeneratedFourslashRunner());
|
||||
break;
|
||||
case 'unittests':
|
||||
runners.push(new UnitTestRunner());
|
||||
break;
|
||||
case 'rwc':
|
||||
runners.push(new RWCRunner());
|
||||
break;
|
||||
@@ -93,9 +89,6 @@ if (runners.length === 0) {
|
||||
// language services
|
||||
runners.push(new FourslashRunner());
|
||||
//runners.push(new GeneratedFourslashRunner());
|
||||
|
||||
// unittests
|
||||
runners.push(new UnitTestRunner());
|
||||
}
|
||||
|
||||
sys.newLine = '\r\n';
|
||||
|
||||
+138
-111
@@ -46,144 +46,171 @@ module RWC {
|
||||
}
|
||||
|
||||
export function runRWCTest(jsonPath: string) {
|
||||
var harnessCompiler = Harness.Compiler.getCompiler();
|
||||
var opts: ts.ParsedCommandLine;
|
||||
describe("Testing a RWC project: " + jsonPath, () => {
|
||||
var inputFiles: { unitName: string; content: string; }[] = [];
|
||||
var otherFiles: { unitName: string; content: string; }[] = [];
|
||||
var compilerResult: Harness.Compiler.CompilerResult;
|
||||
var compilerOptions: ts.CompilerOptions;
|
||||
var baselineOpts: Harness.Baseline.BaselineOptions = { Subfolder: 'rwc' };
|
||||
var baseName = /(.*)\/(.*).json/.exec(Harness.Path.switchToForwardSlashes(jsonPath))[2];
|
||||
// Compile .d.ts files
|
||||
var declFileCompilationResult: {
|
||||
declInputFiles: { unitName: string; content: string }[];
|
||||
declOtherFiles: { unitName: string; content: string }[];
|
||||
declResult: Harness.Compiler.CompilerResult;
|
||||
};
|
||||
|
||||
var ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
|
||||
var errors = '';
|
||||
|
||||
it('has parsable options', () => {
|
||||
runWithIOLog(ioLog, () => {
|
||||
opts = ts.parseCommandLine(ioLog.arguments);
|
||||
assert.equal(opts.errors.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
var inputFiles: { unitName: string; content: string; }[] = [];
|
||||
var otherFiles: { unitName: string; content: string; }[] = [];
|
||||
var compilerResult: Harness.Compiler.CompilerResult;
|
||||
it('can compile', () => {
|
||||
runWithIOLog(ioLog, () => {
|
||||
harnessCompiler.reset();
|
||||
|
||||
// Load the files
|
||||
ts.forEach(opts.filenames, fileName => {
|
||||
inputFiles.push(getHarnessCompilerInputUnit(fileName));
|
||||
});
|
||||
|
||||
if (!opts.options.noLib) {
|
||||
// Find the lib.d.ts file in the input file and add it to the input files list
|
||||
var libFile = ts.forEach(ioLog.filesRead, fileRead=> Harness.isLibraryFile(fileRead.path) ? fileRead.path : undefined);
|
||||
if (libFile) {
|
||||
inputFiles.push(getHarnessCompilerInputUnit(libFile));
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEach(ioLog.filesRead, fileRead => {
|
||||
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(fileRead.path));
|
||||
var inInputList = ts.forEach(inputFiles, inputFile=> inputFile.unitName === resolvedPath);
|
||||
if (!inInputList) {
|
||||
// Add the file to other files
|
||||
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
|
||||
}
|
||||
});
|
||||
|
||||
// do not use lib since we already read it in above
|
||||
opts.options.noLib = true;
|
||||
|
||||
// Emit the results
|
||||
harnessCompiler.compileFiles(inputFiles, otherFiles, compileResult => {
|
||||
compilerResult = compileResult;
|
||||
}, /*settingsCallback*/ undefined, opts.options);
|
||||
after(() => {
|
||||
// Mocha holds onto the closure environment of the describe callback even after the test is done.
|
||||
// Therefore we have to clean out large objects after the test is done.
|
||||
inputFiles = undefined;
|
||||
otherFiles = undefined;
|
||||
compilerResult = undefined;
|
||||
compilerOptions = undefined;
|
||||
baselineOpts = undefined;
|
||||
baseName = undefined;
|
||||
declFileCompilationResult = undefined;
|
||||
});
|
||||
|
||||
function getHarnessCompilerInputUnit(fileName: string) {
|
||||
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(fileName));
|
||||
try {
|
||||
var content = sys.readFile(resolvedPath);
|
||||
it('can compile', () => {
|
||||
var harnessCompiler = Harness.Compiler.getCompiler();
|
||||
var opts: ts.ParsedCommandLine;
|
||||
|
||||
var ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
|
||||
runWithIOLog(ioLog, () => {
|
||||
opts = ts.parseCommandLine(ioLog.arguments);
|
||||
assert.equal(opts.errors.length, 0);
|
||||
});
|
||||
|
||||
runWithIOLog(ioLog, () => {
|
||||
harnessCompiler.reset();
|
||||
|
||||
// Load the files
|
||||
ts.forEach(opts.filenames, fileName => {
|
||||
inputFiles.push(getHarnessCompilerInputUnit(fileName));
|
||||
});
|
||||
|
||||
if (!opts.options.noLib) {
|
||||
// Find the lib.d.ts file in the input file and add it to the input files list
|
||||
var libFile = ts.forEach(ioLog.filesRead, fileRead=> Harness.isLibraryFile(fileRead.path) ? fileRead.path : undefined);
|
||||
if (libFile) {
|
||||
inputFiles.push(getHarnessCompilerInputUnit(libFile));
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEach(ioLog.filesRead, fileRead => {
|
||||
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(fileRead.path));
|
||||
var inInputList = ts.forEach(inputFiles, inputFile=> inputFile.unitName === resolvedPath);
|
||||
if (!inInputList) {
|
||||
// Add the file to other files
|
||||
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
|
||||
}
|
||||
});
|
||||
|
||||
// do not use lib since we already read it in above
|
||||
opts.options.noLib = true;
|
||||
|
||||
// Emit the results
|
||||
compilerOptions = harnessCompiler.compileFiles(inputFiles, otherFiles, compileResult => {
|
||||
compilerResult = compileResult;
|
||||
}, /*settingsCallback*/ undefined, opts.options);
|
||||
});
|
||||
|
||||
function getHarnessCompilerInputUnit(fileName: string) {
|
||||
var resolvedPath = Harness.Path.switchToForwardSlashes(sys.resolvePath(fileName));
|
||||
try {
|
||||
var content = sys.readFile(resolvedPath);
|
||||
}
|
||||
catch (e) {
|
||||
// Leave content undefined.
|
||||
}
|
||||
return { unitName: resolvedPath, content: content };
|
||||
}
|
||||
catch (e) {
|
||||
// Leave content undefined.
|
||||
}
|
||||
return { unitName: resolvedPath, content: content };
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Baselines
|
||||
var baselineOpts: Harness.Baseline.BaselineOptions = { Subfolder: 'rwc' };
|
||||
var baseName = /(.*)\/(.*).json/.exec(Harness.Path.switchToForwardSlashes(jsonPath))[2];
|
||||
// Baselines
|
||||
it('Correct compiler generated.d.ts', () => {
|
||||
declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult, /*settingscallback*/ undefined, compilerOptions);
|
||||
});
|
||||
|
||||
it('has the expected emitted code', () => {
|
||||
Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
|
||||
return collateOutputs(compilerResult.files, s => SyntacticCleaner.clean(s));
|
||||
}, false, baselineOpts);
|
||||
});
|
||||
|
||||
it('has the expected declaration file content', () => {
|
||||
Harness.Baseline.runBaseline('has the expected declaration file content', baseName + '.d.ts', () => {
|
||||
if (compilerResult.errors.length || !compilerResult.declFilesCode.length) {
|
||||
return null;
|
||||
}
|
||||
return collateOutputs(compilerResult.declFilesCode);
|
||||
}, false, baselineOpts);
|
||||
});
|
||||
|
||||
it('has the expected source maps', () => {
|
||||
Harness.Baseline.runBaseline('has the expected source maps', baseName + '.map', () => {
|
||||
if (!compilerResult.sourceMaps.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collateOutputs(compilerResult.sourceMaps);
|
||||
}, false, baselineOpts);
|
||||
});
|
||||
|
||||
it('has correct source map record', () => {
|
||||
if (compilerResult.sourceMapRecord) {
|
||||
Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
|
||||
return compilerResult.sourceMapRecord;
|
||||
it('has the expected emitted code', () => {
|
||||
Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
|
||||
return collateOutputs(compilerResult.files, s => SyntacticCleaner.clean(s));
|
||||
}, false, baselineOpts);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('has the expected errors', () => {
|
||||
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
|
||||
if (compilerResult.errors.length === 0) {
|
||||
return null;
|
||||
it('has the expected declaration file content', () => {
|
||||
Harness.Baseline.runBaseline('has the expected declaration file content', baseName + '.d.ts', () => {
|
||||
if (compilerResult.errors.length || !compilerResult.declFilesCode.length) {
|
||||
return null;
|
||||
}
|
||||
return collateOutputs(compilerResult.declFilesCode);
|
||||
}, false, baselineOpts);
|
||||
});
|
||||
|
||||
it('has the expected source maps', () => {
|
||||
Harness.Baseline.runBaseline('has the expected source maps', baseName + '.map', () => {
|
||||
if (!compilerResult.sourceMaps.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collateOutputs(compilerResult.sourceMaps);
|
||||
}, false, baselineOpts);
|
||||
});
|
||||
|
||||
//it('has correct source map record', () => {
|
||||
// if (compilerOptions.sourceMap) {
|
||||
// Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
|
||||
// return compilerResult.getSourceMapRecord();
|
||||
// }, false, baselineOpts);
|
||||
// }
|
||||
//});
|
||||
|
||||
it('has the expected errors', () => {
|
||||
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
|
||||
if (compilerResult.errors.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Harness.Compiler.getErrorBaseline(inputFiles.concat(otherFiles), compilerResult.errors);
|
||||
}, false, baselineOpts);
|
||||
});
|
||||
|
||||
it('has no errors in generated declaration files', () => {
|
||||
if (compilerOptions.declaration && !compilerResult.errors.length) {
|
||||
Harness.Baseline.runBaseline('has no errors in generated declaration files', baseName + '.dts.errors.txt', () => {
|
||||
if (declFileCompilationResult.declResult.errors.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Harness.Compiler.minimalDiagnosticsToString(declFileCompilationResult.declResult.errors) +
|
||||
sys.newLine + sys.newLine +
|
||||
Harness.Compiler.getErrorBaseline(declFileCompilationResult.declInputFiles.concat(declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.errors);
|
||||
}, false, baselineOpts);
|
||||
}
|
||||
});
|
||||
|
||||
return Harness.Compiler.getErrorBaseline(inputFiles.concat(otherFiles), compilerResult.errors);
|
||||
}, false, baselineOpts);
|
||||
// TODO: Type baselines (need to refactor out from compilerRunner)
|
||||
});
|
||||
|
||||
// TODO: Type baselines (need to refactor out from compilerRunner)
|
||||
}
|
||||
}
|
||||
|
||||
class RWCRunner extends RunnerBase {
|
||||
private runnerPath = "tests/runners/rwc";
|
||||
private sourcePath = "tests/cases/rwc/";
|
||||
|
||||
private harnessCompiler: Harness.Compiler.HarnessCompiler;
|
||||
private static sourcePath = "tests/cases/rwc/";
|
||||
|
||||
/** Setup the runner's tests so that they are ready to be executed by the harness
|
||||
* The first test should be a describe/it block that sets up the harness's compiler instance appropriately
|
||||
*/
|
||||
public initializeTests(): void {
|
||||
// Recreate the compiler with the default lib
|
||||
Harness.Compiler.recreate({ useMinimalDefaultLib: false, noImplicitAny: false });
|
||||
this.harnessCompiler = Harness.Compiler.getCompiler();
|
||||
|
||||
// Read in and evaluate the test list
|
||||
var testList = Harness.IO.listFiles(this.sourcePath, /.+\.json$/);
|
||||
var testList = Harness.IO.listFiles(RWCRunner.sourcePath, /.+\.json$/);
|
||||
for (var i = 0; i < testList.length; i++) {
|
||||
this.runTest(testList[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private runTest(jsonFilename: string) {
|
||||
describe("Testing a RWC project: " + jsonFilename, () => {
|
||||
RWC.runRWCTest(jsonFilename);
|
||||
});
|
||||
RWC.runRWCTest(jsonFilename);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
///<reference path="harness.ts" />
|
||||
///<reference path="runnerbase.ts" />
|
||||
|
||||
class UnitTestRunner extends RunnerBase {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public initializeTests() {
|
||||
this.tests = this.enumerateFiles('tests/cases/unittests/services', /\.ts/i);
|
||||
|
||||
var outfile = new Harness.Compiler.WriterAggregator()
|
||||
var outerr = new Harness.Compiler.WriterAggregator();
|
||||
// note this is running immediately to generate tests to be run later inside describe/it
|
||||
// need a fresh instance so that the previous runner's last test is not hanging around
|
||||
var harnessCompiler = Harness.Compiler.getCompiler({ useExistingInstance: false });
|
||||
|
||||
var toBeAdded = this.tests.map(test => {
|
||||
return { unitName: test, content: Harness.IO.readFile(test) }
|
||||
});
|
||||
harnessCompiler.addInputFiles(toBeAdded);
|
||||
harnessCompiler.setCompilerOptions({ noResolve: true });
|
||||
|
||||
var stdout = new Harness.Compiler.EmitterIOHost();
|
||||
var emitDiagnostics = harnessCompiler.emitAll(stdout);
|
||||
var results = stdout.toArray();
|
||||
var lines: string[] = [];
|
||||
results.forEach(v => lines = lines.concat(v.file.lines));
|
||||
var code = lines.join("\n")
|
||||
|
||||
var nodeContext: any = undefined;
|
||||
if (Utils.getExecutionEnvironment() === Utils.ExecutionEnvironment.Node) {
|
||||
nodeContext = {
|
||||
require: require,
|
||||
process: process,
|
||||
describe: describe,
|
||||
it: it,
|
||||
assert: assert,
|
||||
beforeEach: beforeEach,
|
||||
afterEach: afterEach,
|
||||
before: before,
|
||||
after: after,
|
||||
Harness: Harness,
|
||||
IO: Harness.IO,
|
||||
ts: ts,
|
||||
TypeScript: TypeScript
|
||||
// FourSlash: FourSlash
|
||||
};
|
||||
}
|
||||
|
||||
describe("Setup compiler for compiler unittests", () => {
|
||||
// ensures a clean compiler instance when tests are eventually executed following this describe block
|
||||
harnessCompiler = Harness.Compiler.getCompiler({
|
||||
useExistingInstance: false,
|
||||
optionsForFreshInstance: { useMinimalDefaultLib: true, noImplicitAny: false }
|
||||
});
|
||||
});
|
||||
|
||||
// this generated code is a series of top level describe/it blocks that will run in between the setup and cleanup blocks in this file
|
||||
Utils.evalFile(code, "generated_test_code.js", nodeContext);
|
||||
|
||||
describe("Cleanup after unittests", () => {
|
||||
var harnessCompiler = Harness.Compiler.getCompiler({
|
||||
useExistingInstance: false,
|
||||
optionsForFreshInstance: { useMinimalDefaultLib: true, noImplicitAny: false }
|
||||
});
|
||||
});
|
||||
|
||||
// note this runs immediately (ie before this same code in the describe block above)
|
||||
// to make sure the next runner doesn't include the previous one's stuff
|
||||
harnessCompiler = Harness.Compiler.getCompiler({ useExistingInstance: false });
|
||||
}
|
||||
}
|
||||
@@ -476,8 +476,6 @@ module TypeScript {
|
||||
//}
|
||||
}
|
||||
|
||||
var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl);
|
||||
var funcSignature = funcPullDecl.getSignatureSymbol(this.semanticInfoChain);
|
||||
this.emitDeclarationComments(funcDecl);
|
||||
|
||||
this.emitIndent();
|
||||
@@ -603,11 +601,6 @@ module TypeScript {
|
||||
private emitConstructSignature(funcDecl: ConstructSignatureSyntax) {
|
||||
var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl);
|
||||
|
||||
var start = new Date().getTime();
|
||||
var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl);
|
||||
|
||||
TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start;
|
||||
|
||||
this.emitDeclarationComments(funcDecl);
|
||||
|
||||
this.emitIndent();
|
||||
@@ -633,11 +626,6 @@ module TypeScript {
|
||||
private emitMethodSignature(funcDecl: MethodSignatureSyntax) {
|
||||
var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl);
|
||||
|
||||
var start = new Date().getTime();
|
||||
var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl);
|
||||
|
||||
TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start;
|
||||
|
||||
this.emitDeclarationComments(funcDecl);
|
||||
|
||||
this.emitIndent();
|
||||
@@ -817,7 +805,6 @@ module TypeScript {
|
||||
var parameter = funcDecl.callSignature.parameterList.parameters[i];
|
||||
var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter);
|
||||
if (hasFlag(parameterDecl.flags, PullElementFlags.PropertyParameter)) {
|
||||
var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl);
|
||||
this.emitDeclarationComments(parameter);
|
||||
this.declFile.Write(this.getIndentString());
|
||||
this.emitClassElementModifiers(parameter.modifiers);
|
||||
@@ -838,7 +825,6 @@ module TypeScript {
|
||||
|
||||
var className = classDecl.identifier.text();
|
||||
this.emitDeclarationComments(classDecl);
|
||||
var classPullDecl = this.semanticInfoChain.getDeclForAST(classDecl);
|
||||
this.emitDeclFlags(classDecl, "class");
|
||||
this.declFile.Write(className);
|
||||
|
||||
@@ -934,7 +920,6 @@ module TypeScript {
|
||||
|
||||
var interfaceName = interfaceDecl.identifier.text();
|
||||
this.emitDeclarationComments(interfaceDecl);
|
||||
var interfacePullDecl = this.semanticInfoChain.getDeclForAST(interfaceDecl);
|
||||
this.emitDeclFlags(interfaceDecl, "interface");
|
||||
this.declFile.Write(interfaceName);
|
||||
|
||||
@@ -980,7 +965,6 @@ module TypeScript {
|
||||
}
|
||||
|
||||
this.emitDeclarationComments(moduleDecl);
|
||||
var modulePullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl);
|
||||
this.emitDeclFlags(moduleDecl, "enum");
|
||||
this.declFile.WriteLine(moduleDecl.identifier.text() + " {");
|
||||
|
||||
|
||||
@@ -512,7 +512,7 @@ module TypeScript {
|
||||
for (var i = 0, n = fileNames.length; i < n; i++) {
|
||||
var fileName = fileNames[i];
|
||||
|
||||
var document = this.getDocument(fileNames[i]);
|
||||
var document = this.getDocument(fileName);
|
||||
|
||||
sharedEmitter = this._emitDocumentDeclarations(document, emitOptions,
|
||||
file => emitOutput.outputFiles.push(file), sharedEmitter);
|
||||
@@ -578,7 +578,6 @@ module TypeScript {
|
||||
var sourceUnit = document.sourceUnit();
|
||||
Debug.assert(this._shouldEmit(document));
|
||||
|
||||
var typeScriptFileName = document.fileName;
|
||||
if (!emitter) {
|
||||
var javaScriptFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToJSFileName);
|
||||
var outFile = new TextWriter(javaScriptFileName, this.writeByteOrderMarkForDocument(document), OutputFileType.JavaScript);
|
||||
@@ -799,8 +798,6 @@ module TypeScript {
|
||||
}
|
||||
|
||||
private extractResolutionContextFromAST(resolver: PullTypeResolver, ast: ISyntaxElement, document: Document, propagateContextualTypes: boolean): { ast: ISyntaxElement; enclosingDecl: PullDecl; resolutionContext: PullTypeResolutionContext; inContextuallyTypedAssignment: boolean; inWithBlock: boolean; } {
|
||||
var scriptName = document.fileName;
|
||||
|
||||
var enclosingDecl: PullDecl = null;
|
||||
var enclosingDeclAST: ISyntaxElement = null;
|
||||
var inContextuallyTypedAssignment = false;
|
||||
@@ -981,7 +978,6 @@ module TypeScript {
|
||||
|
||||
case SyntaxKind.ReturnStatement:
|
||||
if (propagateContextualTypes) {
|
||||
var returnStatement = <ReturnStatementSyntax>current;
|
||||
var contextualType: PullTypeSymbol = null;
|
||||
|
||||
if (enclosingDecl && (enclosingDecl.kind & PullElementKind.SomeFunction)) {
|
||||
|
||||
@@ -7,12 +7,6 @@ module TypeScript {
|
||||
}
|
||||
|
||||
export function integerMultiplyLow32Bits(n1: number, n2: number): number {
|
||||
var n1Low16 = n1 & 0x0000ffff;
|
||||
var n1High16 = n1 >>> 16;
|
||||
|
||||
var n2Low16 = n2 & 0x0000ffff;
|
||||
var n2High16 = n2 >>> 16;
|
||||
|
||||
var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0;
|
||||
return resultLow32;
|
||||
}
|
||||
|
||||
+299
-202
@@ -580,7 +580,7 @@ module ts {
|
||||
return this.checker.getPropertyOfType(this, propertyName);
|
||||
}
|
||||
getApparentProperties(): Symbol[] {
|
||||
return this.checker.getAugmentedPropertiesOfApparentType(this);
|
||||
return this.checker.getAugmentedPropertiesOfType(this);
|
||||
}
|
||||
getCallSignatures(): Signature[] {
|
||||
return this.checker.getSignaturesOfType(this, SignatureKind.Call);
|
||||
@@ -999,12 +999,37 @@ module ts {
|
||||
containerKind: string;
|
||||
containerName: string;
|
||||
}
|
||||
|
||||
|
||||
export enum SymbolDisplayPartKind {
|
||||
aliasName,
|
||||
className,
|
||||
enumName,
|
||||
fieldName,
|
||||
interfaceName,
|
||||
keyword,
|
||||
lineBreak,
|
||||
numericLiteral,
|
||||
stringLiteral,
|
||||
localName,
|
||||
methodName,
|
||||
moduleName,
|
||||
operator,
|
||||
parameterName,
|
||||
propertyName,
|
||||
punctuation,
|
||||
space,
|
||||
text,
|
||||
typeParameterName,
|
||||
enumMemberName,
|
||||
functionName,
|
||||
regularExpressionLiteral,
|
||||
}
|
||||
|
||||
export interface SymbolDisplayPart {
|
||||
text: string;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
|
||||
export interface QuickInfo {
|
||||
kind: string;
|
||||
kindModifiers: string;
|
||||
@@ -1310,7 +1335,12 @@ module ts {
|
||||
resetWriter();
|
||||
return {
|
||||
displayParts: () => displayParts,
|
||||
writeKind: writeKind,
|
||||
writeKeyword: text => writeKind(text, SymbolDisplayPartKind.keyword),
|
||||
writeOperator: text => writeKind(text, SymbolDisplayPartKind.operator),
|
||||
writePunctuation: text => writeKind(text, SymbolDisplayPartKind.punctuation),
|
||||
writeSpace: text => writeKind(text, SymbolDisplayPartKind.space),
|
||||
writeStringLiteral: text => writeKind(text, SymbolDisplayPartKind.stringLiteral),
|
||||
writeParameter: text => writeKind(text, SymbolDisplayPartKind.parameterName),
|
||||
writeSymbol: writeSymbol,
|
||||
writeLine: writeLine,
|
||||
increaseIndent: () => { indent++; },
|
||||
@@ -1434,7 +1464,7 @@ module ts {
|
||||
}
|
||||
}
|
||||
|
||||
function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] {
|
||||
export function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] {
|
||||
writeDisplayParts(displayPartWriter);
|
||||
var result = displayPartWriter.displayParts();
|
||||
displayPartWriter.clear();
|
||||
@@ -1443,19 +1473,19 @@ module ts {
|
||||
|
||||
export function typeToDisplayParts(typechecker: TypeChecker, type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[] {
|
||||
return mapToDisplayParts(writer => {
|
||||
typechecker.writeType(type, writer, enclosingDeclaration, flags);
|
||||
typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
|
||||
});
|
||||
}
|
||||
|
||||
export function symbolToDisplayParts(typeChecker: TypeChecker, symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): SymbolDisplayPart[] {
|
||||
return mapToDisplayParts(writer => {
|
||||
typeChecker.writeSymbol(symbol, writer, enclosingDeclaration, meaning, flags);
|
||||
typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags);
|
||||
});
|
||||
}
|
||||
|
||||
function signatureToDisplayParts(typechecker: TypeChecker, signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[]{
|
||||
return mapToDisplayParts(writer => {
|
||||
typechecker.writeSignature(signature, writer, enclosingDeclaration, flags);
|
||||
typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2287,7 +2317,7 @@ module ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function createCompletionEntry(symbol: Symbol): CompletionEntry {
|
||||
function createCompletionEntry(symbol: Symbol, typeChecker: TypeChecker): CompletionEntry {
|
||||
// Try to get a valid display name for this symbol, if we could not find one, then ignore it.
|
||||
// We would like to only show things that can be added after a dot, so for instance numeric properties can
|
||||
// not be accessed with a dot (a.1 <- invalid)
|
||||
@@ -2302,7 +2332,7 @@ module ts {
|
||||
// We COULD also just do what 'getSymbolModifiers' does, which is to use the first declaration.
|
||||
return {
|
||||
name: displayName,
|
||||
kind: getSymbolKind(symbol, SemanticMeaning.All),
|
||||
kind: getSymbolKind(symbol, typeChecker),
|
||||
kindModifiers: getSymbolModifiers(symbol)
|
||||
};
|
||||
}
|
||||
@@ -2310,7 +2340,7 @@ module ts {
|
||||
function getCompletionsAtPosition(filename: string, position: number, isMemberCompletion: boolean) {
|
||||
function getCompletionEntriesFromSymbols(symbols: Symbol[], session: CompletionSession): void {
|
||||
forEach(symbols, symbol => {
|
||||
var entry = createCompletionEntry(symbol);
|
||||
var entry = createCompletionEntry(symbol, session.typeChecker);
|
||||
if (entry && !lookUp(session.symbols, entry.name)) {
|
||||
session.entries.push(entry);
|
||||
session.symbols[entry.name] = symbol;
|
||||
@@ -2567,10 +2597,9 @@ module ts {
|
||||
}
|
||||
|
||||
var type = typeInfoResolver.getTypeOfNode(node);
|
||||
var apparentType = type && typeInfoResolver.getApparentType(type);
|
||||
if (apparentType) {
|
||||
if (type) {
|
||||
// Filter private properties
|
||||
forEach(apparentType.getApparentProperties(), symbol => {
|
||||
forEach(type.getApparentProperties(), symbol => {
|
||||
if (typeInfoResolver.isValidPropertyAccess(<PropertyAccess>(node.parent), symbol.name)) {
|
||||
symbols.push(symbol);
|
||||
}
|
||||
@@ -2638,7 +2667,7 @@ module ts {
|
||||
if (symbol) {
|
||||
var type = session.typeChecker.getTypeOfSymbol(symbol);
|
||||
Debug.assert(type, "Could not find type for symbol");
|
||||
var completionEntry = createCompletionEntry(symbol);
|
||||
var completionEntry = createCompletionEntry(symbol, session.typeChecker);
|
||||
// TODO(drosen): Right now we just permit *all* semantic meanings when calling 'getSymbolKind'
|
||||
// which is permissible given that it is backwards compatible; but really we should consider
|
||||
// passing the meaning for the node so that we don't report that a suggestion for a value is an interface.
|
||||
@@ -2687,20 +2716,16 @@ module ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getSymbolKind(symbol: Symbol, meaningAtLocation: SemanticMeaning): string {
|
||||
var flags = typeInfoResolver.getRootSymbol(symbol).getFlags();
|
||||
// TODO(drosen): use contextual SemanticMeaning.
|
||||
function getSymbolKind(symbol: Symbol, typeResolver: TypeChecker): string {
|
||||
var flags = symbol.getFlags();
|
||||
|
||||
if (flags & SymbolFlags.Class) return ScriptElementKind.classElement;
|
||||
if (flags & SymbolFlags.Enum) return ScriptElementKind.enumElement;
|
||||
|
||||
// The following should only apply if encountered at a type position,
|
||||
// and need to have precedence over other meanings if this is the case.
|
||||
if (meaningAtLocation & SemanticMeaning.Type) {
|
||||
if (flags & SymbolFlags.Interface) return ScriptElementKind.interfaceElement;
|
||||
if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement;
|
||||
}
|
||||
|
||||
var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags);
|
||||
if (flags & SymbolFlags.Interface) return ScriptElementKind.interfaceElement;
|
||||
if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement;
|
||||
|
||||
var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, typeResolver);
|
||||
if (result === ScriptElementKind.unknown) {
|
||||
if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement;
|
||||
if (flags & SymbolFlags.EnumMember) return ScriptElementKind.variableElement;
|
||||
@@ -2710,23 +2735,40 @@ module ts {
|
||||
return result;
|
||||
}
|
||||
|
||||
function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol: Symbol, flags: SymbolFlags) {
|
||||
function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol: Symbol, flags: SymbolFlags, typeResolver: TypeChecker) {
|
||||
if (typeResolver.isUndefinedSymbol(symbol)) {
|
||||
return ScriptElementKind.variableElement;
|
||||
}
|
||||
if (typeResolver.isArgumentsSymbol(symbol)) {
|
||||
return ScriptElementKind.localVariableElement;
|
||||
}
|
||||
if (flags & SymbolFlags.Variable) {
|
||||
if (isFirstDeclarationOfSymbolParameter(symbol)) {
|
||||
return ScriptElementKind.parameterElement;
|
||||
}
|
||||
return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement;
|
||||
}
|
||||
if (flags & SymbolFlags.Undefined) {
|
||||
return ScriptElementKind.variableElement;
|
||||
}
|
||||
if (flags & SymbolFlags.Function) return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localFunctionElement : ScriptElementKind.functionElement;
|
||||
if (flags & SymbolFlags.GetAccessor) return ScriptElementKind.memberGetAccessorElement;
|
||||
if (flags & SymbolFlags.SetAccessor) return ScriptElementKind.memberSetAccessorElement;
|
||||
if (flags & SymbolFlags.Method) return ScriptElementKind.memberFunctionElement;
|
||||
if (flags & SymbolFlags.Property) return ScriptElementKind.memberVariableElement;
|
||||
if (flags & SymbolFlags.Constructor) return ScriptElementKind.constructorImplementationElement;
|
||||
|
||||
if (flags & SymbolFlags.Property) {
|
||||
if (flags & SymbolFlags.UnionProperty) {
|
||||
return forEach(typeInfoResolver.getRootSymbols(symbol), rootSymbol => {
|
||||
var rootSymbolFlags = rootSymbol.getFlags();
|
||||
if (rootSymbolFlags & SymbolFlags.Property) {
|
||||
return ScriptElementKind.memberVariableElement;
|
||||
}
|
||||
if (rootSymbolFlags & SymbolFlags.GetAccessor) return ScriptElementKind.memberVariableElement;
|
||||
if (rootSymbolFlags & SymbolFlags.SetAccessor) return ScriptElementKind.memberVariableElement;
|
||||
Debug.assert(rootSymbolFlags & SymbolFlags.Method);
|
||||
}) || ScriptElementKind.memberFunctionElement;
|
||||
}
|
||||
return ScriptElementKind.memberVariableElement;
|
||||
}
|
||||
|
||||
return ScriptElementKind.unknown;
|
||||
}
|
||||
|
||||
@@ -2778,19 +2820,15 @@ module ts {
|
||||
semanticMeaning = getMeaningFromLocation(location)) {
|
||||
var displayParts: SymbolDisplayPart[] = [];
|
||||
var documentation: SymbolDisplayPart[];
|
||||
var symbolFlags = typeResolver.getRootSymbol(symbol).flags;
|
||||
var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags);
|
||||
var symbolFlags = symbol.flags;
|
||||
var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, typeResolver);
|
||||
var hasAddedSymbolInfo: boolean;
|
||||
// Class at constructor site need to be shown as constructor apart from property,method, vars
|
||||
if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Signature || symbolFlags & SymbolFlags.Class) {
|
||||
if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Import) {
|
||||
// If it is accessor they are allowed only if location is at name of the accessor
|
||||
if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) {
|
||||
symbolKind = ScriptElementKind.memberVariableElement;
|
||||
}
|
||||
else if (symbol.name === "undefined") {
|
||||
// undefined is symbol and not property
|
||||
symbolKind = ScriptElementKind.variableElement;
|
||||
}
|
||||
|
||||
var type = typeResolver.getTypeOfSymbol(symbol);
|
||||
if (type) {
|
||||
@@ -2833,6 +2871,18 @@ module ts {
|
||||
symbolKind = ScriptElementKind.constructorImplementationElement;
|
||||
addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
|
||||
}
|
||||
else if (symbolFlags & SymbolFlags.Import) {
|
||||
symbolKind = ScriptElementKind.alias;
|
||||
displayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
|
||||
displayParts.push(textPart(symbolKind));
|
||||
displayParts.push(punctuationPart(SyntaxKind.CloseParenToken));
|
||||
displayParts.push(spacePart());
|
||||
if (useConstructSignatures) {
|
||||
displayParts.push(keywordPart(SyntaxKind.NewKeyword));
|
||||
displayParts.push(spacePart());
|
||||
}
|
||||
addFullSymbolName(symbol);
|
||||
}
|
||||
else {
|
||||
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
|
||||
}
|
||||
@@ -2893,27 +2943,27 @@ module ts {
|
||||
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo) {
|
||||
displayParts.push(keywordPart(SyntaxKind.ClassKeyword));
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
|
||||
addFullSymbolName(symbol);
|
||||
writeTypeParametersOfSymbol(symbol, sourceFile);
|
||||
}
|
||||
if ((symbolFlags & SymbolFlags.Interface) && (semanticMeaning & SemanticMeaning.Type)) {
|
||||
addNewLineIfDisplayPartsExist();
|
||||
displayParts.push(keywordPart(SyntaxKind.InterfaceKeyword));
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
|
||||
addFullSymbolName(symbol);
|
||||
writeTypeParametersOfSymbol(symbol, sourceFile);
|
||||
}
|
||||
if (symbolFlags & SymbolFlags.Enum) {
|
||||
addNewLineIfDisplayPartsExist();
|
||||
displayParts.push(keywordPart(SyntaxKind.EnumKeyword));
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, sourceFile));
|
||||
addFullSymbolName(symbol);
|
||||
}
|
||||
if (symbolFlags & SymbolFlags.Module) {
|
||||
addNewLineIfDisplayPartsExist();
|
||||
displayParts.push(keywordPart(SyntaxKind.ModuleKeyword));
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, sourceFile));
|
||||
addFullSymbolName(symbol);
|
||||
}
|
||||
if ((symbolFlags & SymbolFlags.TypeParameter) && (semanticMeaning & SemanticMeaning.Type)) {
|
||||
addNewLineIfDisplayPartsExist();
|
||||
@@ -2921,13 +2971,13 @@ module ts {
|
||||
displayParts.push(textPart("type parameter"));
|
||||
displayParts.push(punctuationPart(SyntaxKind.CloseParenToken));
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, enclosingDeclaration));
|
||||
addFullSymbolName(symbol);
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push(keywordPart(SyntaxKind.InKeyword));
|
||||
displayParts.push(spacePart());
|
||||
if (symbol.parent) {
|
||||
// Class/Interface type parameter
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol.parent, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments))
|
||||
addFullSymbolName(symbol.parent, enclosingDeclaration);
|
||||
writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration);
|
||||
}
|
||||
else {
|
||||
@@ -2939,7 +2989,7 @@ module ts {
|
||||
displayParts.push(spacePart());
|
||||
}
|
||||
else if (signatureDeclaration.kind !== SyntaxKind.CallSignature && signatureDeclaration.name) {
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, signatureDeclaration.symbol, sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments))
|
||||
addFullSymbolName(signatureDeclaration.symbol);
|
||||
}
|
||||
displayParts.push.apply(displayParts, signatureToDisplayParts(typeResolver, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
|
||||
}
|
||||
@@ -2959,24 +3009,43 @@ module ts {
|
||||
}
|
||||
if (symbolFlags & SymbolFlags.Import) {
|
||||
addNewLineIfDisplayPartsExist();
|
||||
displayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
|
||||
displayParts.push(textPart("alias"));
|
||||
displayParts.push(punctuationPart(SyntaxKind.CloseParenToken));
|
||||
displayParts.push(keywordPart(SyntaxKind.ImportKeyword));
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, sourceFile));
|
||||
addFullSymbolName(symbol);
|
||||
displayParts.push(spacePart());
|
||||
displayParts.push(punctuationPart(SyntaxKind.EqualsToken));
|
||||
displayParts.push(spacePart());
|
||||
ts.forEach(symbol.declarations, declaration => {
|
||||
if (declaration.kind === SyntaxKind.ImportDeclaration) {
|
||||
var importDeclaration = <ImportDeclaration>declaration;
|
||||
if (importDeclaration.externalModuleName) {
|
||||
displayParts.push(keywordPart(SyntaxKind.RequireKeyword));
|
||||
displayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
|
||||
displayParts.push(displayPart(getTextOfNode(importDeclaration.externalModuleName), SymbolDisplayPartKind.stringLiteral));
|
||||
displayParts.push(punctuationPart(SyntaxKind.CloseParenToken));
|
||||
}
|
||||
else {
|
||||
var internalAliasSymbol = typeResolver.getSymbolInfo(importDeclaration.entityName);
|
||||
addFullSymbolName(internalAliasSymbol, enclosingDeclaration);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!hasAddedSymbolInfo) {
|
||||
if (symbolKind !== ScriptElementKind.unknown) {
|
||||
if (type) {
|
||||
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
|
||||
// For properties, variables and local vars: show the type
|
||||
if (symbolKind === ScriptElementKind.memberVariableElement ||
|
||||
symbolFlags & SymbolFlags.Variable) {
|
||||
symbolFlags & SymbolFlags.Variable ||
|
||||
symbolKind === ScriptElementKind.localVariableElement) {
|
||||
displayParts.push(punctuationPart(SyntaxKind.ColonToken));
|
||||
displayParts.push(spacePart());
|
||||
// If the type is type parameter, format it specially
|
||||
if (type.symbol && type.symbol.flags & SymbolFlags.TypeParameter) {
|
||||
var typeParameterParts = mapToDisplayParts(writer => {
|
||||
typeResolver.writeTypeParameter(<TypeParameter>type, writer, enclosingDeclaration);
|
||||
typeResolver.getSymbolDisplayBuilder().buildTypeParameterDisplay(<TypeParameter>type, writer, enclosingDeclaration);
|
||||
});
|
||||
displayParts.push.apply(displayParts, typeParameterParts);
|
||||
}
|
||||
@@ -2988,14 +3057,15 @@ module ts {
|
||||
symbolFlags & SymbolFlags.Method ||
|
||||
symbolFlags & SymbolFlags.Constructor ||
|
||||
symbolFlags & SymbolFlags.Signature ||
|
||||
symbolFlags & SymbolFlags.Accessor) {
|
||||
symbolFlags & SymbolFlags.Accessor ||
|
||||
symbolKind === ScriptElementKind.memberFunctionElement) {
|
||||
var allSignatures = type.getCallSignatures();
|
||||
addSignatureDisplayParts(allSignatures[0], allSignatures);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
symbolKind = getSymbolKind(symbol, semanticMeaning);
|
||||
symbolKind = getSymbolKind(symbol, typeResolver);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3011,6 +3081,12 @@ module ts {
|
||||
}
|
||||
}
|
||||
|
||||
function addFullSymbolName(symbol: Symbol, enclosingDeclaration?: Node) {
|
||||
var fullSymbolDisplayParts = symbolToDisplayParts(typeResolver, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined,
|
||||
SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing);
|
||||
displayParts.push.apply(displayParts, fullSymbolDisplayParts);
|
||||
}
|
||||
|
||||
function addPrefixForAnyFunctionOrVar(symbol: Symbol, symbolKind: string) {
|
||||
addNewLineIfDisplayPartsExist();
|
||||
if (symbolKind) {
|
||||
@@ -3018,8 +3094,7 @@ module ts {
|
||||
displayParts.push(textPart(symbolKind));
|
||||
displayParts.push(punctuationPart(SyntaxKind.CloseParenToken));
|
||||
displayParts.push(spacePart());
|
||||
// Write type parameters of class/Interface if it is property/method of the generic class/interface
|
||||
displayParts.push.apply(displayParts, symbolToDisplayParts(typeResolver, symbol, sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
|
||||
addFullSymbolName(symbol);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3039,7 +3114,7 @@ module ts {
|
||||
|
||||
function writeTypeParametersOfSymbol(symbol: Symbol, enclosingDeclaration: Node) {
|
||||
var typeParameterParts = mapToDisplayParts(writer => {
|
||||
typeResolver.writeTypeParametersOfSymbol(symbol, writer, enclosingDeclaration);
|
||||
typeResolver.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration);
|
||||
});
|
||||
displayParts.push.apply(displayParts, typeParameterParts);
|
||||
}
|
||||
@@ -3057,12 +3132,6 @@ module ts {
|
||||
|
||||
var symbol = typeInfoResolver.getSymbolInfo(node);
|
||||
if (!symbol) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var symbol = typeInfoResolver.getSymbolInfo(node);
|
||||
if (!symbol) {
|
||||
|
||||
// Try getting just type at this position and show
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.Identifier:
|
||||
@@ -3070,7 +3139,7 @@ module ts {
|
||||
case SyntaxKind.QualifiedName:
|
||||
case SyntaxKind.ThisKeyword:
|
||||
case SyntaxKind.SuperKeyword:
|
||||
// For the identifiers/this/usper etc get the type at position
|
||||
// For the identifiers/this/super etc get the type at position
|
||||
var type = typeInfoResolver.getTypeOfNode(node);
|
||||
if (type) {
|
||||
return {
|
||||
@@ -3097,7 +3166,7 @@ module ts {
|
||||
}
|
||||
|
||||
/// Goto definition
|
||||
function getDefinitionAtPosition(filename: string, position: number): DefinitionInfo[]{
|
||||
function getDefinitionAtPosition(filename: string, position: number): DefinitionInfo[] {
|
||||
function getDefinitionInfo(node: Node, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo {
|
||||
return {
|
||||
fileName: node.getSourceFile().filename,
|
||||
@@ -3129,7 +3198,7 @@ module ts {
|
||||
result.push(getDefinitionInfo(declarations[declarations.length - 1], symbolKind, symbolName, containerName));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -3193,7 +3262,7 @@ module ts {
|
||||
|
||||
// Could not find a symbol e.g. node is string or number keyword,
|
||||
// or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
|
||||
if (!symbol || !(symbol.getDeclarations())) {
|
||||
if (!symbol) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -3201,7 +3270,7 @@ module ts {
|
||||
|
||||
var declarations = symbol.getDeclarations();
|
||||
var symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
|
||||
var symbolKind = getSymbolKind(symbol, getMeaningFromLocation(node));
|
||||
var symbolKind = getSymbolKind(symbol, typeInfoResolver);
|
||||
var containerSymbol = symbol.parent;
|
||||
var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : "";
|
||||
|
||||
@@ -3726,18 +3795,20 @@ module ts {
|
||||
return [getReferenceEntryFromNode(node)];
|
||||
}
|
||||
|
||||
// the symbol was an internal symbol and does not have a declaration e.g.undefined symbol
|
||||
if (!symbol.getDeclarations()) {
|
||||
var declarations = symbol.declarations;
|
||||
|
||||
// The symbol was an internal symbol and does not have a declaration e.g.undefined symbol
|
||||
if (!declarations || !declarations.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var result: ReferenceEntry[];
|
||||
|
||||
// Compute the meaning from the location and the symbol it references
|
||||
var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), symbol.getDeclarations());
|
||||
var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations);
|
||||
|
||||
// Get the text to search for, we need to normalize it as external module names will have quote
|
||||
var symbolName = getNormalizedSymbolName(symbol);
|
||||
var symbolName = getNormalizedSymbolName(symbol.name, declarations);
|
||||
|
||||
// Get syntactic diagnostics
|
||||
var scope = getSymbolScope(symbol);
|
||||
@@ -3759,15 +3830,15 @@ module ts {
|
||||
|
||||
return result;
|
||||
|
||||
function getNormalizedSymbolName(symbol: Symbol): string {
|
||||
function getNormalizedSymbolName(symbolName: string, declarations: Declaration[]): string {
|
||||
// Special case for function expressions, whose names are solely local to their bodies.
|
||||
var functionExpression = getDeclarationOfKind(symbol, SyntaxKind.FunctionExpression);
|
||||
var functionExpression = forEach(declarations, d => d.kind === SyntaxKind.FunctionExpression ? d : undefined);
|
||||
|
||||
if (functionExpression && functionExpression.name) {
|
||||
var name = functionExpression.name.text;
|
||||
}
|
||||
else {
|
||||
var name = symbol.name;
|
||||
var name = symbolName;
|
||||
}
|
||||
|
||||
var length = name.length;
|
||||
@@ -3794,22 +3865,24 @@ module ts {
|
||||
var scope: Node = undefined;
|
||||
|
||||
var declarations = symbol.getDeclarations();
|
||||
for (var i = 0, n = declarations.length; i < n; i++) {
|
||||
var container = getContainerNode(declarations[i]);
|
||||
if (declarations) {
|
||||
for (var i = 0, n = declarations.length; i < n; i++) {
|
||||
var container = getContainerNode(declarations[i]);
|
||||
|
||||
if (scope && scope !== container) {
|
||||
// Different declarations have different containers, bail out
|
||||
return undefined;
|
||||
if (scope && scope !== container) {
|
||||
// Different declarations have different containers, bail out
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (container.kind === SyntaxKind.SourceFile && !isExternalModule(<SourceFile>container)) {
|
||||
// This is a global variable and not an external module, any declaration defined
|
||||
// within this scope is visible outside the file
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The search scope is the container node
|
||||
scope = container;
|
||||
}
|
||||
|
||||
if (container.kind === SyntaxKind.SourceFile && !isExternalModule(<SourceFile>container)) {
|
||||
// This is a global variable and not an external module, any declaration defined
|
||||
// within this scope is visible outside the file
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The search scope is the container node
|
||||
scope = container;
|
||||
}
|
||||
|
||||
return scope;
|
||||
@@ -3945,14 +4018,7 @@ module ts {
|
||||
}
|
||||
|
||||
var referenceSymbol = typeInfoResolver.getSymbolInfo(referenceLocation);
|
||||
|
||||
// Could not find a symbol e.g. node is string or number keyword,
|
||||
// or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol
|
||||
if (!referenceSymbol || !(referenceSymbol.getDeclarations())) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRelatableToSearchSet(searchSymbols, referenceSymbol, referenceLocation)) {
|
||||
if (referenceSymbol && isRelatableToSearchSet(searchSymbols, referenceSymbol, referenceLocation)) {
|
||||
result.push(getReferenceEntryFromNode(referenceLocation));
|
||||
}
|
||||
});
|
||||
@@ -4114,24 +4180,27 @@ module ts {
|
||||
// The search set contains at least the current symbol
|
||||
var result = [symbol];
|
||||
|
||||
// If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list
|
||||
var rootSymbol = typeInfoResolver.getRootSymbol(symbol);
|
||||
if (rootSymbol && rootSymbol !== symbol) {
|
||||
result.push(rootSymbol);
|
||||
}
|
||||
|
||||
// If the location is in a context sensitive location (i.e. in an object literal) try
|
||||
// to get a contextual type for it, and add the property symbol from the contextual
|
||||
// type to the search set
|
||||
if (isNameOfPropertyAssignment(location)) {
|
||||
var symbolFromContextualType = getPropertySymbolFromContextualType(location);
|
||||
if (symbolFromContextualType) result.push(typeInfoResolver.getRootSymbol(symbolFromContextualType));
|
||||
forEach(getPropertySymbolsFromContextualType(location), contextualSymbol => {
|
||||
result.push.apply(result, typeInfoResolver.getRootSymbols(contextualSymbol));
|
||||
});
|
||||
}
|
||||
|
||||
// Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
|
||||
if (symbol.parent && symbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
|
||||
getPropertySymbolsFromBaseTypes(symbol.parent, symbol.getName(), result);
|
||||
}
|
||||
// If this is a union property, add all the symbols from all its source symbols in all unioned types.
|
||||
// If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list
|
||||
forEach(typeInfoResolver.getRootSymbols(symbol), rootSymbol => {
|
||||
if (rootSymbol !== symbol) {
|
||||
result.push(rootSymbol);
|
||||
}
|
||||
|
||||
// Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
|
||||
if (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
|
||||
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result);
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -4167,11 +4236,7 @@ module ts {
|
||||
}
|
||||
|
||||
function isRelatableToSearchSet(searchSymbols: Symbol[], referenceSymbol: Symbol, referenceLocation: Node): boolean {
|
||||
// Unwrap symbols to get to the root (e.g. transient symbols as a result of widening)
|
||||
var referenceSymbolTarget = typeInfoResolver.getRootSymbol(referenceSymbol);
|
||||
|
||||
// if it is in the list, then we are done
|
||||
if (searchSymbols.indexOf(referenceSymbolTarget) >= 0) {
|
||||
if (searchSymbols.indexOf(referenceSymbol) >= 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -4179,29 +4244,61 @@ module ts {
|
||||
// object literal, lookup the property symbol in the contextual type, and use this symbol to
|
||||
// compare to our searchSymbol
|
||||
if (isNameOfPropertyAssignment(referenceLocation)) {
|
||||
var symbolFromContextualType = getPropertySymbolFromContextualType(referenceLocation);
|
||||
if (symbolFromContextualType && searchSymbols.indexOf(typeInfoResolver.getRootSymbol(symbolFromContextualType)) >= 0) {
|
||||
return forEach(getPropertySymbolsFromContextualType(referenceLocation), contextualSymbol => {
|
||||
return forEach(typeInfoResolver.getRootSymbols(contextualSymbol), s => searchSymbols.indexOf(s) >= 0);
|
||||
});
|
||||
}
|
||||
|
||||
// Unwrap symbols to get to the root (e.g. transient symbols as a result of widening)
|
||||
// Or a union property, use its underlying unioned symbols
|
||||
return forEach(typeInfoResolver.getRootSymbols(referenceSymbol), rootSymbol => {
|
||||
// if it is in the list, then we are done
|
||||
if (searchSymbols.indexOf(rootSymbol) >= 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, try all properties with the same name in any type the containing type extend or implemented, and
|
||||
// see if any is in the list
|
||||
if (referenceSymbol.parent && referenceSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
|
||||
var result: Symbol[] = [];
|
||||
getPropertySymbolsFromBaseTypes(referenceSymbol.parent, referenceSymbol.getName(), result);
|
||||
return forEach(result, s => searchSymbols.indexOf(s) >= 0);
|
||||
}
|
||||
// Finally, try all properties with the same name in any type the containing type extended or implemented, and
|
||||
// see if any is in the list
|
||||
if (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
|
||||
var result: Symbol[] = [];
|
||||
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result);
|
||||
return forEach(result, s => searchSymbols.indexOf(s) >= 0);
|
||||
}
|
||||
|
||||
return false;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
function getPropertySymbolFromContextualType(node: Node): Symbol {
|
||||
function getPropertySymbolsFromContextualType(node: Node): Symbol[] {
|
||||
if (isNameOfPropertyAssignment(node)) {
|
||||
var objectLiteral = node.parent.parent;
|
||||
var contextualType = typeInfoResolver.getContextualType(objectLiteral);
|
||||
var name = (<Identifier>node).text;
|
||||
if (contextualType) {
|
||||
return typeInfoResolver.getPropertyOfType(contextualType, (<Identifier>node).text);
|
||||
if (contextualType.flags & TypeFlags.Union) {
|
||||
// This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types)
|
||||
// if not, search the constituent types for the property
|
||||
var unionProperty = contextualType.getProperty(name)
|
||||
if (unionProperty) {
|
||||
return [unionProperty];
|
||||
}
|
||||
else {
|
||||
var result: Symbol[] = [];
|
||||
forEach((<UnionType>contextualType).types, t => {
|
||||
var symbol = t.getProperty(name);
|
||||
if (symbol) {
|
||||
result.push(symbol);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
else {
|
||||
var symbol = contextualType.getProperty(name);
|
||||
if (symbol) {
|
||||
return [symbol];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
@@ -4718,7 +4815,24 @@ module ts {
|
||||
}
|
||||
}
|
||||
else if (flags & SymbolFlags.Module) {
|
||||
return ClassificationTypeNames.moduleName;
|
||||
// Only classify a module as such if
|
||||
// - It appears in a namespace context.
|
||||
// - There exists a module declaration which actually impacts the value side.
|
||||
if (meaningAtPosition & SemanticMeaning.Namespace ||
|
||||
(meaningAtPosition & SemanticMeaning.Value && hasValueSideModule(symbol))) {
|
||||
return ClassificationTypeNames.moduleName;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
||||
/**
|
||||
* Returns true if there exists a module that introduces entities on the value side.
|
||||
*/
|
||||
function hasValueSideModule(symbol: Symbol): boolean {
|
||||
return forEach(symbol.declarations, declaration => {
|
||||
return declaration.kind === SyntaxKind.ModuleDeclaration && isInstantiated(declaration);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4749,115 +4863,99 @@ module ts {
|
||||
var sourceFile = getCurrentSourceFile(fileName);
|
||||
|
||||
var result: ClassifiedSpan[] = [];
|
||||
processElement(sourceFile.getSourceUnit());
|
||||
processElement(sourceFile);
|
||||
|
||||
return result;
|
||||
|
||||
function classifyTrivia(trivia: TypeScript.ISyntaxTrivia) {
|
||||
if (trivia.isComment() && span.intersectsWith(trivia.fullStart(), trivia.fullWidth())) {
|
||||
function classifyComment(comment: CommentRange) {
|
||||
var width = comment.end - comment.pos;
|
||||
if (span.intersectsWith(comment.pos, width)) {
|
||||
result.push({
|
||||
textSpan: new TypeScript.TextSpan(trivia.fullStart(), trivia.fullWidth()),
|
||||
textSpan: new TypeScript.TextSpan(comment.pos, width),
|
||||
classificationType: ClassificationTypeNames.comment
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function classifyTriviaList(trivia: TypeScript.ISyntaxTriviaList) {
|
||||
for (var i = 0, n = trivia.count(); i < n; i++) {
|
||||
classifyTrivia(trivia.syntaxTriviaAt(i));
|
||||
}
|
||||
}
|
||||
function classifyToken(token: Node): void {
|
||||
forEach(getLeadingCommentRanges(sourceFile.text, token.getFullStart()), classifyComment);
|
||||
|
||||
function classifyToken(token: TypeScript.ISyntaxToken) {
|
||||
if (token.hasLeadingComment()) {
|
||||
classifyTriviaList(token.leadingTrivia());
|
||||
}
|
||||
|
||||
if (TypeScript.width(token) > 0) {
|
||||
if (token.getWidth() > 0) {
|
||||
var type = classifyTokenType(token);
|
||||
if (type) {
|
||||
result.push({
|
||||
textSpan: new TypeScript.TextSpan(TypeScript.start(token), TypeScript.width(token)),
|
||||
textSpan: new TypeScript.TextSpan(token.getStart(), token.getWidth()),
|
||||
classificationType: type
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (token.hasTrailingComment()) {
|
||||
classifyTriviaList(token.trailingTrivia());
|
||||
}
|
||||
forEach(getTrailingCommentRanges(sourceFile.text, token.getEnd()), classifyComment);
|
||||
}
|
||||
|
||||
function classifyTokenType(token: TypeScript.ISyntaxToken): string {
|
||||
var tokenKind = token.kind();
|
||||
if (TypeScript.SyntaxFacts.isAnyKeyword(token.kind())) {
|
||||
function classifyTokenType(token: Node): string {
|
||||
var tokenKind = token.kind;
|
||||
if (isKeyword(tokenKind)) {
|
||||
return ClassificationTypeNames.keyword;
|
||||
}
|
||||
|
||||
// Special case < and > If they appear in a generic context they are punctation,
|
||||
// Special case < and > If they appear in a generic context they are punctuation,
|
||||
// not operators.
|
||||
if (tokenKind === TypeScript.SyntaxKind.LessThanToken || tokenKind === TypeScript.SyntaxKind.GreaterThanToken) {
|
||||
var tokenParentKind = token.parent.kind();
|
||||
if (tokenParentKind === TypeScript.SyntaxKind.TypeArgumentList ||
|
||||
tokenParentKind === TypeScript.SyntaxKind.TypeParameterList) {
|
||||
|
||||
if (tokenKind === SyntaxKind.LessThanToken || tokenKind === SyntaxKind.GreaterThanToken) {
|
||||
// If the node owning the token has a type argument list or type parameter list, then
|
||||
// we can effectively assume that a '<' and '>' belong to those lists.
|
||||
if (getTypeArgumentOrTypeParameterList(token.parent)) {
|
||||
return ClassificationTypeNames.punctuation;
|
||||
}
|
||||
}
|
||||
|
||||
if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(tokenKind) ||
|
||||
TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(tokenKind)) {
|
||||
return ClassificationTypeNames.operator;
|
||||
if (isPunctuation(token)) {
|
||||
// the '=' in a variable declaration is special cased here.
|
||||
if (token.parent.kind === SyntaxKind.BinaryExpression ||
|
||||
token.parent.kind === SyntaxKind.VariableDeclaration ||
|
||||
token.parent.kind === SyntaxKind.PrefixOperator ||
|
||||
token.parent.kind === SyntaxKind.PostfixOperator ||
|
||||
token.parent.kind === SyntaxKind.ConditionalExpression) {
|
||||
return ClassificationTypeNames.operator;
|
||||
}
|
||||
else {
|
||||
return ClassificationTypeNames.punctuation;
|
||||
}
|
||||
}
|
||||
else if (TypeScript.SyntaxFacts.isAnyPunctuation(tokenKind)) {
|
||||
return ClassificationTypeNames.punctuation;
|
||||
}
|
||||
else if (tokenKind === TypeScript.SyntaxKind.NumericLiteral) {
|
||||
else if (tokenKind === SyntaxKind.NumericLiteral) {
|
||||
return ClassificationTypeNames.numericLiteral;
|
||||
}
|
||||
else if (tokenKind === TypeScript.SyntaxKind.StringLiteral) {
|
||||
else if (tokenKind === SyntaxKind.StringLiteral) {
|
||||
return ClassificationTypeNames.stringLiteral;
|
||||
}
|
||||
else if (tokenKind === TypeScript.SyntaxKind.RegularExpressionLiteral) {
|
||||
// TODO: we shoudl get another classification type for these literals.
|
||||
else if (tokenKind === SyntaxKind.RegularExpressionLiteral) {
|
||||
// TODO: we should get another classification type for these literals.
|
||||
return ClassificationTypeNames.stringLiteral;
|
||||
}
|
||||
else if (tokenKind === TypeScript.SyntaxKind.IdentifierName) {
|
||||
var current: TypeScript.ISyntaxNodeOrToken = token;
|
||||
var parent = token.parent;
|
||||
while (parent.kind() === TypeScript.SyntaxKind.QualifiedName) {
|
||||
current = parent;
|
||||
parent = parent.parent;
|
||||
}
|
||||
|
||||
switch (parent.kind()) {
|
||||
case TypeScript.SyntaxKind.SimplePropertyAssignment:
|
||||
if ((<TypeScript.SimplePropertyAssignmentSyntax>parent).propertyName === token) {
|
||||
return ClassificationTypeNames.identifier;
|
||||
}
|
||||
return;
|
||||
case TypeScript.SyntaxKind.ClassDeclaration:
|
||||
if ((<TypeScript.ClassDeclarationSyntax>parent).identifier === token) {
|
||||
else if (tokenKind === SyntaxKind.Identifier) {
|
||||
switch (token.parent.kind) {
|
||||
case SyntaxKind.ClassDeclaration:
|
||||
if ((<ClassDeclaration>token.parent).name === token) {
|
||||
return ClassificationTypeNames.className;
|
||||
}
|
||||
return;
|
||||
case TypeScript.SyntaxKind.TypeParameter:
|
||||
if ((<TypeScript.TypeParameterSyntax>parent).identifier === token) {
|
||||
case SyntaxKind.TypeParameter:
|
||||
if ((<TypeParameterDeclaration>token.parent).name === token) {
|
||||
return ClassificationTypeNames.typeParameterName;
|
||||
}
|
||||
return;
|
||||
case TypeScript.SyntaxKind.InterfaceDeclaration:
|
||||
if ((<TypeScript.InterfaceDeclarationSyntax>parent).identifier === token) {
|
||||
case SyntaxKind.InterfaceDeclaration:
|
||||
if ((<InterfaceDeclaration>token.parent).name === token) {
|
||||
return ClassificationTypeNames.interfaceName;
|
||||
}
|
||||
return;
|
||||
case TypeScript.SyntaxKind.EnumDeclaration:
|
||||
if ((<TypeScript.EnumDeclarationSyntax>parent).identifier === token) {
|
||||
case SyntaxKind.EnumDeclaration:
|
||||
if ((<EnumDeclaration>token.parent).name === token) {
|
||||
return ClassificationTypeNames.enumName;
|
||||
}
|
||||
return;
|
||||
case TypeScript.SyntaxKind.ModuleDeclaration:
|
||||
if ((<TypeScript.ModuleDeclarationSyntax>parent).name === current) {
|
||||
case SyntaxKind.ModuleDeclaration:
|
||||
if ((<ModuleDeclaration>token.parent).name === token) {
|
||||
return ClassificationTypeNames.moduleName;
|
||||
}
|
||||
return;
|
||||
@@ -4867,19 +4965,18 @@ module ts {
|
||||
}
|
||||
}
|
||||
|
||||
function processElement(element: TypeScript.ISyntaxElement) {
|
||||
function processElement(element: Node) {
|
||||
// Ignore nodes that don't intersect the original span to classify.
|
||||
if (!TypeScript.isShared(element) && span.intersectsWith(TypeScript.fullStart(element), TypeScript.fullWidth(element))) {
|
||||
for (var i = 0, n = TypeScript.childCount(element); i < n; i++) {
|
||||
var child = TypeScript.childAt(element, i);
|
||||
if (child) {
|
||||
if (TypeScript.isToken(child)) {
|
||||
classifyToken(<TypeScript.ISyntaxToken>child);
|
||||
}
|
||||
else {
|
||||
// Recurse into our child nodes.
|
||||
processElement(child);
|
||||
}
|
||||
if (span.intersectsWith(element.getFullStart(), element.getFullWidth())) {
|
||||
var children = element.getChildren();
|
||||
for (var i = 0, n = children.length; i < n; i++) {
|
||||
var child = children[i];
|
||||
if (isToken(child)) {
|
||||
classifyToken(child);
|
||||
}
|
||||
else {
|
||||
// Recurse into our child nodes.
|
||||
processElement(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5179,7 +5276,7 @@ module ts {
|
||||
|
||||
// Only allow a symbol to be renamed if it actually has at least one declaration.
|
||||
if (symbol && symbol.getDeclarations() && symbol.getDeclarations().length > 0) {
|
||||
var kind = getSymbolKind(symbol, getMeaningFromLocation(node));
|
||||
var kind = getSymbolKind(symbol, typeInfoResolver);
|
||||
if (kind) {
|
||||
return getRenameInfo(symbol.name, typeInfoResolver.getFullyQualifiedName(symbol), kind,
|
||||
getSymbolModifiers(symbol),
|
||||
|
||||
@@ -258,6 +258,13 @@ module ts.SignatureHelp {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getChildListThatStartsWithOpenerToken(parent: Node, openerToken: Node, sourceFile: SourceFile): Node {
|
||||
var children = parent.getChildren(sourceFile);
|
||||
var indexOfOpenerToken = children.indexOf(openerToken);
|
||||
Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
|
||||
return children[indexOfOpenerToken + 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* The selectedItemIndex could be negative for several reasons.
|
||||
* 1. There are too many arguments for all of the overloads
|
||||
@@ -287,74 +294,51 @@ module ts.SignatureHelp {
|
||||
|
||||
function createSignatureHelpItems(candidates: Signature[], bestSignature: Signature, argumentInfoOrTypeArgumentInfo: ListItemInfo): SignatureHelpItems {
|
||||
var argumentListOrTypeArgumentList = argumentInfoOrTypeArgumentInfo.list;
|
||||
var parent = <CallExpression>argumentListOrTypeArgumentList.parent;
|
||||
var isTypeParameterHelp = parent.typeArguments && parent.typeArguments.pos === argumentListOrTypeArgumentList.pos;
|
||||
Debug.assert(isTypeParameterHelp || parent.arguments.pos === argumentListOrTypeArgumentList.pos);
|
||||
|
||||
var callTargetNode = (<CallExpression>argumentListOrTypeArgumentList.parent).func;
|
||||
var callTargetSymbol = typeInfoResolver.getSymbolInfo(callTargetNode);
|
||||
var callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeInfoResolver, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined);
|
||||
var items: SignatureHelpItem[] = map(candidates, candidateSignature => {
|
||||
var parameters = candidateSignature.parameters;
|
||||
var parameterHelpItems: SignatureHelpParameter[] = parameters.length === 0 ? emptyArray : map(parameters, p => {
|
||||
var displayParts: SymbolDisplayPart[] = [];
|
||||
var signatureHelpParameters: SignatureHelpParameter[];
|
||||
var prefixParts: SymbolDisplayPart[] = [];
|
||||
var suffixParts: SymbolDisplayPart[] = [];
|
||||
|
||||
if (candidateSignature.hasRestParameter && parameters[parameters.length - 1] === p) {
|
||||
displayParts.push(punctuationPart(SyntaxKind.DotDotDotToken));
|
||||
}
|
||||
|
||||
displayParts.push(symbolPart(p.name, p));
|
||||
|
||||
var isOptional = !!(p.valueDeclaration.flags & NodeFlags.QuestionMark);
|
||||
if (isOptional) {
|
||||
displayParts.push(punctuationPart(SyntaxKind.QuestionToken));
|
||||
}
|
||||
|
||||
displayParts.push(punctuationPart(SyntaxKind.ColonToken));
|
||||
displayParts.push(spacePart());
|
||||
|
||||
var typeParts = typeToDisplayParts(typeInfoResolver, typeInfoResolver.getTypeOfSymbol(p), argumentListOrTypeArgumentList);
|
||||
displayParts.push.apply(displayParts, typeParts);
|
||||
|
||||
return {
|
||||
name: p.name,
|
||||
documentation: p.getDocumentationComment(),
|
||||
displayParts: displayParts,
|
||||
isOptional: isOptional
|
||||
};
|
||||
});
|
||||
|
||||
var callTargetNode = (<CallExpression>argumentListOrTypeArgumentList.parent).func;
|
||||
var callTargetSymbol = typeInfoResolver.getSymbolInfo(callTargetNode);
|
||||
|
||||
var prefixParts = callTargetSymbol ? symbolToDisplayParts(typeInfoResolver, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : [];
|
||||
|
||||
var separatorParts = [punctuationPart(SyntaxKind.CommaToken), spacePart()];
|
||||
|
||||
// TODO(jfreeman): Constraints?
|
||||
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
|
||||
prefixParts.push(punctuationPart(SyntaxKind.LessThanToken));
|
||||
|
||||
for (var i = 0, n = candidateSignature.typeParameters.length; i < n; i++) {
|
||||
if (i) {
|
||||
prefixParts.push.apply(prefixParts, separatorParts);
|
||||
}
|
||||
|
||||
var tp = candidateSignature.typeParameters[i].symbol;
|
||||
prefixParts.push(symbolPart(tp.name, tp));
|
||||
}
|
||||
|
||||
prefixParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
|
||||
if (callTargetDisplayParts) {
|
||||
prefixParts.push.apply(prefixParts, callTargetDisplayParts);
|
||||
}
|
||||
|
||||
prefixParts.push(punctuationPart(SyntaxKind.OpenParenToken));
|
||||
if (isTypeParameterHelp) {
|
||||
prefixParts.push(punctuationPart(SyntaxKind.LessThanToken));
|
||||
var typeParameters = candidateSignature.typeParameters;
|
||||
signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray;
|
||||
suffixParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
|
||||
var parameterParts = mapToDisplayParts(writer =>
|
||||
typeInfoResolver.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, argumentListOrTypeArgumentList));
|
||||
suffixParts.push.apply(suffixParts, parameterParts);
|
||||
}
|
||||
else {
|
||||
var typeParameterParts = mapToDisplayParts(writer =>
|
||||
typeInfoResolver.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, argumentListOrTypeArgumentList));
|
||||
prefixParts.push.apply(prefixParts, typeParameterParts);
|
||||
prefixParts.push(punctuationPart(SyntaxKind.OpenParenToken));
|
||||
var parameters = candidateSignature.parameters;
|
||||
signatureHelpParameters = parameters.length > 0 ? map(parameters, createSignatureHelpParameterForParameter) : emptyArray;
|
||||
suffixParts.push(punctuationPart(SyntaxKind.CloseParenToken));
|
||||
}
|
||||
|
||||
var suffixParts = [punctuationPart(SyntaxKind.CloseParenToken)];
|
||||
suffixParts.push(punctuationPart(SyntaxKind.ColonToken));
|
||||
suffixParts.push(spacePart());
|
||||
|
||||
var typeParts = typeToDisplayParts(typeInfoResolver, candidateSignature.getReturnType(), argumentListOrTypeArgumentList);
|
||||
suffixParts.push.apply(suffixParts, typeParts);
|
||||
var returnTypeParts = mapToDisplayParts(writer =>
|
||||
typeInfoResolver.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, argumentListOrTypeArgumentList));
|
||||
suffixParts.push.apply(suffixParts, returnTypeParts);
|
||||
|
||||
return {
|
||||
isVariadic: candidateSignature.hasRestParameter,
|
||||
prefixDisplayParts: prefixParts,
|
||||
suffixDisplayParts: suffixParts,
|
||||
separatorDisplayParts: separatorParts,
|
||||
parameters: parameterHelpItems,
|
||||
separatorDisplayParts: [punctuationPart(SyntaxKind.CommaToken), spacePart()],
|
||||
parameters: signatureHelpParameters,
|
||||
documentation: candidateSignature.getDocumentationComment()
|
||||
};
|
||||
});
|
||||
@@ -400,12 +384,32 @@ module ts.SignatureHelp {
|
||||
argumentIndex: argumentIndex,
|
||||
argumentCount: argumentCount
|
||||
};
|
||||
|
||||
function createSignatureHelpParameterForParameter(parameter: Symbol): SignatureHelpParameter {
|
||||
var displayParts = mapToDisplayParts(writer =>
|
||||
typeInfoResolver.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, argumentListOrTypeArgumentList));
|
||||
|
||||
var isOptional = !!(parameter.valueDeclaration.flags & NodeFlags.QuestionMark);
|
||||
|
||||
return {
|
||||
name: parameter.name,
|
||||
documentation: parameter.getDocumentationComment(),
|
||||
displayParts: displayParts,
|
||||
isOptional: isOptional
|
||||
};
|
||||
}
|
||||
|
||||
function createSignatureHelpParameterForTypeParameter(typeParameter: TypeParameter): SignatureHelpParameter {
|
||||
var displayParts = mapToDisplayParts(writer =>
|
||||
typeInfoResolver.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, argumentListOrTypeArgumentList));
|
||||
|
||||
return {
|
||||
name: typeParameter.symbol.name,
|
||||
documentation: emptyArray,
|
||||
displayParts: displayParts,
|
||||
isOptional: false
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getChildListThatStartsWithOpenerToken(parent: Node, openerToken: Node, sourceFile: SourceFile): Node {
|
||||
var children = parent.getChildren(sourceFile);
|
||||
var indexOfOpenerToken = children.indexOf(openerToken);
|
||||
return children[indexOfOpenerToken + 1];
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,6 @@ module TypeScript {
|
||||
private cacheSyntaxTreeInfo(): void {
|
||||
// If we're not keeping around the syntax tree, store the diagnostics and line
|
||||
// map so they don't have to be recomputed.
|
||||
var sourceUnit = this.sourceUnit();
|
||||
var firstToken = firstSyntaxTreeToken(this);
|
||||
var leadingTrivia = firstToken.leadingTrivia(this.text);
|
||||
|
||||
|
||||
@@ -230,19 +230,35 @@ module ts {
|
||||
return n.kind !== SyntaxKind.SyntaxList || n.getChildCount() !== 0;
|
||||
}
|
||||
|
||||
export function getTypeArgumentOrTypeParameterList(node: Node): NodeArray<Node> {
|
||||
if (node.kind === SyntaxKind.TypeReference || node.kind === SyntaxKind.CallExpression) {
|
||||
return (<CallExpression>node).typeArguments;
|
||||
}
|
||||
|
||||
if (isAnyFunction(node) || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.InterfaceDeclaration) {
|
||||
return (<FunctionDeclaration>node).typeParameters;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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);
|
||||
return n.kind === SyntaxKind.Identifier || isKeyword(n.kind);
|
||||
}
|
||||
|
||||
function isPropertyName(n: Node): boolean {
|
||||
return n.kind === SyntaxKind.StringLiteral || n.kind === SyntaxKind.NumericLiteral || isWord(n);
|
||||
}
|
||||
|
||||
export function isComment(n: Node): boolean {
|
||||
return n.kind === SyntaxKind.SingleLineCommentTrivia || n.kind === SyntaxKind.MultiLineCommentTrivia;
|
||||
}
|
||||
|
||||
export function isPunctuation(n: Node): boolean {
|
||||
return SyntaxKind.FirstPunctuation <= n.kind && n.kind <= SyntaxKind.LastPunctuation;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user