Merge branch 'master' into javascriptLanguageservice

Conflicts:
	src/services/services.ts
This commit is contained in:
Cyrus Najmabadi
2015-03-24 13:23:23 -07:00
573 changed files with 14131 additions and 3496 deletions
+137 -36
View File
@@ -512,6 +512,19 @@ module ts {
node.kind === SyntaxKind.ExportAssignment;
}
function getAnyImportSyntax(node: Node): AnyImportSyntax {
if (isAliasSymbolDeclaration(node)) {
if (node.kind === SyntaxKind.ImportEqualsDeclaration) {
return <ImportEqualsDeclaration>node;
}
while (node.kind !== SyntaxKind.ImportDeclaration) {
node = node.parent;
}
return <ImportDeclaration>node;
}
}
function getDeclarationOfAliasSymbol(symbol: Symbol): Declaration {
return forEach(symbol.declarations, d => isAliasSymbolDeclaration(d) ? d : undefined);
}
@@ -783,7 +796,7 @@ module ts {
}
function getExportsForModule(moduleSymbol: Symbol): SymbolTable {
if (compilerOptions.target < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES6) {
// A default export hides all other exports in CommonJS and AMD modules
let defaultSymbol = getExportAssignmentSymbol(moduleSymbol);
if (defaultSymbol) {
@@ -1122,7 +1135,7 @@ module ts {
}
function hasVisibleDeclarations(symbol: Symbol): SymbolVisibilityResult {
let aliasesToMakeVisible: ImportEqualsDeclaration[];
let aliasesToMakeVisible: AnyImportSyntax[];
if (forEach(symbol.declarations, declaration => !getIsDeclarationVisible(declaration))) {
return undefined;
}
@@ -1132,17 +1145,19 @@ module ts {
if (!isDeclarationVisible(declaration)) {
// Mark the unexported alias as visible if its parent is visible
// because these kind of aliases can be used to name types in declaration file
if (declaration.kind === SyntaxKind.ImportEqualsDeclaration &&
!(declaration.flags & NodeFlags.Export) &&
isDeclarationVisible(<Declaration>declaration.parent)) {
var anyImportSyntax = getAnyImportSyntax(declaration);
if (anyImportSyntax &&
!(anyImportSyntax.flags & NodeFlags.Export) && // import clause without export
isDeclarationVisible(<Declaration>anyImportSyntax.parent)) {
getNodeLinks(declaration).isVisible = true;
if (aliasesToMakeVisible) {
if (!contains(aliasesToMakeVisible, declaration)) {
aliasesToMakeVisible.push(<ImportEqualsDeclaration>declaration);
if (!contains(aliasesToMakeVisible, anyImportSyntax)) {
aliasesToMakeVisible.push(anyImportSyntax);
}
}
else {
aliasesToMakeVisible = [<ImportEqualsDeclaration>declaration];
aliasesToMakeVisible = [anyImportSyntax];
}
return true;
}
@@ -1766,8 +1781,15 @@ module ts {
function determineIfDeclarationIsVisible() {
switch (node.kind) {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
return isDeclarationVisible(<Declaration>node.parent.parent);
case SyntaxKind.VariableDeclaration:
if (isBindingPattern(node.name) &&
!(<BindingPattern>node.name).elements.length) {
// If the binding pattern is empty, this variable declaration is not visible
return false;
}
// Otherwise fall through
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
@@ -1779,7 +1801,7 @@ module ts {
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(getCombinedNodeFlags(node) & NodeFlags.Export) &&
!(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && isInAmbientContext(parent))) {
return isGlobalSourceFile(parent) || isUsedInExportAssignment(node);
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
return isDeclarationVisible(<Declaration>parent);
@@ -1812,6 +1834,13 @@ module ts {
case SyntaxKind.ParenthesizedType:
return isDeclarationVisible(<Declaration>node.parent);
// Default binding, import specifier and namespace import is visible
// only on demand so by default it is not visible
case SyntaxKind.ImportClause:
case SyntaxKind.NamespaceImport:
case SyntaxKind.ImportSpecifier:
return false;
// Type parameters are always visible
case SyntaxKind.TypeParameter:
// Source file is always visible
@@ -1832,6 +1861,40 @@ module ts {
}
}
function collectLinkedAliases(node: Identifier): Node[]{
var exportSymbol: Symbol;
if (node.parent && node.parent.kind === SyntaxKind.ExportAssignment) {
exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, node);
}
else if (node.parent.kind === SyntaxKind.ExportSpecifier) {
exportSymbol = getTargetOfExportSpecifier(<ExportSpecifier>node.parent);
}
var result: Node[] = [];
if (exportSymbol) {
buildVisibleNodeList(exportSymbol.declarations);
}
return result;
function buildVisibleNodeList(declarations: Declaration[]) {
forEach(declarations, declaration => {
getNodeLinks(declaration).isVisible = true;
var resultNode = getAnyImportSyntax(declaration) || declaration;
if (!contains(result, resultNode)) {
result.push(resultNode);
}
if (isInternalModuleImportEqualsDeclaration(declaration)) {
// Add the referenced top container visible
var internalModuleReference = <Identifier | QualifiedName>(<ImportEqualsDeclaration>declaration).moduleReference;
var firstIdentifier = getFirstIdentifier(internalModuleReference);
var importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace,
Diagnostics.Cannot_find_name_0, firstIdentifier);
buildVisibleNodeList(importSymbol.declarations);
}
});
}
}
function getRootDeclaration(node: Node): Node {
while (node.kind === SyntaxKind.BindingElement) {
node = node.parent.parent;
@@ -9742,7 +9805,7 @@ module ts {
}
let initializer = member.initializer;
if (initializer) {
autoValue = getConstantValueForEnumMemberInitializer(initializer, enumIsConst);
autoValue = getConstantValueForEnumMemberInitializer(initializer);
if (autoValue === undefined) {
if (enumIsConst) {
error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression);
@@ -9777,7 +9840,7 @@ module ts {
nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed;
}
function getConstantValueForEnumMemberInitializer(initializer: Expression, enumIsConst: boolean): number {
function getConstantValueForEnumMemberInitializer(initializer: Expression): number {
return evalConstant(initializer);
function evalConstant(e: Node): number {
@@ -9790,14 +9853,10 @@ module ts {
switch ((<PrefixUnaryExpression>e).operator) {
case SyntaxKind.PlusToken: return value;
case SyntaxKind.MinusToken: return -value;
case SyntaxKind.TildeToken: return enumIsConst ? ~value : undefined;
case SyntaxKind.TildeToken: return ~value;
}
return undefined;
case SyntaxKind.BinaryExpression:
if (!enumIsConst) {
return undefined;
}
let left = evalConstant((<BinaryExpression>e).left);
if (left === undefined) {
return undefined;
@@ -9823,14 +9882,10 @@ module ts {
case SyntaxKind.NumericLiteral:
return +(<LiteralExpression>e).text;
case SyntaxKind.ParenthesizedExpression:
return enumIsConst ? evalConstant((<ParenthesizedExpression>e).expression) : undefined;
return evalConstant((<ParenthesizedExpression>e).expression);
case SyntaxKind.Identifier:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.PropertyAccessExpression:
if (!enumIsConst) {
return undefined;
}
let member = initializer.parent;
let currentType = getTypeOfSymbol(getSymbolOfNode(member.parent));
let enumType: Type;
@@ -9843,19 +9898,37 @@ module ts {
propertyName = (<Identifier>e).text;
}
else {
let expression: Expression;
if (e.kind === SyntaxKind.ElementAccessExpression) {
if ((<ElementAccessExpression>e).argumentExpression === undefined ||
(<ElementAccessExpression>e).argumentExpression.kind !== SyntaxKind.StringLiteral) {
return undefined;
}
enumType = getTypeOfNode((<ElementAccessExpression>e).expression);
expression = (<ElementAccessExpression>e).expression;
propertyName = (<LiteralExpression>(<ElementAccessExpression>e).argumentExpression).text;
}
else {
enumType = getTypeOfNode((<PropertyAccessExpression>e).expression);
expression = (<PropertyAccessExpression>e).expression;
propertyName = (<PropertyAccessExpression>e).name.text;
}
if (enumType !== currentType) {
// expression part in ElementAccess\PropertyAccess should be either identifier or dottedName
var current = expression;
while (current) {
if (current.kind === SyntaxKind.Identifier) {
break;
}
else if (current.kind === SyntaxKind.PropertyAccessExpression) {
current = (<ElementAccessExpression>current).expression;
}
else {
return undefined;
}
}
enumType = checkExpression(expression);
// allow references to constant members of other enums
if (!(enumType.symbol && (enumType.symbol.flags & SymbolFlags.Enum))) {
return undefined;
}
}
@@ -9863,10 +9936,12 @@ module ts {
if (propertyName === undefined) {
return undefined;
}
let property = getPropertyOfObjectType(enumType, propertyName);
if (!property || !(property.flags & SymbolFlags.EnumMember)) {
return undefined;
}
let propertyDecl = property.valueDeclaration;
// self references are illegal
if (member === propertyDecl) {
@@ -9877,6 +9952,7 @@ module ts {
if (!isDefinedBefore(propertyDecl, member)) {
return undefined;
}
return <number>getNodeLinks(propertyDecl).enumMemberValue;
}
}
@@ -10093,6 +10169,12 @@ module ts {
}
}
}
else {
if (languageVersion >= ScriptTarget.ES6) {
// Import equals declaration is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_or_import_d_from_mod_instead);
}
}
}
}
@@ -10140,6 +10222,11 @@ module ts {
}
checkExternalModuleExports(container);
if (node.isExportEquals && languageVersion >= ScriptTarget.ES6) {
// export assignment is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_export_default_instead);
}
}
function getModuleStatements(node: Declaration): ModuleElement[] {
@@ -10182,7 +10269,7 @@ module ts {
if (!links.exportsChecked) {
let defaultSymbol = getExportAssignmentSymbol(moduleSymbol);
if (defaultSymbol) {
if (hasExportedMembers(moduleSymbol)) {
if (languageVersion < ScriptTarget.ES6 && hasExportedMembers(moduleSymbol)) {
let declaration = getDeclarationOfAliasSymbol(defaultSymbol) || defaultSymbol.valueDeclaration;
error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
}
@@ -11005,7 +11092,15 @@ module ts {
function getExportNameSubstitution(symbol: Symbol, location: Node): string {
if (isExternalModuleSymbol(symbol.parent)) {
return "exports." + unescapeIdentifier(symbol.name);
var symbolName = unescapeIdentifier(symbol.name);
// If this is es6 or higher, just use the name of the export
// no need to qualify it.
if (languageVersion >= ScriptTarget.ES6) {
return symbolName;
}
else {
return "exports." + symbolName;
}
}
let node = location;
let containerSymbol = getParentOfSymbol(symbol);
@@ -11033,7 +11128,7 @@ module ts {
return getExportNameSubstitution(exportSymbol, node.parent);
}
// Named imports from ES6 import declarations are rewritten
if (symbol.flags & SymbolFlags.Alias) {
if (symbol.flags & SymbolFlags.Alias && languageVersion < ScriptTarget.ES6) {
return getAliasNameSubstitution(symbol);
}
}
@@ -11069,7 +11164,6 @@ module ts {
return true;
}
}
return forEachChild(node, isReferencedAliasDeclaration);
}
function isImplementationOfOverload(node: FunctionLikeDeclaration) {
@@ -11109,10 +11203,9 @@ module ts {
let symbol = getNodeLinks(node).resolvedSymbol;
if (symbol && (symbol.flags & SymbolFlags.EnumMember)) {
let declaration = symbol.valueDeclaration;
let constantValue: number;
if (declaration.kind === SyntaxKind.EnumMember) {
return getEnumMemberValue(<EnumMember>declaration);
// inline property\index accesses only for const enums
if (isConstEnumDeclaration(symbol.valueDeclaration.parent)) {
return getEnumMemberValue(<EnumMember>symbol.valueDeclaration);
}
}
@@ -11134,6 +11227,11 @@ module ts {
getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags);
}
function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) {
var type = getTypeOfExpression(expr);
getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
}
function isUnknownIdentifier(location: Node, name: string): boolean {
Debug.assert(!nodeIsSynthesized(location), "isUnknownIdentifier called with a synthesized location");
return !resolveName(location, name, SymbolFlags.Value, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined) &&
@@ -11177,10 +11275,12 @@ module ts {
isImplementationOfOverload,
writeTypeOfDeclaration,
writeReturnTypeOfSignatureDeclaration,
writeTypeOfExpression,
isSymbolAccessible,
isEntityNameVisible,
getConstantValue,
isUnknownIdentifier,
collectLinkedAliases,
getBlockScopedVariableId,
};
}
@@ -12118,8 +12218,8 @@ module ts {
}
function checkGrammarTopLevelElementForRequiredDeclareModifier(node: Node): boolean {
// A declare modifier is required for any top level .d.ts declaration except export=, interfaces and imports:
// categories:
// A declare modifier is required for any top level .d.ts declaration except export=, export default,
// interfaces and imports categories:
//
// DeclarationElement:
// ExportAssignment
@@ -12133,7 +12233,8 @@ module ts {
node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.ExportDeclaration ||
node.kind === SyntaxKind.ExportAssignment ||
(node.flags & NodeFlags.Ambient)) {
(node.flags & NodeFlags.Ambient) ||
(node.flags & (NodeFlags.Export | NodeFlags.Default))) {
return false;
}
+4 -2
View File
@@ -122,8 +122,10 @@ module ts {
}
export function addRange<T>(to: T[], from: T[]): void {
for (let v of from) {
to.push(v);
if (to && from) {
for (let v of from) {
to.push(v);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -159,6 +159,9 @@ module ts {
Unterminated_Unicode_escape_sequence: { code: 1199, category: DiagnosticCategory.Error, key: "Unterminated Unicode escape sequence." },
Line_terminator_not_permitted_before_arrow: { code: 1200, category: DiagnosticCategory.Error, key: "Line terminator not permitted before arrow." },
A_type_annotation_on_an_export_statement_is_only_allowed_in_an_ambient_external_module_declaration: { code: 1201, category: DiagnosticCategory.Error, key: "A type annotation on an export statement is only allowed in an ambient external module declaration." },
Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_or_import_d_from_mod_instead: { code: 1202, category: DiagnosticCategory.Error, key: "Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"' or 'import d from \"mod\"' instead." },
Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_export_default_instead: { code: 1203, category: DiagnosticCategory.Error, key: "Export assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'export default' instead." },
Cannot_compile_external_modules_into_amd_or_commonjs_when_targeting_es6_or_higher: { code: 1204, category: DiagnosticCategory.Error, key: "Cannot compile external modules into amd or commonjs when targeting es6 or higher." },
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." },
@@ -341,7 +344,8 @@ module ts {
Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: DiagnosticCategory.Error, key: "Cannot redeclare identifier '{0}' in catch clause" },
Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: DiagnosticCategory.Error, key: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." },
Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: DiagnosticCategory.Error, key: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." },
Type_0_is_not_an_array_type_or_a_string_type: { code: 2461, category: DiagnosticCategory.Error, key: "Type '{0}' is not an array type or a string type." },
Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: DiagnosticCategory.Error, key: "Type '{0}' is not an array type or a string type." },
The_arguments_object_cannot_be_referenced_in_an_arrow_function_Consider_using_a_standard_function_expression: { code: 2496, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -411,6 +415,7 @@ module ts {
Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." },
Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using private name '{1}'." },
Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: DiagnosticCategory.Error, key: "Exported type alias '{0}' has or is using private name '{1}'." },
Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: DiagnosticCategory.Error, key: "Default export of the module has or is using private name '{0}'." },
Loop_contains_block_scoped_variable_0_referenced_by_a_function_in_the_loop_This_is_only_supported_in_ECMAScript_6_or_higher: { code: 4091, category: DiagnosticCategory.Error, key: "Loop contains block-scoped variable '{0}' referenced by a function in the loop. This is only supported in ECMAScript 6 or higher." },
The_current_host_does_not_support_the_0_option: { code: 5001, category: DiagnosticCategory.Error, key: "The current host does not support the '{0}' option." },
Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: DiagnosticCategory.Error, key: "Cannot find the common subdirectory path for the input files." },
@@ -503,6 +508,5 @@ module ts {
type_assertion_expressions_can_only_be_used_in_TypeScript: { code: 8016, category: DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in TypeScript." },
yield_expressions_are_not_currently_supported: { code: 9000, category: DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." },
Generators_are_not_currently_supported: { code: 9001, category: DiagnosticCategory.Error, key: "Generators are not currently supported." },
The_arguments_object_cannot_be_referenced_in_an_arrow_function_Consider_using_a_standard_function_expression: { code: 9002, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression." },
};
}
+21 -5
View File
@@ -627,6 +627,18 @@
"category": "Error",
"code": 1201
},
"Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"' or 'import d from \"mod\"' instead.": {
"category": "Error",
"code": 1202
},
"Export assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'export default' instead.": {
"category": "Error",
"code": 1203
},
"Cannot compile external modules into amd or commonjs when targeting es6 or higher.": {
"category": "Error",
"code": 1204
},
"Duplicate identifier '{0}'.": {
"category": "Error",
@@ -1358,7 +1370,11 @@
},
"Type '{0}' is not an array type or a string type.": {
"category": "Error",
"code": 2461
"code": 2495
},
"The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression.": {
"category": "Error",
"code": 2496
},
"Import declaration '{0}' is using private name '{1}'.": {
@@ -1637,6 +1653,10 @@
"category": "Error",
"code": 4081
},
"Default export of the module has or is using private name '{0}'.": {
"category": "Error",
"code": 4082
},
"Loop contains block-scoped variable '{0}' referenced by a function in the loop. This is only supported in ECMAScript 6 or higher.": {
"category": "Error",
"code": 4091
@@ -2006,9 +2026,5 @@
"Generators are not currently supported.": {
"category": "Error",
"code": 9001
},
"The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression.": {
"category": "Error",
"code": 9002
}
}
+424 -1707
View File
File diff suppressed because it is too large Load Diff
+32 -10
View File
@@ -10,7 +10,7 @@ module ts {
/** The version of the TypeScript compiler release */
export let version = "1.5.0.0";
export function createCompilerHost(options: CompilerOptions): CompilerHost {
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
let currentDirectory: string;
let existingDirectories: Map<boolean> = {};
@@ -38,7 +38,7 @@ module ts {
}
text = "";
}
return text !== undefined ? createSourceFile(fileName, text, languageVersion) : undefined;
return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
function directoryExists(directoryPath: string): boolean {
@@ -87,6 +87,11 @@ module ts {
export function getPreEmitDiagnostics(program: Program): Diagnostic[] {
let diagnostics = program.getSyntacticDiagnostics().concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics());
if (program.getCompilerOptions().declaration) {
diagnostics.concat(program.getDeclarationDiagnostics());
}
return sortAndDeduplicateDiagnostics(diagnostics);
}
@@ -178,11 +183,6 @@ module ts {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function getDeclarationDiagnostics(targetSourceFile: SourceFile): Diagnostic[] {
let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(targetSourceFile);
return ts.getDeclarationDiagnostics(getEmitHost(), resolver, targetSourceFile);
}
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback): EmitResult {
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out.
@@ -232,6 +232,10 @@ module ts {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile);
}
function getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile);
}
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
return sourceFile.parseDiagnostics;
}
@@ -247,6 +251,15 @@ module ts {
return bindDiagnostics.concat(checkDiagnostics).concat(programDiagnostics);
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
if (!isDeclarationFile(sourceFile)) {
let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile);
// Don't actually write any files since we're just getting diagnostics.
var writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
}
function getGlobalDiagnostics(): Diagnostic[] {
let typeChecker = getDiagnosticsProducingTypeChecker();
@@ -436,11 +449,20 @@ module ts {
return;
}
let languageVersion = options.target || ScriptTarget.ES3;
let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (firstExternalModuleSourceFile && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided));
if (!options.module && languageVersion < ScriptTarget.ES6) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided));
}
}
// Cannot specify module gen target when in es6 or above
if (options.module && languageVersion >= ScriptTarget.ES6) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_external_modules_into_amd_or_commonjs_when_targeting_es6_or_higher));
}
// there has to be common source directory if user specified --outdir || --sourcRoot
+43 -11
View File
@@ -318,13 +318,38 @@ module ts {
let hasOwnProperty = Object.prototype.hasOwnProperty;
export function isWhiteSpace(ch: number): boolean {
return ch === CharacterCodes.space || ch === CharacterCodes.tab || ch === CharacterCodes.verticalTab || ch === CharacterCodes.formFeed ||
ch === CharacterCodes.nonBreakingSpace || ch === CharacterCodes.ogham || ch >= CharacterCodes.enQuad && ch <= CharacterCodes.zeroWidthSpace ||
ch === CharacterCodes.narrowNoBreakSpace || ch === CharacterCodes.mathematicalSpace || ch === CharacterCodes.ideographicSpace || ch === CharacterCodes.byteOrderMark;
// Note: nextLine is in the Zs space, and should be considered to be a whitespace.
// It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
return ch === CharacterCodes.space ||
ch === CharacterCodes.tab ||
ch === CharacterCodes.verticalTab ||
ch === CharacterCodes.formFeed ||
ch === CharacterCodes.nonBreakingSpace ||
ch === CharacterCodes.nextLine ||
ch === CharacterCodes.ogham ||
ch >= CharacterCodes.enQuad && ch <= CharacterCodes.zeroWidthSpace ||
ch === CharacterCodes.narrowNoBreakSpace ||
ch === CharacterCodes.mathematicalSpace ||
ch === CharacterCodes.ideographicSpace ||
ch === CharacterCodes.byteOrderMark;
}
export function isLineBreak(ch: number): boolean {
return ch === CharacterCodes.lineFeed || ch === CharacterCodes.carriageReturn || ch === CharacterCodes.lineSeparator || ch === CharacterCodes.paragraphSeparator || ch === CharacterCodes.nextLine;
// ES5 7.3:
// The ECMAScript line terminator characters are listed in Table 3.
// Table 3 — Line Terminator Characters
// Code Unit Value Name Formal Name
// \u000A Line Feed <LF>
// \u000D Carriage Return <CR>
// \u2028 Line separator <LS>
// \u2029 Paragraph separator <PS>
// Only the characters in Table 3 are treated as line terminators. Other new line or line
// breaking characters are treated as white space but not as line terminators.
return ch === CharacterCodes.lineFeed ||
ch === CharacterCodes.carriageReturn ||
ch === CharacterCodes.lineSeparator ||
ch === CharacterCodes.paragraphSeparator;
}
function isDigit(ch: number): boolean {
@@ -455,11 +480,13 @@ module ts {
return pos;
}
// Extract comments from the given source text starting at the given position. If trailing is false, whitespace is skipped until
// the first line break and comments between that location and the next token are returned. If trailing is true, comments occurring
// between the given position and the next line break are returned. The return value is an array containing a TextRange for each
// comment. Single-line comment ranges include the beginning '//' characters but not the ending line break. Multi-line comment
// ranges include the beginning '/* and ending '*/' characters. The return value is undefined if no comments were found.
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
// position and the next line break are returned.The return value is an array containing a
// TextRange for each comment. Single-line comment ranges include the beginning '//' characters
// but not the ending line break. Multi - line comment ranges include the beginning '/* and
// ending '*/' characters.The return value is undefined if no comments were found.
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
let collecting = trailing || pos === 0;
@@ -467,7 +494,9 @@ module ts {
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) pos++;
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
case CharacterCodes.lineFeed:
pos++;
if (trailing) {
@@ -509,7 +538,10 @@ module ts {
}
}
if (collecting) {
if (!result) result = [];
if (!result) {
result = [];
}
result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine });
}
continue;
+5 -1
View File
@@ -1189,9 +1189,11 @@ module ts {
CannotBeNamed
}
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
export interface SymbolVisibilityResult {
accessibility: SymbolAccessibility;
aliasesToMakeVisible?: ImportEqualsDeclaration[]; // aliases that need to have this symbol visible
aliasesToMakeVisible?: AnyImportSyntax[]; // aliases that need to have this symbol visible
errorSymbolName?: string; // Optional symbol name that results in error
errorNode?: Node; // optional node that results in error
}
@@ -1208,9 +1210,11 @@ module ts {
isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean;
getNodeCheckFlags(node: Node): NodeCheckFlags;
isDeclarationVisible(node: Declaration): boolean;
collectLinkedAliases(node: Identifier): Node[];
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
+320 -7
View File
@@ -361,16 +361,16 @@ module ts {
return node.kind === SyntaxKind.ExpressionStatement && (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
}
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode?: SourceFile) {
sourceFileOfNode = sourceFileOfNode || getSourceFileOfNode(node);
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile) {
// If parameter/type parameter, the prev token trailing comments are part of this node too
if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
// e.g. (/** blah */ a, /** blah */ b);
return concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
// e.g.: (
// /** blah */ a,
// /** blah */ b);
// e.g.: (
// /** blah */ a,
// /** blah */ b);
return concatenate(
getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
getLeadingCommentRanges(sourceFileOfNode.text, node.pos));
}
else {
@@ -1364,4 +1364,317 @@ module ts {
s.replace(nonAsciiCharacters, c => get16BitUnicodeEscapeSequence(c.charCodeAt(0))) :
s;
}
export interface EmitTextWriter {
write(s: string): void;
writeTextOfNode(sourceFile: SourceFile, node: Node): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
getText(): string;
rawWrite(s: string): void;
writeLiteral(s: string): void;
getTextPos(): number;
getLine(): number;
getColumn(): number;
getIndent(): number;
}
let indentStrings: string[] = ["", " "];
export function getIndentString(level: number) {
if (indentStrings[level] === undefined) {
indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
}
return indentStrings[level];
}
export function getIndentSize() {
return indentStrings[1].length;
}
export function createTextWriter(newLine: String): EmitTextWriter {
let output = "";
let indent = 0;
let lineStart = true;
let lineCount = 0;
let linePos = 0;
function write(s: string) {
if (s && s.length) {
if (lineStart) {
output += getIndentString(indent);
lineStart = false;
}
output += s;
}
}
function rawWrite(s: string) {
if (s !== undefined) {
if (lineStart) {
lineStart = false;
}
output += s;
}
}
function writeLiteral(s: string) {
if (s && s.length) {
write(s);
let lineStartsOfS = computeLineStarts(s);
if (lineStartsOfS.length > 1) {
lineCount = lineCount + lineStartsOfS.length - 1;
linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1];
}
}
}
function writeLine() {
if (!lineStart) {
output += newLine;
lineCount++;
linePos = output.length;
lineStart = true;
}
}
function writeTextOfNode(sourceFile: SourceFile, node: Node) {
write(getSourceTextOfNodeFromSourceFile(sourceFile, node));
}
return {
write,
rawWrite,
writeTextOfNode,
writeLiteral,
writeLine,
increaseIndent: () => indent++,
decreaseIndent: () => indent--,
getIndent: () => indent,
getTextPos: () => output.length,
getLine: () => lineCount + 1,
getColumn: () => lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1,
getText: () => output,
};
}
export function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string) {
let compilerOptions = host.getCompilerOptions();
let emitOutputFilePathWithoutExtension: string;
if (compilerOptions.outDir) {
emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir));
}
else {
emitOutputFilePathWithoutExtension = removeFileExtension(sourceFile.fileName);
}
return emitOutputFilePathWithoutExtension + extension;
}
export function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string) {
let sourceFilePath = getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory());
sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), "");
return combinePaths(newDirPath, sourceFilePath);
}
export function writeFile(host: EmitHost, diagnostics: Diagnostic[], fileName: string, data: string, writeByteOrderMark: boolean) {
host.writeFile(fileName, data, writeByteOrderMark, hostErrorMessage => {
diagnostics.push(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
});
}
export function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number) {
return getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
export function getFirstConstructorWithBody(node: ClassDeclaration): ConstructorDeclaration {
return forEach(node.members, member => {
if (member.kind === SyntaxKind.Constructor && nodeIsPresent((<ConstructorDeclaration>member).body)) {
return <ConstructorDeclaration>member;
}
});
}
export function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
if (!isDeclarationFile(sourceFile)) {
if ((isExternalModule(sourceFile) || !compilerOptions.out) && !fileExtensionIs(sourceFile.fileName, ".js")) {
return true;
}
return false;
}
return false;
}
export function getAllAccessorDeclarations(declarations: NodeArray<Declaration>, accessor: AccessorDeclaration) {
let firstAccessor: AccessorDeclaration;
let getAccessor: AccessorDeclaration;
let setAccessor: AccessorDeclaration;
if (hasDynamicName(accessor)) {
firstAccessor = accessor;
if (accessor.kind === SyntaxKind.GetAccessor) {
getAccessor = accessor;
}
else if (accessor.kind === SyntaxKind.SetAccessor) {
setAccessor = accessor;
}
else {
Debug.fail("Accessor has wrong kind");
}
}
else {
forEach(declarations, (member: Declaration) => {
if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor)
&& (member.flags & NodeFlags.Static) === (accessor.flags & NodeFlags.Static)) {
let memberName = getPropertyNameForPropertyNameNode(member.name);
let accessorName = getPropertyNameForPropertyNameNode(accessor.name);
if (memberName === accessorName) {
if (!firstAccessor) {
firstAccessor = <AccessorDeclaration>member;
}
if (member.kind === SyntaxKind.GetAccessor && !getAccessor) {
getAccessor = <AccessorDeclaration>member;
}
if (member.kind === SyntaxKind.SetAccessor && !setAccessor) {
setAccessor = <AccessorDeclaration>member;
}
}
}
});
}
return {
firstAccessor,
getAccessor,
setAccessor
};
}
export function emitNewLineBeforeLeadingComments(currentSourceFile: SourceFile, writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]) {
// If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) {
writer.writeLine();
}
}
export function emitComments(currentSourceFile: SourceFile, writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string,
writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void) {
let emitLeadingSpace = !trailingSeparator;
forEach(comments, comment => {
if (emitLeadingSpace) {
writer.write(" ");
emitLeadingSpace = false;
}
writeComment(currentSourceFile, writer, comment, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
else if (trailingSeparator) {
writer.write(" ");
}
else {
// Emit leading space to separate comment during next comment emit
emitLeadingSpace = true;
}
});
}
export function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
let firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
let lineCount = getLineStarts(currentSourceFile).length;
let firstCommentLineIndent: number;
for (let pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
let nextLineStart = (currentLine + 1) === lineCount
? currentSourceFile.text.length + 1
: getStartPositionOfLine(currentLine + 1, currentSourceFile);
if (pos !== comment.pos) {
// If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
}
// These are number of spaces writer is going to write at current indent
let currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
// Number of spaces we want to be writing
// eg: Assume writer indent
// module m {
// /* starts at character 9 this is line 1
// * starts at character pos 4 line --1 = 8 - 8 + 3
// More left indented comment */ --2 = 8 - 8 + 2
// class c { }
// }
// module m {
// /* this is line 1 -- Assume current writer indent 8
// * line --3 = 8 - 4 + 5
// More right indented comment */ --4 = 8 - 4 + 11
// class c { }
// }
let spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
if (spacesToEmit > 0) {
let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
let indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
// Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
writer.rawWrite(indentSizeSpaceString);
// Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
while (numberOfSingleSpacesToEmit) {
writer.rawWrite(" ");
numberOfSingleSpacesToEmit--;
}
}
else {
// No spaces to emit write empty string
writer.rawWrite("");
}
}
// Write the comment line text
writeTrimmedCurrentLine(pos, nextLineStart);
pos = nextLineStart;
}
}
else {
// Single line comment of style //....
writer.write(currentSourceFile.text.substring(comment.pos, comment.end));
}
function writeTrimmedCurrentLine(pos: number, nextLineStart: number) {
let end = Math.min(comment.end, nextLineStart - 1);
let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, '');
if (currentLineText) {
// trimmed forward and ending spaces text
writer.write(currentLineText);
if (end !== comment.end) {
writer.writeLine();
}
}
else {
// Empty string - make sure we write empty line
writer.writeLiteral(newLine);
}
}
function calculateIndent(pos: number, end: number) {
let currentLineIndent = 0;
for (; pos < end && isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
if (currentSourceFile.text.charCodeAt(pos) === CharacterCodes.tab) {
// Tabs = TabSize = indent size and go to next tabStop
currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
}
else {
// Single space
currentLineIndent++;
}
}
return currentLineIndent;
}
}
}
+8 -3
View File
@@ -625,7 +625,7 @@ module FourSlash {
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
var members = this.getMemberListAtCaret();
if (members.entries.filter(e => e.name === symbol).length !== 0) {
if (members && members.entries.filter(e => e.name === symbol).length !== 0) {
this.raiseError('Member list did contain ' + symbol);
}
}
@@ -696,7 +696,12 @@ module FourSlash {
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
var completions = this.getCompletionListAtCaret();
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
if (completions) {
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
}
else {
this.raiseError(`No completions at position '${ this.currentCaretPosition }' when looking for '${ symbol }'.`);
}
}
public verifyCompletionListDoesNotContain(symbol: string) {
@@ -704,7 +709,7 @@ module FourSlash {
this.scenarioActions.push('<VerifyCompletionDoesNotContainItem ItemName="' + escapeXmlAttributeValue(symbol) + '" />');
var completions = this.getCompletionListAtCaret();
if (completions && completions.entries && completions.entries.filter(e => e.name === symbol).length !== 0) {
if (completions && completions.entries.filter(e => e.name === symbol).length !== 0) {
this.raiseError('Completion list did contain ' + symbol);
}
}
+57 -57
View File
@@ -46,21 +46,21 @@ module ts.server {
return lineMap;
}
private lineColToPosition(fileName: string, lineCol: protocol.Location): number {
return ts.computePositionOfLineAndCharacter(this.getLineMap(fileName), lineCol.line - 1, lineCol.col - 1);
private lineOffsetToPosition(fileName: string, lineOffset: protocol.Location): number {
return ts.computePositionOfLineAndCharacter(this.getLineMap(fileName), lineOffset.line - 1, lineOffset.offset - 1);
}
private positionToOneBasedLineCol(fileName: string, position: number): protocol.Location {
var lineCol = ts.computeLineAndCharacterOfPosition(this.getLineMap(fileName), position);
private positionToOneBasedLineOffset(fileName: string, position: number): protocol.Location {
var lineOffset = ts.computeLineAndCharacterOfPosition(this.getLineMap(fileName), position);
return {
line: lineCol.line + 1,
col: lineCol.character + 1
line: lineOffset.line + 1,
offset: lineOffset.character + 1
};
}
private convertCodeEditsToTextChange(fileName: string, codeEdit: protocol.CodeEdit): ts.TextChange {
var start = this.lineColToPosition(fileName, codeEdit.start);
var end = this.lineColToPosition(fileName, codeEdit.end);
var start = this.lineOffsetToPosition(fileName, codeEdit.start);
var end = this.lineOffsetToPosition(fileName, codeEdit.end);
return {
span: ts.createTextSpanFromBounds(start, end),
@@ -134,15 +134,15 @@ module ts.server {
// clear the line map after an edit
this.lineMaps[fileName] = undefined;
var lineCol = this.positionToOneBasedLineCol(fileName, start);
var endLineCol = this.positionToOneBasedLineCol(fileName, end);
var lineOffset = this.positionToOneBasedLineOffset(fileName, start);
var endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
var args: protocol.ChangeRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
endLine: endLineCol.line,
endCol: endLineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
endLine: endLineOffset.line,
endOffset: endLineOffset.offset,
insertString: newText
};
@@ -150,18 +150,18 @@ module ts.server {
}
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col
line: lineOffset.line,
offset: lineOffset.offset
};
var request = this.processRequest<protocol.QuickInfoRequest>(CommandNames.Quickinfo, args);
var response = this.processResponse<protocol.QuickInfoResponse>(request);
var start = this.lineColToPosition(fileName, response.body.start);
var end = this.lineColToPosition(fileName, response.body.end);
var start = this.lineOffsetToPosition(fileName, response.body.start);
var end = this.lineOffsetToPosition(fileName, response.body.end);
return {
kind: response.body.kind,
@@ -173,11 +173,11 @@ module ts.server {
}
getCompletionsAtPosition(fileName: string, position: number): CompletionInfo {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.CompletionsRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
prefix: undefined
};
@@ -194,11 +194,11 @@ module ts.server {
}
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.CompletionDetailsRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
entryNames: [entryName]
};
@@ -219,8 +219,8 @@ module ts.server {
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineColToPosition(fileName, entry.start);
var end = this.lineColToPosition(fileName, entry.end);
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
return {
name: entry.name,
@@ -237,14 +237,14 @@ module ts.server {
}
getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): ts.TextChange[] {
var startLineCol = this.positionToOneBasedLineCol(fileName, start);
var endLineCol = this.positionToOneBasedLineCol(fileName, end);
var startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
var endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
var args: protocol.FormatRequestArgs = {
file: fileName,
line: startLineCol.line,
col: startLineCol.col,
endLine: endLineCol.line,
endCol: endLineCol.col,
line: startLineOffset.line,
offset: startLineOffset.offset,
endLine: endLineOffset.line,
endOffset: endLineOffset.offset,
};
// TODO: handle FormatCodeOptions
@@ -259,11 +259,11 @@ module ts.server {
}
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): ts.TextChange[] {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FormatOnKeyRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
key: key
};
@@ -275,11 +275,11 @@ module ts.server {
}
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.DefinitionRequest>(CommandNames.Definition, args);
@@ -287,8 +287,8 @@ module ts.server {
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineColToPosition(fileName, entry.start);
var end = this.lineColToPosition(fileName, entry.end);
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerName: "",
@@ -301,11 +301,11 @@ module ts.server {
}
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.ReferencesRequest>(CommandNames.References, args);
@@ -313,8 +313,8 @@ module ts.server {
return response.body.refs.map(entry => {
var fileName = entry.file;
var start = this.lineColToPosition(fileName, entry.start);
var end = this.lineColToPosition(fileName, entry.end);
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
return {
fileName: fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
@@ -340,11 +340,11 @@ module ts.server {
}
getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.RenameRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
findInStrings,
findInComments
};
@@ -355,8 +355,8 @@ module ts.server {
response.body.locs.map((entry: protocol.SpanGroup) => {
var fileName = entry.file;
entry.locs.map((loc: protocol.TextSpan) => {
var start = this.lineColToPosition(fileName, loc.start);
var end = this.lineColToPosition(fileName, loc.end);
var start = this.lineOffsetToPosition(fileName, loc.start);
var end = this.lineOffsetToPosition(fileName, loc.end);
locations.push({
textSpan: ts.createTextSpanFromBounds(start, end),
fileName: fileName
@@ -400,7 +400,7 @@ module ts.server {
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers || "",
spans: item.spans.map(span=> createTextSpanFromBounds(this.lineColToPosition(fileName, span.start), this.lineColToPosition(fileName, span.end))),
spans: item.spans.map(span=> createTextSpanFromBounds(this.lineOffsetToPosition(fileName, span.start), this.lineOffsetToPosition(fileName, span.end))),
childItems: this.decodeNavigationBarItems(item.childItems, fileName),
indent: 0,
bolded: false,
@@ -444,19 +444,19 @@ module ts.server {
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineCol = this.positionToOneBasedLineCol(fileName, position);
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineCol.line,
col: lineCol.col,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.BraceRequest>(CommandNames.Brace, args);
var response = this.processResponse<protocol.BraceResponse>(request);
return response.body.map(entry => {
var start = this.lineColToPosition(fileName, entry.start);
var end = this.lineColToPosition(fileName, entry.end);
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
return {
start: start,
length: end - start,
+74 -30
View File
@@ -19,15 +19,23 @@ module ts.server {
class ScriptInfo {
svc: ScriptVersionCache;
children: ScriptInfo[] = []; // files referenced by this file
defaultProject: Project; // project to use by default for file
fileWatcher: FileWatcher;
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) {
this.svc = ScriptVersionCache.fromString(content);
}
setFormatOptions(tabSize?: number, indentSize?: number) {
if (tabSize) {
this.formatCodeOptions.TabSize = tabSize;
}
if (indentSize) {
this.formatCodeOptions.IndentSize = indentSize;
}
}
close() {
this.isOpen = false;
}
@@ -200,33 +208,33 @@ module ts.server {
}
else {
var nextLineInfo = index.lineNumberToInfo(line + 2);
len = nextLineInfo.col - lineInfo.col;
len = nextLineInfo.offset - lineInfo.offset;
}
return ts.createTextSpan(lineInfo.col, len);
return ts.createTextSpan(lineInfo.offset, len);
}
/**
* @param line 1 based index
* @param col 1 based index
* @param offset 1 based index
*/
lineColToPosition(filename: string, line: number, col: number): number {
lineOffsetToPosition(filename: string, line: number, offset: number): number {
var script: ScriptInfo = this.filenameToScript[filename];
var index = script.snap().index;
var lineInfo = index.lineNumberToInfo(line);
// TODO: assert this column is actually on the line
return (lineInfo.col + col - 1);
// TODO: assert this offset is actually on the line
return (lineInfo.offset + offset - 1);
}
/**
* @param line 1-based index
* @param col 1-based index
* @param offset 1-based index
*/
positionToLineCol(filename: string, position: number): ILineInfo {
positionToLineOffset(filename: string, position: number): ILineInfo {
var script: ScriptInfo = this.filenameToScript[filename];
var index = script.snap().index;
var lineCol = index.charOffsetToLineNumberAndPos(position);
return { line: lineCol.line, col: lineCol.col + 1 };
var lineOffset = index.charOffsetToLineNumberAndPos(position);
return { line: lineOffset.line, offset: lineOffset.offset + 1 };
}
}
@@ -259,7 +267,6 @@ module ts.server {
interface ProjectOptions {
// these fields can be present in the project file
files?: string[];
formatCodeOptions?: ts.FormatCodeOptions;
compilerOptions?: ts.CompilerOptions;
}
@@ -338,7 +345,6 @@ module ts.server {
if (projectOptions.compilerOptions) {
this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
}
// TODO: format code options
}
}
@@ -362,6 +368,11 @@ module ts.server {
(eventName: string, project: Project, fileName: string): void;
}
interface HostConfiguration {
formatCodeOptions: ts.FormatCodeOptions;
hostInfo: string;
}
export class ProjectService {
filenameToScriptInfo: ts.Map<ScriptInfo> = {};
// open, non-configured files in two lists
@@ -369,9 +380,28 @@ module ts.server {
openFilesReferenced: ScriptInfo[] = [];
// projects covering open files
inferredProjects: Project[] = [];
hostConfiguration: HostConfiguration;
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
this.addDefaultHostConfiguration();
}
addDefaultHostConfiguration() {
this.hostConfiguration = {
formatCodeOptions: ts.clone(CompilerService.defaultFormatCodeOptions),
hostInfo: "Unknown host"
}
}
getFormatCodeOptions(file?: string) {
if (file) {
var info = this.filenameToScriptInfo[file];
if (info) {
return info.formatCodeOptions;
}
}
return this.hostConfiguration.formatCodeOptions;
}
watchedFileChanged(fileName: string) {
@@ -395,6 +425,22 @@ module ts.server {
this.psLogger.msg(msg, type);
}
setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments) {
if (args.file) {
var info = this.filenameToScriptInfo[args.file];
if (info) {
info.setFormatOptions(args.tabSize, args.indentSize);
this.log("Host configuration update for file " + args.file + " tab size " + args.tabSize);
}
}
else {
this.hostConfiguration.formatCodeOptions.TabSize = args.tabSize;
this.hostConfiguration.formatCodeOptions.IndentSize = args.indentSize;
this.hostConfiguration.hostInfo = args.hostInfo;
this.log("Host information " + args.hostInfo, "Info");
}
}
closeLog() {
this.psLogger.close();
}
@@ -595,7 +641,7 @@ module ts.server {
/**
* @param filename is absolute pathname
*/
openFile(fileName: string, openedByClient = false) {
openFile(fileName: string, openedByClient: boolean) {
fileName = ts.normalizePath(fileName);
var info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
@@ -609,6 +655,7 @@ module ts.server {
}
}
if (content !== undefined) {
var indentSize: number;
info = new ScriptInfo(this.host, fileName, content, openedByClient);
this.filenameToScriptInfo[fileName] = info;
if (!info.isOpen) {
@@ -731,7 +778,8 @@ module ts.server {
var normRootFilename = ts.normalizePath(rootFilename);
normRootFilename = getAbsolutePath(normRootFilename, dirPath);
if (this.host.fileExists(normRootFilename)) {
var info = this.openFile(normRootFilename);
// TODO: pass true for file exiplicitly opened
var info = this.openFile(normRootFilename, false);
proj.addRoot(info);
}
else {
@@ -742,9 +790,6 @@ module ts.server {
files: parsedCommandLine.fileNames,
compilerOptions: parsedCommandLine.options
};
if (rawConfig.formatCodeOptions) {
projectOptions.formatCodeOptions = rawConfig.formatCodeOptions;
}
proj.setProjectOptions(projectOptions);
return { success: true, project: proj };
}
@@ -768,7 +813,6 @@ module ts.server {
classifier: ts.Classifier;
settings = ts.getDefaultCompilerOptions();
documentRegistry = ts.createDocumentRegistry();
formatCodeOptions: ts.FormatCodeOptions = CompilerService.defaultFormatCodeOptions;
constructor(public project: Project) {
this.host = new LSHost(project.projectService.host, project);
@@ -815,7 +859,7 @@ module ts.server {
export interface ILineInfo {
line: number;
col: number;
offset: number;
text?: string;
leaf?: LineLeaf;
}
@@ -1208,7 +1252,7 @@ module ts.server {
getLineMapper() {
return ((line: number) => {
return this.index.lineNumberToInfo(line).col;
return this.index.lineNumberToInfo(line).offset;
});
}
@@ -1245,7 +1289,7 @@ module ts.server {
else {
return {
line: lineNumber,
col: this.root.charCount()
offset: this.root.charCount()
}
}
}
@@ -1331,7 +1375,7 @@ module ts.server {
// check whether last characters deleted are line break
var e = pos + deleteLength;
var lineInfo = this.charOffsetToLineNumberAndPos(e);
if ((lineInfo && (lineInfo.col == 0))) {
if ((lineInfo && (lineInfo.offset == 0))) {
// move range end just past line that will merge with previous line
deleteLength += lineInfo.text.length;
// store text by appending to end of insertedText
@@ -1507,14 +1551,14 @@ module ts.server {
if (!childInfo.child) {
return {
line: lineNumber,
col: charOffset,
offset: charOffset,
}
}
else if (childInfo.childIndex < this.children.length) {
if (childInfo.child.isLeaf()) {
return {
line: childInfo.lineNumber,
col: childInfo.charOffset,
offset: childInfo.charOffset,
text: (<LineLeaf>(childInfo.child)).text,
leaf: (<LineLeaf>(childInfo.child))
};
@@ -1526,7 +1570,7 @@ module ts.server {
}
else {
var lineInfo = this.lineNumberToInfo(this.lineCount(), 0);
return { line: this.lineCount(), col: lineInfo.leaf.charCount() };
return { line: this.lineCount(), offset: lineInfo.leaf.charCount() };
}
}
@@ -1535,13 +1579,13 @@ module ts.server {
if (!childInfo.child) {
return {
line: lineNumber,
col: charOffset
offset: charOffset
}
}
}
else if (childInfo.child.isLeaf()) {
return {
line: lineNumber,
col: childInfo.charOffset,
offset: childInfo.charOffset,
text: (<LineLeaf>(childInfo.child)).text,
leaf: (<LineLeaf>(childInfo.child))
}
+57 -12
View File
@@ -96,7 +96,7 @@ declare module ts.server.protocol {
/**
* Instances of this interface specify a location in a source file:
* (file, line, col), where line and column are 1-based.
* (file, line, character offset), where line and character offset are 1-based.
*/
export interface FileLocationRequestArgs extends FileRequestArgs {
/**
@@ -105,9 +105,9 @@ declare module ts.server.protocol {
line: number;
/**
* The column for the request (1-based).
* The character offset (on the line) for the request (1-based).
*/
col: number;
offset: number;
}
/**
@@ -126,11 +126,11 @@ declare module ts.server.protocol {
}
/**
* Location in source code expressed as (one-based) line and column.
* Location in source code expressed as (one-based) line and character offset.
*/
export interface Location {
line: number;
col: number;
offset: number;
}
/**
@@ -202,9 +202,9 @@ declare module ts.server.protocol {
symbolName: string;
/**
* The start column of the symbol (on the line provided by the references request).
* The start character offset of the symbol (on the line provided by the references request).
*/
symbolStartCol: number;
symbolStartOffset: number;
/**
* The full display name of the symbol.
@@ -299,6 +299,50 @@ declare module ts.server.protocol {
body?: RenameResponseBody;
}
/**
* Information found in a configure request.
*/
export interface ConfigureRequestArguments {
/** Number of spaces for each tab */
tabSize: number;
/** Number of spaces to indent during formatting */
indentSize: number;
/**
* Information about the host, for example 'Emacs 24.4' or
* 'Sublime Text version 3075'
*/
hostInfo: string;
/**
* If present, tab settings apply only to this file.
*/
file?: string;
}
/**
* Configure request; value of command field is "configure". Specifies
* host information, such as host type, tab size, and indent size.
*/
export interface ConfigureRequest extends Request {
arguments: ConfigureRequestArguments;
}
/**
* Response to "configure" request. This is just an acknowledgement, so
* no body field is required.
*/
export interface ConfigureResponse extends Response {
}
/**
* Information found in an "open" request.
*/
export interface OpenRequestArgs extends FileRequestArgs {
/** Initial tab size of file. */
tabSize?: number;
/** Number of spaces to indent during formatting */
indentSize?: number;
}
/**
* Open request; value of command field is "open". Notify the
* server that the client has file open. The server will not
@@ -307,7 +351,8 @@ declare module ts.server.protocol {
* reload messages) when the file changes. Server does not currently
* send a response to an open request.
*/
export interface OpenRequest extends FileRequest {
export interface OpenRequest extends Request {
arguments: OpenRequestArgs;
}
/**
@@ -381,9 +426,9 @@ declare module ts.server.protocol {
endLine: number;
/**
* Last column of range for which to format text in file.
* Character offset on last line of range for which to format text in file.
*/
endCol: number;
endOffset: number;
}
/**
@@ -762,7 +807,7 @@ declare module ts.server.protocol {
*/
export interface ChangeRequestArgs extends FormatRequestArgs {
/**
* Optional string to insert at location (file, line, col).
* Optional string to insert at location (file, line, offset).
*/
insertString?: string;
}
@@ -786,7 +831,7 @@ declare module ts.server.protocol {
/**
* Brace matching request; value of command field is "brace".
* Return response giving the file locations of matching braces
* found in file at location line, col.
* found in file at location line, offset.
*/
export interface BraceRequest extends FileLocationRequest {
}
+83 -68
View File
@@ -5,13 +5,13 @@
/// <reference path="editorServices.ts" />
module ts.server {
var spaceCache = [" ", " ", " ", " "];
var spaceCache:string[] = [];
interface StackTraceError extends Error {
stack?: string;
}
function generateSpaces(n: number): string {
export function generateSpaces(n: number): string {
if (!spaceCache[n]) {
var strBuilder = "";
for (var i = 0; i < n; i++) {
@@ -44,7 +44,7 @@ module ts.server {
else if (a.file == b.file) {
var n = compareNumber(a.start.line, b.start.line);
if (n == 0) {
return compareNumber(a.start.col, b.start.col);
return compareNumber(a.start.offset, b.start.offset);
}
else return n;
}
@@ -55,8 +55,8 @@ module ts.server {
function formatDiag(fileName: string, project: Project, diag: ts.Diagnostic) {
return {
start: project.compilerService.host.positionToLineCol(fileName, diag.start),
end: project.compilerService.host.positionToLineCol(fileName, diag.start + diag.length),
start: project.compilerService.host.positionToLineOffset(fileName, diag.start),
end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length),
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n")
};
}
@@ -80,6 +80,7 @@ module ts.server {
export var Close = "close";
export var Completions = "completions";
export var CompletionDetails = "completionEntryDetails";
export var Configure = "configure";
export var Definition = "definition";
export var Format = "format";
export var Formatonkey = "formatonkey";
@@ -259,7 +260,7 @@ module ts.server {
}
}
getDefinition(line: number, col: number, fileName: string): protocol.FileSpan[] {
getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -267,7 +268,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var definitions = compilerService.languageService.getDefinitionAtPosition(file, position);
if (!definitions) {
@@ -276,12 +277,12 @@ module ts.server {
return definitions.map(def => ({
file: def.fileName,
start: compilerService.host.positionToLineCol(def.fileName, def.textSpan.start),
end: compilerService.host.positionToLineCol(def.fileName, ts.textSpanEnd(def.textSpan))
start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start),
end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan))
}));
}
getRenameLocations(line: number, col: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody {
getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -289,7 +290,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var renameInfo = compilerService.languageService.getRenameInfo(file, position);
if (!renameInfo) {
return undefined;
@@ -309,8 +310,8 @@ module ts.server {
var bakedRenameLocs = renameLocations.map(location => (<protocol.FileSpan>{
file: location.fileName,
start: compilerService.host.positionToLineCol(location.fileName, location.textSpan.start),
end: compilerService.host.positionToLineCol(location.fileName, ts.textSpanEnd(location.textSpan)),
start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start),
end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)),
})).sort((a, b) => {
if (a.file < b.file) {
return -1;
@@ -327,7 +328,7 @@ module ts.server {
return -1;
}
else {
return b.start.col - a.start.col;
return b.start.offset - a.start.offset;
}
}
}).reduce<protocol.SpanGroup[]>((accum: protocol.SpanGroup[], cur: protocol.FileSpan) => {
@@ -349,7 +350,7 @@ module ts.server {
return { info: renameInfo, locs: bakedRenameLocs };
}
getReferences(line: number, col: number, fileName: string): protocol.ReferencesResponseBody {
getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody {
// TODO: get all projects for this file; report refs for all projects deleting duplicates
// can avoid duplicates by eliminating same ref file from subsequent projects
var file = ts.normalizePath(fileName);
@@ -359,7 +360,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var references = compilerService.languageService.getReferencesAtPosition(file, position);
if (!references) {
@@ -373,10 +374,10 @@ module ts.server {
var displayString = ts.displayPartsToString(nameInfo.displayParts);
var nameSpan = nameInfo.textSpan;
var nameColStart = compilerService.host.positionToLineCol(file, nameSpan.start).col;
var nameColStart = compilerService.host.positionToLineOffset(file, nameSpan.start).offset;
var nameText = compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan));
var bakedRefs: protocol.ReferencesResponseItem[] = references.map((ref) => {
var start = compilerService.host.positionToLineCol(ref.fileName, ref.textSpan.start);
var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start);
var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1);
var snap = compilerService.host.getScriptSnapshot(ref.fileName);
var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
@@ -384,24 +385,27 @@ module ts.server {
file: ref.fileName,
start: start,
lineText: lineText,
end: compilerService.host.positionToLineCol(ref.fileName, ts.textSpanEnd(ref.textSpan)),
end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)),
isWriteAccess: ref.isWriteAccess
};
}).sort(compareFileStart);
return {
refs: bakedRefs,
symbolName: nameText,
symbolStartCol: nameColStart,
symbolStartOffset: nameColStart,
symbolDisplayString: displayString
};
}
openClientFile(fileName: string) {
openClientFile(fileName: string, tabSize?: number, indentSize?: number) {
var file = ts.normalizePath(fileName);
this.projectService.openClientFile(file);
var info = this.projectService.openClientFile(file);
if (info) {
info.setFormatOptions(tabSize, indentSize);
}
}
getQuickInfo(line: number, col: number, fileName: string): protocol.QuickInfoResponseBody {
getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -409,7 +413,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position);
if (!quickInfo) {
return undefined;
@@ -420,14 +424,14 @@ module ts.server {
return {
kind: quickInfo.kind,
kindModifiers: quickInfo.kindModifiers,
start: compilerService.host.positionToLineCol(file, quickInfo.textSpan.start),
end: compilerService.host.positionToLineCol(file, ts.textSpanEnd(quickInfo.textSpan)),
start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start),
end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)),
displayString: displayString,
documentation: docString,
};
}
getFormattingEditsForRange(line: number, col: number, endLine: number, endCol: number, fileName: string): protocol.CodeEdit[] {
getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
@@ -435,25 +439,26 @@ module ts.server {
}
var compilerService = project.compilerService;
var startPosition = compilerService.host.lineColToPosition(file, line, col);
var endPosition = compilerService.host.lineColToPosition(file, endLine, endCol);
var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset);
var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset);
// TODO: avoid duplicate code (with formatonkey)
var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, compilerService.formatCodeOptions);
var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition,
this.projectService.getFormatCodeOptions(file));
if (!edits) {
return undefined;
}
return edits.map((edit) => {
return {
start: compilerService.host.positionToLineCol(file, edit.span.start),
end: compilerService.host.positionToLineCol(file, ts.textSpanEnd(edit.span)),
start: compilerService.host.positionToLineOffset(file, edit.span.start),
end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
}
getFormattingEditsAfterKeystroke(line: number, col: number, key: string, fileName: string): protocol.CodeEdit[] {
getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -462,9 +467,10 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var formatOptions = this.projectService.getFormatCodeOptions(file);
var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key,
compilerService.formatCodeOptions);
formatOptions);
// Check whether we should auto-indent. This will be when
// the position is on a line containing only whitespace.
// This should leave the edits returned from
@@ -480,8 +486,8 @@ module ts.server {
if (lineText.search("\\S") < 0) {
// TODO: get these options from host
var editorOptions: ts.EditorOptions = {
IndentSize: 4,
TabSize: 4,
IndentSize: formatOptions.IndentSize,
TabSize: formatOptions.TabSize,
NewLineCharacter: "\n",
ConvertTabsToSpaces: true,
};
@@ -516,16 +522,16 @@ module ts.server {
return edits.map((edit) => {
return {
start: compilerService.host.positionToLineCol(file,
start: compilerService.host.positionToLineOffset(file,
edit.span.start),
end: compilerService.host.positionToLineCol(file,
end: compilerService.host.positionToLineOffset(file,
ts.textSpanEnd(edit.span)),
newText: edit.newText ? edit.newText : ""
};
});
}
getCompletions(line: number, col: number, prefix: string, fileName: string): protocol.CompletionEntry[] {
getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] {
if (!prefix) {
prefix = "";
}
@@ -536,7 +542,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var completions = compilerService.languageService.getCompletionsAtPosition(file, position);
if (!completions) {
@@ -551,7 +557,7 @@ module ts.server {
}, []);
}
getCompletionEntryDetails(line: number, col: number,
getCompletionEntryDetails(line: number, offset: number,
entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -560,7 +566,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
return entryNames.reduce((accum: protocol.CompletionEntryDetails[], entryName: string) => {
var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName);
@@ -586,13 +592,13 @@ module ts.server {
}
}
change(line: number, col: number, endLine: number, endCol: number, insertString: string, fileName: string) {
change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (project) {
var compilerService = project.compilerService;
var start = compilerService.host.lineColToPosition(file, line, col);
var end = compilerService.host.lineColToPosition(file, endLine, endCol);
var start = compilerService.host.lineOffsetToPosition(file, line, offset);
var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset);
if (start >= 0) {
compilerService.host.editScript(file, start, end, insertString);
this.changeSeq++;
@@ -608,7 +614,7 @@ module ts.server {
if (project) {
this.changeSeq++;
// make sure no changes happen before this one is finished
project.compilerService.host.reloadScript(file, tmpfile,() => {
project.compilerService.host.reloadScript(file, tmpfile, () => {
this.output(undefined, CommandNames.Reload, reqSeq);
});
}
@@ -641,8 +647,8 @@ module ts.server {
kind: item.kind,
kindModifiers: item.kindModifiers,
spans: item.spans.map(span => ({
start: compilerService.host.positionToLineCol(fileName, span.start),
end: compilerService.host.positionToLineCol(fileName, ts.textSpanEnd(span))
start: compilerService.host.positionToLineOffset(fileName, span.start),
end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span))
})),
childItems: this.decorateNavigationBarItem(project, fileName, item.childItems)
}));
@@ -678,8 +684,8 @@ module ts.server {
}
return navItems.map((navItem) => {
var start = compilerService.host.positionToLineCol(navItem.fileName, navItem.textSpan.start);
var end = compilerService.host.positionToLineCol(navItem.fileName, ts.textSpanEnd(navItem.textSpan));
var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start);
var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan));
var bakedItem: protocol.NavtoItem = {
name: navItem.name,
kind: navItem.kind,
@@ -703,7 +709,7 @@ module ts.server {
});
}
getBraceMatching(line: number, col: number, fileName: string): protocol.TextSpan[] {
getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
@@ -712,7 +718,7 @@ module ts.server {
}
var compilerService = project.compilerService;
var position = compilerService.host.lineColToPosition(file, line, col);
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position);
if (!spans) {
@@ -720,8 +726,8 @@ module ts.server {
}
return spans.map(span => ({
start: compilerService.host.positionToLineCol(file, span.start),
end: compilerService.host.positionToLineCol(file, span.start + span.length)
start: compilerService.host.positionToLineOffset(file, span.start),
end: compilerService.host.positionToLineOffset(file, span.start + span.length)
}));
}
@@ -738,49 +744,50 @@ module ts.server {
switch (request.command) {
case CommandNames.Definition: {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getDefinition(defArgs.line, defArgs.col, defArgs.file);
response = this.getDefinition(defArgs.line, defArgs.offset, defArgs.file);
break;
}
case CommandNames.References: {
var refArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getReferences(refArgs.line, refArgs.col, refArgs.file);
response = this.getReferences(refArgs.line, refArgs.offset, refArgs.file);
break;
}
case CommandNames.Rename: {
var renameArgs = <protocol.RenameRequestArgs>request.arguments;
response = this.getRenameLocations(renameArgs.line, renameArgs.col, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings);
response = this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings);
break;
}
case CommandNames.Open: {
var openArgs = <protocol.FileRequestArgs>request.arguments;
this.openClientFile(openArgs.file);
var openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file,openArgs.tabSize, openArgs.indentSize);
responseRequired = false;
break;
}
case CommandNames.Quickinfo: {
var quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.col, quickinfoArgs.file);
response = this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file);
break;
}
case CommandNames.Format: {
var formatArgs = <protocol.FormatRequestArgs>request.arguments;
response = this.getFormattingEditsForRange(formatArgs.line, formatArgs.col, formatArgs.endLine, formatArgs.endCol, formatArgs.file);
response = this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file);
break;
}
case CommandNames.Formatonkey: {
var formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments;
response = this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.col, formatOnKeyArgs.key, formatOnKeyArgs.file);
response = this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file);
break;
}
case CommandNames.Completions: {
var completionsArgs = <protocol.CompletionsRequestArgs>request.arguments;
response = this.getCompletions(request.arguments.line, request.arguments.col, completionsArgs.prefix, request.arguments.file);
response = this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file);
break;
}
case CommandNames.CompletionDetails: {
var completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments;
response = this.getCompletionEntryDetails(request.arguments.line, request.arguments.col, completionDetailsArgs.entryNames,
request.arguments.file);
response =
this.getCompletionEntryDetails(completionDetailsArgs.line,completionDetailsArgs.offset,
completionDetailsArgs.entryNames,completionDetailsArgs.file);
break;
}
case CommandNames.Geterr: {
@@ -791,14 +798,22 @@ module ts.server {
}
case CommandNames.Change: {
var changeArgs = <protocol.ChangeRequestArgs>request.arguments;
this.change(changeArgs.line, changeArgs.col, changeArgs.endLine, changeArgs.endCol,
this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset,
changeArgs.insertString, changeArgs.file);
responseRequired = false;
break;
}
case CommandNames.Configure: {
var configureArgs = <protocol.ConfigureRequestArguments>request.arguments;
this.projectService.setHostConfiguration(configureArgs);
this.output(undefined, CommandNames.Configure, request.seq);
responseRequired = false;
break;
}
case CommandNames.Reload: {
var reloadArgs = <protocol.ReloadRequestArgs>request.arguments;
this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq);
responseRequired = false;
break;
}
case CommandNames.Saveto: {
@@ -820,7 +835,7 @@ module ts.server {
}
case CommandNames.Brace: {
var braceArguments = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getBraceMatching(braceArguments.line, braceArguments.col, braceArguments.file);
response = this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file);
break;
}
case CommandNames.NavBar: {
+12 -2
View File
@@ -1008,10 +1008,20 @@ module ts.formatting {
return SyntaxKind.Unknown;
}
let internedTabsIndentation: string[];
let internedSpacesIndentation: string[];
var internedSizes: { tabSize: number; indentSize: number };
var internedTabsIndentation: string[];
var internedSpacesIndentation: string[];
export function getIndentationString(indentation: number, options: FormatCodeOptions): string {
// reset interned strings if FormatCodeOptions were changed
let resetInternedStrings =
!internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize);
if (resetInternedStrings) {
internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize };
internedTabsIndentation = internedSpacesIndentation = undefined;
}
if (!options.ConvertTabsToSpaces) {
let tabs = Math.floor(indentation / options.TabSize);
let spaces = indentation - tabs * options.TabSize;
-54
View File
@@ -1,54 +0,0 @@
module ts.formatting {
var internedTabsIndentation: string[];
var internedSpacesIndentation: string[];
export function getIndentationString(indentation: number, options: FormatCodeOptions): string {
if (!options.ConvertTabsToSpaces) {
var tabs = Math.floor(indentation / options.TabSize);
var spaces = indentation - tabs * options.TabSize;
var tabString: string;
if (!internedTabsIndentation) {
internedTabsIndentation = [];
}
if (internedTabsIndentation[tabs] === undefined) {
internedTabsIndentation[tabs] = tabString = repeat('\t', tabs);
}
else {
tabString = internedTabsIndentation[tabs];
}
return spaces ? tabString + repeat(" ", spaces) : tabString;
}
else {
var spacesString: string;
var quotient = Math.floor(indentation / options.IndentSize);
var remainder = indentation % options.IndentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
if (internedSpacesIndentation[quotient] === undefined) {
spacesString = repeat(" ", options.IndentSize * quotient);
internedSpacesIndentation[quotient] = spacesString;
}
else {
spacesString = internedSpacesIndentation[quotient];
}
return remainder ? spacesString + repeat(" ", remainder) : spacesString;
}
function repeat(value: string, count: number): string {
var s = "";
for (var i = 0; i < count; ++i) {
s += value;
}
return s;
}
}
}
+1 -128
View File
@@ -215,11 +215,7 @@ module ts.formatting {
function getStartLineAndCharacterForNode(n: Node, sourceFile: SourceFile): LineAndCharacter {
return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
}
function positionBelongsToNode(candidate: Node, position: number, sourceFile: SourceFile): boolean {
return candidate.end > position || !isCompletedNode(candidate, sourceFile);
}
export function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean {
if (parent.kind === SyntaxKind.IfStatement && (<IfStatement>parent).elseStatement === child) {
let elseKeyword = findChildOfKind(parent, SyntaxKind.ElseKeyword, sourceFile);
@@ -403,128 +399,5 @@ module ts.formatting {
return false;
}
}
/*
* Checks if node ends with 'expectedLastToken'.
* If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
*/
function nodeEndsWith(n: Node, expectedLastToken: SyntaxKind, sourceFile: SourceFile): boolean {
let children = n.getChildren(sourceFile);
if (children.length) {
let last = children[children.length - 1];
if (last.kind === expectedLastToken) {
return true;
}
else if (last.kind === SyntaxKind.SemicolonToken && children.length !== 1) {
return children[children.length - 2].kind === expectedLastToken;
}
}
return false;
}
/*
* This function is always called when position of the cursor is located after the node
*/
function isCompletedNode(n: Node, sourceFile: SourceFile): boolean {
if (n.getFullWidth() === 0) {
return false;
}
switch (n.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.TypeLiteral:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
case SyntaxKind.CaseBlock:
return nodeEndsWith(n, SyntaxKind.CloseBraceToken, sourceFile);
case SyntaxKind.CatchClause:
return isCompletedNode((<CatchClause>n).block, sourceFile);
case SyntaxKind.NewExpression:
if (!(<NewExpression>n).arguments) {
return true;
}
// fall through
case SyntaxKind.CallExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.ParenthesizedType:
return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return isCompletedNode((<SignatureDeclaration>n).type, sourceFile);
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ArrowFunction:
if ((<FunctionLikeDeclaration>n).body) {
return isCompletedNode((<FunctionLikeDeclaration>n).body, sourceFile);
}
if ((<FunctionLikeDeclaration>n).type) {
return isCompletedNode((<FunctionLikeDeclaration>n).type, sourceFile);
}
// Even though type parameters can be unclosed, we can get away with
// having at least a closing paren.
return hasChildOfKind(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.ModuleDeclaration:
return (<ModuleDeclaration>n).body && isCompletedNode((<ModuleDeclaration>n).body, sourceFile);
case SyntaxKind.IfStatement:
if ((<IfStatement>n).elseStatement) {
return isCompletedNode((<IfStatement>n).elseStatement, sourceFile);
}
return isCompletedNode((<IfStatement>n).thenStatement, sourceFile);
case SyntaxKind.ExpressionStatement:
return isCompletedNode((<ExpressionStatement>n).expression, sourceFile);
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ComputedPropertyName:
case SyntaxKind.TupleType:
return nodeEndsWith(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.IndexSignature:
if ((<IndexSignatureDeclaration>n).type) {
return isCompletedNode((<IndexSignatureDeclaration>n).type, sourceFile);
}
return hasChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
// there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed
return false;
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.WhileStatement:
return isCompletedNode((<IterationStatement>n).statement, sourceFile);
case SyntaxKind.DoStatement:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
let hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile);
if (hasWhileKeyword) {
return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile);
}
return isCompletedNode((<DoStatement>n).statement, sourceFile);
default:
return true;
}
}
}
}
+33 -22
View File
@@ -2400,7 +2400,7 @@ module ts {
// If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface
let declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile);
return semanticDiagnostics.concat(declarationDiagnostics);
return concatenate(semanticDiagnostics, declarationDiagnostics);
}
function getJavaScriptSemanticDiagnostics(sourceFile: SourceFile): Diagnostic[] {
@@ -2836,8 +2836,9 @@ module ts {
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(previousToken);
/// TODO filter meaning based on the current context
let scopeNode = getScopeNode(previousToken, position, sourceFile);
let symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias;
let symbols = typeInfoResolver.getSymbolsInScope(node, symbolMeanings);
let symbols = typeInfoResolver.getSymbolsInScope(scopeNode, symbolMeanings);
getCompletionEntriesFromSymbols(symbols);
}
@@ -2845,6 +2846,25 @@ module ts {
return true;
}
return {
isMemberCompletion,
isNewIdentifierLocation,
isBuilder: isNewIdentifierDefinitionLocation, // temporary property used to match VS implementation
entries: activeCompletionSession.entries
};
/**
* Finds the first node that "embraces" the position, so that one may
* accurately aggregate locals from the closest containing scope.
*/
function getScopeNode(initialToken: Node, position: number, sourceFile: SourceFile) {
var scope = initialToken;
while (scope && !positionBelongsToNode(scope, position, sourceFile)) {
scope = scope.parent;
}
return scope;
}
function getCompletionEntriesFromSymbols(symbols: Symbol[]): void {
let session = activeCompletionSession;
let start = new Date().getTime();
@@ -3708,7 +3728,6 @@ module ts {
}
}
let result: DefinitionInfo[] = [];
// Because name in short-hand property assignment has two different meanings: property name and property value,
// using go-to-definition at such position should go to the variable declaration of the property value rather than
@@ -3717,16 +3736,19 @@ module ts {
// assignment. This case and others are handled by the following code.
if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
let shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
if (!shorthandSymbol) {
return [];
}
let shorthandDeclarations = shorthandSymbol.getDeclarations();
let shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver, node);
let shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol);
let shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node);
forEach(shorthandDeclarations, declaration => {
result.push(getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName));
});
return result
return map(shorthandDeclarations,
declaration => getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName));
}
let result: DefinitionInfo[] = [];
let declarations = symbol.getDeclarations();
let symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
let symbolKind = getSymbolKind(symbol, typeInfoResolver, node);
@@ -4240,18 +4262,18 @@ module ts {
let container = declaration.parent;
// Make sure we only highlight the keyword when it makes sense to do so.
if (declaration.flags & NodeFlags.AccessibilityModifier) {
if (isAccessibilityModifier(modifier)) {
if (!(container.kind === SyntaxKind.ClassDeclaration ||
(declaration.kind === SyntaxKind.Parameter && hasKind(container, SyntaxKind.Constructor)))) {
return undefined;
}
}
else if (declaration.flags & NodeFlags.Static) {
else if (modifier === SyntaxKind.StaticKeyword) {
if (container.kind !== SyntaxKind.ClassDeclaration) {
return undefined;
}
}
else if (declaration.flags & (NodeFlags.Export | NodeFlags.Ambient)) {
else if (modifier === SyntaxKind.ExportKeyword || modifier === SyntaxKind.DeclareKeyword) {
if (!(container.kind === SyntaxKind.ModuleBlock || container.kind === SyntaxKind.SourceFile)) {
return undefined;
}
@@ -4292,7 +4314,7 @@ module ts {
default:
Debug.fail("Invalid container kind.")
}
forEach(nodes, node => {
if (node.modifiers && node.flags & modifierFlag) {
forEach(node.modifiers, child => pushKeywordIf(keywords, child, modifier));
@@ -6077,17 +6099,6 @@ module ts {
// a string literal, and a template end consisting of '} } `'.
let templateStack: SyntaxKind[] = [];
function isAccessibilityModifier(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return true;
}
return false;
}
/** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */
function canFollow(keyword1: SyntaxKind, keyword2: SyntaxKind) {
if (isAccessibilityModifier(keyword1)) {
+2
View File
@@ -838,3 +838,5 @@ module ts {
module TypeScript.Services {
export var TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
}
let toolsVersion = "1.4";
+162
View File
@@ -59,6 +59,157 @@ module ts {
return start < end;
}
export function positionBelongsToNode(candidate: Node, position: number, sourceFile: SourceFile): boolean {
return candidate.end > position || !isCompletedNode(candidate, sourceFile);
}
export function isCompletedNode(n: Node, sourceFile: SourceFile): boolean {
if (nodeIsMissing(n)) {
return false;
}
switch (n.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.TypeLiteral:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
case SyntaxKind.CaseBlock:
return nodeEndsWith(n, SyntaxKind.CloseBraceToken, sourceFile);
case SyntaxKind.CatchClause:
return isCompletedNode((<CatchClause>n).block, sourceFile);
case SyntaxKind.NewExpression:
if (!(<NewExpression>n).arguments) {
return true;
}
// fall through
case SyntaxKind.CallExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.ParenthesizedType:
return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return isCompletedNode((<SignatureDeclaration>n).type, sourceFile);
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ArrowFunction:
if ((<FunctionLikeDeclaration>n).body) {
return isCompletedNode((<FunctionLikeDeclaration>n).body, sourceFile);
}
if ((<FunctionLikeDeclaration>n).type) {
return isCompletedNode((<FunctionLikeDeclaration>n).type, sourceFile);
}
// Even though type parameters can be unclosed, we can get away with
// having at least a closing paren.
return hasChildOfKind(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.ModuleDeclaration:
return (<ModuleDeclaration>n).body && isCompletedNode((<ModuleDeclaration>n).body, sourceFile);
case SyntaxKind.IfStatement:
if ((<IfStatement>n).elseStatement) {
return isCompletedNode((<IfStatement>n).elseStatement, sourceFile);
}
return isCompletedNode((<IfStatement>n).thenStatement, sourceFile);
case SyntaxKind.ExpressionStatement:
return isCompletedNode((<ExpressionStatement>n).expression, sourceFile);
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.ComputedPropertyName:
case SyntaxKind.TupleType:
return nodeEndsWith(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.IndexSignature:
if ((<IndexSignatureDeclaration>n).type) {
return isCompletedNode((<IndexSignatureDeclaration>n).type, sourceFile);
}
return hasChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
// there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed
return false;
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.WhileStatement:
return isCompletedNode((<IterationStatement>n).statement, sourceFile);
case SyntaxKind.DoStatement:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
let hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile);
if (hasWhileKeyword) {
return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile);
}
return isCompletedNode((<DoStatement>n).statement, sourceFile);
case SyntaxKind.TypeQuery:
return isCompletedNode((<TypeQueryNode>n).exprName, sourceFile);
case SyntaxKind.TypeOfExpression:
case SyntaxKind.DeleteExpression:
case SyntaxKind.VoidExpression:
case SyntaxKind.YieldExpression:
case SyntaxKind.SpreadElementExpression:
let unaryWordExpression = (<TypeOfExpression|DeleteExpression|VoidExpression|YieldExpression|SpreadElementExpression>n);
return isCompletedNode(unaryWordExpression.expression, sourceFile);
case SyntaxKind.TaggedTemplateExpression:
return isCompletedNode((<TaggedTemplateExpression>n).template, sourceFile);
case SyntaxKind.TemplateExpression:
let lastSpan = lastOrUndefined((<TemplateExpression>n).templateSpans);
return isCompletedNode(lastSpan, sourceFile);
case SyntaxKind.TemplateSpan:
return nodeIsPresent((<TemplateSpan>n).literal);
case SyntaxKind.PrefixUnaryExpression:
return isCompletedNode((<PrefixUnaryExpression>n).operand, sourceFile);
case SyntaxKind.BinaryExpression:
return isCompletedNode((<BinaryExpression>n).right, sourceFile);
case SyntaxKind.ConditionalExpression:
return isCompletedNode((<ConditionalExpression>n).whenFalse, sourceFile);
default:
return true;
}
}
/*
* Checks if node ends with 'expectedLastToken'.
* If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
*/
function nodeEndsWith(n: Node, expectedLastToken: SyntaxKind, sourceFile: SourceFile): boolean {
let children = n.getChildren(sourceFile);
if (children.length) {
let last = children[children.length - 1];
if (last.kind === expectedLastToken) {
return true;
}
else if (last.kind === SyntaxKind.SemicolonToken && children.length !== 1) {
return children[children.length - 2].kind === expectedLastToken;
}
}
return false;
}
export function findListItemInfo(node: Node): ListItemInfo {
let list = findContainingList(node);
@@ -320,6 +471,17 @@ module ts {
&& (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd());
}
export function isAccessibilityModifier(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return true;
}
return false;
}
export function compareDataObjects(dst: any, src: any): boolean {
for (let e in dst) {
if (typeof dst[e] === "object") {