From 1d176e43b089642a7ae3384e4b7fedcdc928d449 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Tue, 28 Oct 2014 18:55:49 -0700 Subject: [PATCH 1/9] Remove syntaxTree from SourceFileObject --- src/services/services.ts | 74 +++++++++++++++------------------------- 1 file changed, 28 insertions(+), 46 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 1ef25e2cb0e..afaf5ca4535 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -71,8 +71,6 @@ module ts { } export interface SourceFile { - getSourceUnit(): TypeScript.SourceUnitSyntax; - getSyntaxTree(): TypeScript.SyntaxTree; getScriptSnapshot(): TypeScript.IScriptSnapshot; getNamedDeclarations(): Declaration[]; update(scriptSnapshot: TypeScript.IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange): SourceFile; @@ -660,23 +658,13 @@ module ts { public languageVersion: ScriptTarget; public identifiers: Map; - private syntaxTree: TypeScript.SyntaxTree; private scriptSnapshot: TypeScript.IScriptSnapshot; private namedDeclarations: Declaration[]; - public getSourceUnit(): TypeScript.SourceUnitSyntax { - // If we don't have a script, create one from our parse tree. - return this.getSyntaxTree().sourceUnit(); - } - public getScriptSnapshot(): TypeScript.IScriptSnapshot { return this.scriptSnapshot; } - public getLineMap(): TypeScript.LineMap { - return this.getSyntaxTree().lineMap(); - } - public getNamedDeclarations() { if (!this.namedDeclarations) { var sourceFile = this; @@ -748,32 +736,11 @@ module ts { return this.namedDeclarations; } - public getSyntaxTree(): TypeScript.SyntaxTree { - if (!this.syntaxTree) { - var start = new Date().getTime(); - - this.syntaxTree = TypeScript.Parser.parse( - this.filename, TypeScript.SimpleText.fromScriptSnapshot(this.scriptSnapshot), this.languageVersion, this.isDeclareFile()); - - var time = new Date().getTime() - start; - - //TypeScript.syntaxTreeParseTime += time; - } - - return this.syntaxTree; - } - private isDeclareFile(): boolean { return TypeScript.isDTSFile(this.filename); } public update(scriptSnapshot: TypeScript.IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange): SourceFile { - // See if we are currently holding onto a syntax tree. We may not be because we're - // either a closed file, or we've just been lazy and haven't had to create the syntax - // tree yet. Access the field instead of the method so we don't accidentally realize - // the old syntax tree. - var oldSyntaxTree = this.syntaxTree; - if (textChangeRange && Debug.shouldAssert(AssertionLevel.Normal)) { var oldText = this.scriptSnapshot; var newText = scriptSnapshot; @@ -791,21 +758,12 @@ module ts { } } - var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); - - // If we don't have a text change, or we don't have an old syntax tree, then do a full - // parse. Otherwise, do an incremental parse. - var newSyntaxTree = !textChangeRange || !oldSyntaxTree - ? TypeScript.Parser.parse(this.filename, text, this.languageVersion, TypeScript.isDTSFile(this.filename)) - : TypeScript.IncrementalParser.parse(oldSyntaxTree, textChangeRange, text); - - return SourceFileObject.createSourceFileObject(this.filename, scriptSnapshot, this.languageVersion, version, isOpen, newSyntaxTree); + return SourceFileObject.createSourceFileObject(this.filename, scriptSnapshot, this.languageVersion, version, isOpen); } - public static createSourceFileObject(filename: string, scriptSnapshot: TypeScript.IScriptSnapshot, languageVersion: ScriptTarget, version: string, isOpen: boolean, syntaxTree?: TypeScript.SyntaxTree) { + public static createSourceFileObject(filename: string, scriptSnapshot: TypeScript.IScriptSnapshot, languageVersion: ScriptTarget, version: string, isOpen: boolean) { var newSourceFile = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), languageVersion, version, isOpen); newSourceFile.scriptSnapshot = scriptSnapshot; - newSourceFile.syntaxTree = syntaxTree; return newSourceFile; } } @@ -1633,7 +1591,9 @@ module ts { private initialize(filename: string) { // ensure that both source file and syntax tree are either initialized or not initialized Debug.assert(!!this.currentFileSyntaxTree === !!this.currentSourceFile); + var start = new Date().getTime(); this.hostCache = new HostCache(this.host); + this.host.log("SyntaxTreeCache.Initialize: new HostCache: " + (new Date().getTime() - start)); var version = this.hostCache.getVersion(filename); var syntaxTree: TypeScript.SyntaxTree = null; @@ -1641,22 +1601,37 @@ module ts { if (this.currentFileSyntaxTree === null || this.currentFilename !== filename) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); + var start = new Date().getTime(); syntaxTree = this.createSyntaxTree(filename, scriptSnapshot); - sourceFile = createSourceFileFromScriptSnapshot(filename, scriptSnapshot, getDefaultCompilerOptions(), version, /*isOpen*/ true); + this.host.log("SyntaxTreeCache.Initialize: createSyntaxTree: " + (new Date().getTime() - start)); + var start = new Date().getTime(); + sourceFile = createSourceFileFromScriptSnapshot(filename, scriptSnapshot, getDefaultCompilerOptions(), version, /*isOpen*/ true); + this.host.log("SyntaxTreeCache.Initialize: createSourceFile: " + (new Date().getTime() - start)); + + var start = new Date().getTime(); fixupParentReferences(sourceFile); + this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } else if (this.currentFileVersion !== version) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); + + var start = new Date().getTime(); syntaxTree = this.updateSyntaxTree(filename, scriptSnapshot, this.currentSourceFile.getScriptSnapshot(), this.currentFileSyntaxTree, this.currentFileVersion); + this.host.log("SyntaxTreeCache.Initialize: updateSyntaxTree: " + (new Date().getTime() - start)); var editRange = this.hostCache.getChangeRange(filename, this.currentFileVersion, this.currentSourceFile.getScriptSnapshot()); + + var start = new Date().getTime(); sourceFile = !editRange ? createSourceFileFromScriptSnapshot(filename, scriptSnapshot, getDefaultCompilerOptions(), version, /*isOpen*/ true) : this.currentSourceFile.update(scriptSnapshot, version, /*isOpen*/ true, editRange); + this.host.log("SyntaxTreeCache.Initialize: updateSourceFile: " + (new Date().getTime() - start)); + var start = new Date().getTime(); fixupParentReferences(sourceFile); + this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } if (syntaxTree !== null) { @@ -5050,10 +5025,17 @@ module ts { function getIndentationAtPosition(filename: string, position: number, editorOptions: EditorOptions) { filename = TypeScript.switchToForwardSlashes(filename); + var start = new Date().getTime(); var sourceFile = getCurrentSourceFile(filename); + host.log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + + var start = new Date().getTime(); var options = new TypeScript.FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter) - return formatting.SmartIndenter.getIndentation(position, sourceFile, options); + var result = formatting.SmartIndenter.getIndentation(position, sourceFile, options); + host.log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + + return result; } function getFormattingManager(filename: string, options: FormatCodeOptions) { From aba220c69071578a3738b3962b4f2c4df74f3e7d Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 29 Oct 2014 09:39:19 -0700 Subject: [PATCH 2/9] Export DisplayPartsSymbolWriter as it is already used in exported types --- src/services/services.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/services.ts b/src/services/services.ts index d2e4360725d..4d4a4f94ea5 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1286,7 +1286,7 @@ module ts { return ""; } - interface DisplayPartsSymbolWriter extends SymbolWriter { + export interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } From 7eeac2bce26019b2c50ea388a4628f0186c6e785 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 29 Oct 2014 09:49:57 -0700 Subject: [PATCH 3/9] Update LKG --- bin/tsc.js | 471 ++++++++++++-------- bin/typescriptServices.js | 915 +++++++++++++++++++++----------------- 2 files changed, 795 insertions(+), 591 deletions(-) diff --git a/bin/tsc.js b/bin/tsc.js index aaba61dfe94..0b8dd882716 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -155,17 +155,16 @@ var ts; Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: 1 /* Error */, key: "Global type '{0}' must have {1} type parameter(s)." }, Cannot_find_global_type_0: { code: 2318, category: 1 /* Error */, key: "Cannot find global type '{0}'." }, Named_properties_0_of_types_1_and_2_are_not_identical: { code: 2319, category: 1 /* Error */, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon: { code: 2320, category: 1 /* Error */, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':" }, + Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: 1 /* Error */, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: 1 /* Error */, key: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1_Colon: { code: 2322, category: 1 /* Error */, key: "Type '{0}' is not assignable to type '{1}':" }, Type_0_is_not_assignable_to_type_1: { code: 2323, category: 1 /* Error */, key: "Type '{0}' is not assignable to type '{1}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: 1 /* Error */, key: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: 1 /* Error */, key: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible_Colon: { code: 2326, category: 1 /* Error */, key: "Types of property '{0}' are incompatible:" }, + Types_of_property_0_are_incompatible: { code: 2326, category: 1 /* Error */, key: "Types of property '{0}' are incompatible." }, Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: 1 /* Error */, key: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible_Colon: { code: 2328, category: 1 /* Error */, key: "Types of parameters '{0}' and '{1}' are incompatible:" }, + Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: 1 /* Error */, key: "Types of parameters '{0}' and '{1}' are incompatible." }, Index_signature_is_missing_in_type_0: { code: 2329, category: 1 /* Error */, key: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible_Colon: { code: 2330, category: 1 /* Error */, key: "Index signatures are incompatible:" }, + Index_signatures_are_incompatible: { code: 2330, category: 1 /* Error */, key: "Index signatures are incompatible." }, this_cannot_be_referenced_in_a_module_body: { code: 2331, category: 1 /* Error */, key: "'this' cannot be referenced in a module body." }, this_cannot_be_referenced_in_current_location: { code: 2332, category: 1 /* Error */, key: "'this' cannot be referenced in current location." }, this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: 1 /* Error */, key: "'this' cannot be referenced in constructor arguments." }, @@ -178,7 +177,6 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: 1 /* Error */, key: "Only public and protected methods of the base class are accessible via the 'super' keyword" }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: 1 /* Error */, key: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_or_any: { code: 2342, category: 1 /* Error */, key: "An index expression argument must be of type 'string', 'number', or 'any'." }, - Type_0_does_not_satisfy_the_constraint_1_Colon: { code: 2343, category: 1 /* Error */, key: "Type '{0}' does not satisfy the constraint '{1}':" }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: 1 /* Error */, key: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: 1 /* Error */, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: 1 /* Error */, key: "Supplied parameters do not match any signature of call target." }, @@ -188,7 +186,6 @@ var ts; Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: 1 /* Error */, key: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: 1 /* Error */, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: 1 /* Error */, key: "Neither type '{0}' nor type '{1}' is assignable to the other." }, - Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon: { code: 2353, category: 1 /* Error */, key: "Neither type '{0}' nor type '{1}' is assignable to the other:" }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: 1 /* Error */, key: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: 1 /* Error */, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: 1 /* Error */, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, @@ -249,12 +246,9 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: 1 /* Error */, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, Class_name_cannot_be_0: { code: 2414, category: 1 /* Error */, key: "Class name cannot be '{0}'" }, Class_0_incorrectly_extends_base_class_1: { code: 2415, category: 1 /* Error */, key: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_0_incorrectly_extends_base_class_1_Colon: { code: 2416, category: 1 /* Error */, key: "Class '{0}' incorrectly extends base class '{1}':" }, Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: 1 /* Error */, key: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon: { code: 2418, category: 1 /* Error */, key: "Class static side '{0}' incorrectly extends base class static side '{1}':" }, Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: 1 /* Error */, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, Class_0_incorrectly_implements_interface_1: { code: 2420, category: 1 /* Error */, key: "Class '{0}' incorrectly implements interface '{1}'." }, - Class_0_incorrectly_implements_interface_1_Colon: { code: 2421, category: 1 /* Error */, key: "Class '{0}' incorrectly implements interface '{1}':" }, A_class_may_only_implement_another_class_or_interface: { code: 2422, category: 1 /* Error */, key: "A class may only implement another class or interface." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: 1 /* Error */, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: 1 /* Error */, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, @@ -262,7 +256,6 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: 1 /* Error */, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, Interface_name_cannot_be_0: { code: 2427, category: 1 /* Error */, key: "Interface name cannot be '{0}'" }, All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: 1 /* Error */, key: "All declarations of an interface must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1_Colon: { code: 2429, category: 1 /* Error */, key: "Interface '{0}' incorrectly extends interface '{1}':" }, Interface_0_incorrectly_extends_interface_1: { code: 2430, category: 1 /* Error */, key: "Interface '{0}' incorrectly extends interface '{1}'." }, Enum_name_cannot_be_0: { code: 2431, category: 1 /* Error */, key: "Enum name cannot be '{0}'" }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: 1 /* Error */, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, @@ -286,7 +279,9 @@ var ts; Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: 1 /* Error */, key: "Left-hand side of assignment expression cannot be a constant.", isEarly: true }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: 1 /* Error */, key: "Cannot redeclare block-scoped variable '{0}'.", isEarly: true }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: 1 /* Error */, key: "An enum member cannot have a numeric name." }, - Type_alias_0_circularly_references_itself: { code: 2453, category: 1 /* Error */, key: "Type alias '{0}' circularly references itself." }, + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: 1 /* Error */, key: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: 1 /* Error */, key: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, + Type_alias_0_circularly_references_itself: { code: 2456, category: 1 /* Error */, key: "Type alias '{0}' circularly references itself." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: 1 /* Error */, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4001, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, @@ -2130,6 +2125,12 @@ var ts; }; } ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + Debug.assert(!headChain.next); + headChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; function flattenDiagnosticChain(file, start, length, diagnosticChain, newLine) { Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); @@ -9344,6 +9345,7 @@ var ts; var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var inferenceFailureType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); var globals = {}; @@ -9517,21 +9519,100 @@ var ts; } } function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { - var errorLocation = location; var result; var lastLocation; - var memberWithInitializerThatReferencesIdentifierFromConstructor; - function returnResolvedSymbol(s) { - if (s && memberWithInitializerThatReferencesIdentifierFromConstructor) { - var propertyName = memberWithInitializerThatReferencesIdentifierFromConstructor.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.identifierToString(propertyName), nameArg); + var propertyWithInvalidInitializer; + var errorLocation = location; + loop: while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = getSymbol(location.locals, name, meaning)) { + break loop; + } + } + switch (location.kind) { + case 186 /* SourceFile */: + if (!ts.isExternalModule(location)) + break; + case 181 /* ModuleDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & ts.SymbolFlags.ModuleMember)) { + break loop; + } + break; + case 180 /* EnumDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 120 /* Property */: + if (location.parent.kind === 177 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (getSymbol(ctor.locals, name, meaning & ts.SymbolFlags.Value)) { + propertyWithInvalidInitializer = location; + } + } + } + break; + case 177 /* ClassDeclaration */: + case 178 /* InterfaceDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & ts.SymbolFlags.Type)) { + if (lastLocation && lastLocation.flags & 128 /* Static */) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + break; + case 121 /* Method */: + case 122 /* Constructor */: + case 123 /* GetAccessor */: + case 124 /* SetAccessor */: + case 175 /* FunctionDeclaration */: + case 145 /* ArrowFunction */: + if (name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 144 /* FunctionExpression */: + if (name === "arguments") { + result = argumentsSymbol; + break loop; + } + var id = location.name; + if (id && name === id.text) { + result = location.symbol; + break loop; + } + break; + case 171 /* CatchBlock */: + var id = location.variable; + if (name === id.text) { + result = location.symbol; + break loop; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (!result) { + result = getSymbol(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.identifierToString(nameArg)); + } + return undefined; + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.identifierToString(propertyName), typeof nameArg === "string" ? nameArg : ts.identifierToString(nameArg)); return undefined; } - if (!s && nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, nameArg); - } - if (s && s.flags & 2 /* BlockScopedVariable */) { - var declaration = ts.forEach(s.declarations, function (d) { return d.flags & ts.NodeFlags.BlockScoped ? d : undefined; }); + if (result.flags & 2 /* BlockScopedVariable */) { + var declaration = ts.forEach(result.declarations, function (d) { return d.flags & ts.NodeFlags.BlockScoped ? d : undefined; }); ts.Debug.assert(declaration, "Block-scoped variable declaration is undefined"); var declarationSourceFile = ts.getSourceFileOfNode(declaration); var referenceSourceFile = ts.getSourceFileOfNode(errorLocation); @@ -9547,83 +9628,8 @@ var ts; } } } - return s; } - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { - return returnResolvedSymbol(result); - } - } - switch (location.kind) { - case 186 /* SourceFile */: - if (!ts.isExternalModule(location)) - break; - case 181 /* ModuleDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & ts.SymbolFlags.ModuleMember)) { - return returnResolvedSymbol(result); - } - break; - case 180 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { - return returnResolvedSymbol(result); - } - break; - case 120 /* Property */: - if (location.parent.kind === 177 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & ts.SymbolFlags.Value)) { - memberWithInitializerThatReferencesIdentifierFromConstructor = location; - } - } - } - break; - case 177 /* ClassDeclaration */: - case 178 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & ts.SymbolFlags.Type)) { - if (lastLocation && lastLocation.flags & 128 /* Static */) { - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - else { - return returnResolvedSymbol(result); - } - } - break; - case 121 /* Method */: - case 122 /* Constructor */: - case 123 /* GetAccessor */: - case 124 /* SetAccessor */: - case 175 /* FunctionDeclaration */: - case 145 /* ArrowFunction */: - if (name === "arguments") { - return returnResolvedSymbol(argumentsSymbol); - } - break; - case 144 /* FunctionExpression */: - if (name === "arguments") { - return returnResolvedSymbol(argumentsSymbol); - } - var id = location.name; - if (id && name === id.text) { - return returnResolvedSymbol(location.symbol); - } - break; - case 171 /* CatchBlock */: - var id = location.variable; - if (name === id.text) { - return returnResolvedSymbol(location.symbol); - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result = getSymbol(globals, name, meaning)) { - return returnResolvedSymbol(result); - } - return returnResolvedSymbol(undefined); + return result; } function resolveImport(symbol) { ts.Debug.assert((symbol.flags & 16777216 /* Import */) !== 0, "Should only get Imports here."); @@ -9665,7 +9671,7 @@ var ts; } function resolveEntityName(location, name, meaning) { if (name.kind === 59 /* Identifier */) { - var symbol = resolveName(location, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(name)); + var symbol = resolveName(location, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, name); if (!symbol) { return; } @@ -9751,7 +9757,7 @@ var ts; } if (node.exportName.text) { var meaning = ts.SymbolFlags.Value | ts.SymbolFlags.Type | ts.SymbolFlags.Namespace; - var exportSymbol = resolveName(node, node.exportName.text, meaning, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(node.exportName)); + var exportSymbol = resolveName(node, node.exportName.text, meaning, ts.Diagnostics.Cannot_find_name_0, node.exportName); } } symbolLinks.exportAssignSymbol = exportSymbol || unknownSymbol; @@ -10022,10 +10028,9 @@ var ts; } function isImportDeclarationEntityNameReferenceDeclarationVisibile(entityName) { var firstIdentifier = getFirstIdentifier(entityName); - var firstIdentifierName = ts.identifierToString(firstIdentifier); - var symbolOfNameSpace = resolveName(entityName.parent, firstIdentifier.text, ts.SymbolFlags.Namespace, ts.Diagnostics.Cannot_find_name_0, firstIdentifierName); + var symbolOfNameSpace = resolveName(entityName.parent, firstIdentifier.text, ts.SymbolFlags.Namespace, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); var hasNamespaceDeclarationsVisibile = hasVisibleDeclarations(symbolOfNameSpace); - return hasNamespaceDeclarationsVisibile ? { accessibility: 0 /* Accessible */, aliasesToMakeVisible: hasNamespaceDeclarationsVisibile.aliasesToMakeVisible } : { accessibility: 1 /* NotAccessible */, errorSymbolName: firstIdentifierName }; + return hasNamespaceDeclarationsVisibile ? { accessibility: 0 /* Accessible */, aliasesToMakeVisible: hasNamespaceDeclarationsVisibile.aliasesToMakeVisible } : { accessibility: 1 /* NotAccessible */, errorSymbolName: ts.identifierToString(firstIdentifier) }; } function releaseStringWriter(writer) { writer.clear(); @@ -11925,27 +11930,27 @@ var ts; var assignableRelation = {}; var identityRelation = {}; function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined, undefined, undefined); + return checkTypeRelatedTo(source, target, identityRelation, undefined); } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, undefined, undefined, undefined); + return checkTypeSubtypeOf(source, target, undefined); } - function checkTypeSubtypeOf(source, target, errorNode, chainedMessage, terminalMessage) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, chainedMessage, terminalMessage); + function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, undefined, undefined, undefined); + return checkTypeAssignableTo(source, target, undefined); } - function checkTypeAssignableTo(source, target, errorNode, chainedMessage, terminalMessage) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, chainedMessage, terminalMessage); + function checkTypeAssignableTo(source, target, errorNode, headMessage) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); } function isTypeRelatedTo(source, target, relation) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + return checkTypeRelatedTo(source, target, relation, undefined); } function isSignatureAssignableTo(source, target) { var sourceType = getOrCreateTypeFromSignature(source); var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined, undefined, undefined); + return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined); } function isPropertyIdenticalTo(sourceProp, targetProp) { return isPropertyIdenticalToRecursive(sourceProp, targetProp, false, function (s, t, _reportErrors) { return isTypeIdenticalTo(s, t); }); @@ -11975,7 +11980,7 @@ var ts; var typeName1 = typeToString(existing.containingType); var typeName2 = typeToString(base); var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon, typeToString(type), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); } } @@ -11999,7 +12004,7 @@ var ts; return isOptionalProperty(sourceProp) === isOptionalProperty(targetProp) && relate(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); } } - function checkTypeRelatedTo(source, target, relation, errorNode, chainedMessage, terminalMessage) { + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; var targetStack; @@ -12007,11 +12012,14 @@ var ts; var depth = 0; var overflow = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, chainedMessage, terminalMessage); + var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); } return result; @@ -12019,9 +12027,9 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function isRelatedTo(source, target, reportErrors) { - return isRelatedToWithCustomErrors(source, target, reportErrors, undefined, undefined); + return isRelatedToWithCustomErrors(source, target, reportErrors, undefined); } - function isRelatedToWithCustomErrors(source, target, reportErrors, chainedMessage, terminalMessage) { + function isRelatedToWithCustomErrors(source, target, reportErrors, headMessage) { if (relation === identityRelation) { if (source === target) return true; @@ -12076,11 +12084,9 @@ var ts; } } if (reportErrors) { - chainedMessage = chainedMessage || ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Colon; - terminalMessage = terminalMessage || ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - var diagnosticKey = errorInfo ? chainedMessage : terminalMessage; - ts.Debug.assert(diagnosticKey); - reportError(diagnosticKey, typeToString(source), typeToString(target)); + headMessage = headMessage || ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + ts.Debug.assert(headMessage); + reportError(headMessage, typeToString(source), typeToString(target)); } return false; } @@ -12239,7 +12245,7 @@ var ts; } if (!isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors)) { if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible_Colon, symbolToString(targetProp)); + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); } return false; } @@ -12332,7 +12338,7 @@ var ts; if (!isRelatedTo(s, t, reportErrors)) { if (!isRelatedTo(t, s, false)) { if (reportErrors) { - reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible_Colon, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); + reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); } return false; } @@ -12373,7 +12379,7 @@ var ts; } if (!isRelatedTo(sourceType, targetType, reportErrors)) { if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible_Colon); + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } return false; } @@ -12402,7 +12408,7 @@ var ts; } if (!compatible) { if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible_Colon); + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } return false; } @@ -12456,6 +12462,32 @@ var ts; function getCommonSupertype(types) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } + function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { + var bestSupertype; + var bestSupertypeDownfallType; + var bestSupertypeScore = 0; + for (var i = 0; i < types.length; i++) { + var score = 0; + var downfallType = undefined; + for (var j = 0; j < types.length; j++) { + if (isTypeSubtypeOf(types[j], types[i])) { + score++; + } + else if (!downfallType) { + downfallType = types[j]; + } + } + if (score > bestSupertypeScore) { + bestSupertype = types[i]; + bestSupertypeDownfallType = downfallType; + bestSupertypeScore = score; + } + if (bestSupertypeScore === types.length - 1) { + break; + } + } + checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + } function isTypeOfObjectLiteral(type) { return (type.flags & 32768 /* Anonymous */) && type.symbol && (type.symbol.flags & 2048 /* ObjectLiteral */) ? true : false; } @@ -12694,27 +12726,28 @@ var ts; } } function getInferredType(context, index) { - var result = context.inferredTypes[index]; - if (!result) { + var inferredType = context.inferredTypes[index]; + if (!inferredType) { var inferences = context.inferences[index]; if (inferences.length) { var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); - var inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : undefinedType; + inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : inferenceFailureType; } else { inferredType = emptyObjectType; } - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - var result = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; - context.inferredTypes[index] = result; + if (inferredType !== inferenceFailureType) { + var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + } + context.inferredTypes[index] = inferredType; } - return result; + return inferredType; } function getInferredTypes(context) { for (var i = 0; i < context.inferredTypes.length; i++) { getInferredType(context, i); } - context.inferences = undefined; return context.inferredTypes; } function hasAncestor(node, kind) { @@ -12723,7 +12756,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = resolveName(node, node.text, ts.SymbolFlags.Value | 2097152 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(node)) || unknownSymbol; + links.resolvedSymbol = resolveName(node, node.text, ts.SymbolFlags.Value | 2097152 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; } return links.resolvedSymbol; } @@ -13531,21 +13564,29 @@ var ts; } } var inferredTypes = getInferredTypes(context); - return ts.contains(inferredTypes, undefinedType) ? undefined : inferredTypes; + context.failedTypeParameterIndex = ts.indexOf(inferredTypes, inferenceFailureType); + for (var i = 0; i < inferredTypes.length; i++) { + if (inferredTypes[i] === inferenceFailureType) { + inferredTypes[i] = unknownType; + } + } + return context; } - function checkTypeArguments(signature, typeArguments) { + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors) { var typeParameters = signature.typeParameters; - var result = []; + var typeArgumentsAreAssignable = true; for (var i = 0; i < typeParameters.length; i++) { var typeArgNode = typeArguments[i]; var typeArgument = getTypeFromTypeNode(typeArgNode); - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint && fullTypeCheck) { - checkTypeAssignableTo(typeArgument, constraint, typeArgNode, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1_Colon, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + typeArgumentResultTypes[i] = typeArgument; + if (typeArgumentsAreAssignable) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } } - result.push(typeArgument); } - return result; + return typeArgumentsAreAssignable; } function checkApplicableSignature(node, signature, relation, excludeArgument, reportErrors) { if (node.arguments) { @@ -13556,7 +13597,7 @@ var ts; } var paramType = getTypeAtPosition(signature, i); var argType = arg.kind === 7 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - var isValidArgument = checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1); + var isValidArgument = checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1); if (!isValidArgument) { return false; } @@ -13581,40 +13622,36 @@ var ts; excludeArgument[i] = true; } } - var relation = candidates.length === 1 ? assignableRelation : subtypeRelation; - var lastCandidate; - while (true) { - for (var i = 0; i < candidates.length; i++) { - if (!signatureHasCorrectArity(node, candidates[i])) { - continue; - } - while (true) { - var candidate = candidates[i]; - if (candidate.typeParameters) { - var typeArguments = node.typeArguments ? checkTypeArguments(candidate, node.typeArguments) : inferTypeArguments(candidate, args, excludeArgument); - if (!typeArguments) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArguments); - } - lastCandidate = candidate; - if (!checkApplicableSignature(node, candidate, relation, excludeArgument, false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - } - if (relation === assignableRelation) { - break; - } - relation = assignableRelation; + var candidateForArgumentError; + var candidateForTypeArgumentError; + var resultOfFailedInference; + var result; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, excludeArgument); } - if (lastCandidate) { - checkApplicableSignature(node, lastCandidate, relation, undefined, true); + if (!result) { + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + resultOfFailedInference = undefined; + result = chooseOverload(candidates, assignableRelation, excludeArgument); + } + if (result) { + return result; + } + if (candidateForArgumentError) { + checkApplicableSignature(node, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForTypeArgumentError) { + if (node.typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true); + } + else { + ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); + var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; + var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex]; + var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + reportNoCommonSupertypeError(inferenceCandidates, node.func, diagnosticChainHead); + } } else { error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); @@ -13627,6 +13664,60 @@ var ts; } } return resolveErrorCall(node); + function chooseOverload(candidates, relation, excludeArgument) { + for (var i = 0; i < candidates.length; i++) { + if (!signatureHasCorrectArity(node, candidates[i])) { + continue; + } + var originalCandidate = candidates[i]; + var inferenceResult; + while (true) { + var candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes; + var typeArgumentsAreValid; + if (node.typeArguments) { + typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentsAreValid = checkTypeArguments(candidate, node.typeArguments, typeArgumentTypes, false); + } + else { + inferenceResult = inferTypeArguments(candidate, args, excludeArgument); + typeArgumentsAreValid = inferenceResult.failedTypeParameterIndex < 0; + typeArgumentTypes = inferenceResult.inferredTypes; + } + if (!typeArgumentsAreValid) { + break; + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, candidate, relation, excludeArgument, false)) { + break; + } + var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; + if (index < 0) { + return candidate; + } + excludeArgument[index] = false; + } + if (originalCandidate.typeParameters) { + var instantiatedCandidate = candidate; + if (typeArgumentsAreValid) { + candidateForArgumentError = instantiatedCandidate; + } + else { + candidateForTypeArgumentError = originalCandidate; + if (!node.typeArguments) { + resultOfFailedInference = inferenceResult; + } + } + } + else { + ts.Debug.assert(originalCandidate === candidate); + candidateForArgumentError = originalCandidate; + } + } + return undefined; + } function collectCandidates() { var result = candidates; var lastParent; @@ -13750,7 +13841,7 @@ var ts; if (fullTypeCheck && targetType !== unknownType) { var widenedType = getWidenedType(exprType, true); if (!(isTypeAssignableTo(targetType, widenedType))) { - checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); + checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } return targetType; @@ -13880,7 +13971,7 @@ var ts; else { var exprType = checkExpression(node.body); if (node.type) { - checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined, undefined); + checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined); } checkFunctionExpressionBodies(node.body); } @@ -14110,7 +14201,7 @@ var ts; if (fullTypeCheck && operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment) { var ok = checkReferenceExpression(node.left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); if (ok) { - checkTypeAssignableTo(valueType, leftType, node.left, undefined, undefined); + checkTypeAssignableTo(valueType, leftType, node.left, undefined); } } } @@ -14414,7 +14505,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); if (fullTypeCheck && constraint) { var typeArgument = type.typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1_Colon, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } } @@ -14852,7 +14943,7 @@ var ts; } if (node.initializer) { if (!(getNodeLinks(node.initializer).flags & 1 /* TypeChecked */)) { - checkTypeAssignableTo(checkAndMarkExpression(node.initializer), type, node, undefined, undefined); + checkTypeAssignableTo(checkAndMarkExpression(node.initializer), type, node, undefined); } checkCollisionWithConstDeclarations(node); } @@ -14933,7 +15024,7 @@ var ts; var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); var checkAssignability = func.type || (func.kind === 123 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(func.symbol, 124 /* SetAccessor */))); if (checkAssignability) { - checkTypeAssignableTo(checkExpression(node.expression), returnType, node.expression, undefined, undefined); + checkTypeAssignableTo(checkExpression(node.expression), returnType, node.expression, undefined); } else if (func.kind == 122 /* Constructor */) { if (!isTypeAssignableTo(checkExpression(node.expression), returnType)) { @@ -14954,7 +15045,7 @@ var ts; if (fullTypeCheck && clause.expression) { var caseType = checkExpression(clause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { - checkTypeAssignableTo(caseType, expressionType, clause.expression, undefined, undefined); + checkTypeAssignableTo(caseType, expressionType, clause.expression, undefined); } } checkBlock(clause); @@ -15061,9 +15152,9 @@ var ts; if (type.baseTypes.length) { if (fullTypeCheck) { var baseType = type.baseTypes[0]; - checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1_Colon, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); var staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseType.symbol !== resolveEntityName(node, node.baseType.typeName, ts.SymbolFlags.Value)) { error(node.baseType, ts.Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); } @@ -15079,7 +15170,7 @@ var ts; if (t !== unknownType) { var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { - checkTypeAssignableTo(type, t, node.name, ts.Diagnostics.Class_0_incorrectly_implements_interface_1_Colon, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + checkTypeAssignableTo(type, t, node.name, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -15184,7 +15275,7 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (checkInheritedPropertiesAreIdentical(type, node.name)) { ts.forEach(type.baseTypes, function (baseType) { - checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1_Colon, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); }); checkIndexConstraints(type); } @@ -15229,7 +15320,7 @@ var ts; if (initializer) { autoValue = getConstantValueForExpression(initializer); if (autoValue === undefined && !ambient) { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined, undefined); + checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); } } else if (ambient) { diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 661017b48b7..8aebc0f642a 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -155,17 +155,16 @@ var ts; Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: 1 /* Error */, key: "Global type '{0}' must have {1} type parameter(s)." }, Cannot_find_global_type_0: { code: 2318, category: 1 /* Error */, key: "Cannot find global type '{0}'." }, Named_properties_0_of_types_1_and_2_are_not_identical: { code: 2319, category: 1 /* Error */, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon: { code: 2320, category: 1 /* Error */, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':" }, + Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: 1 /* Error */, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: 1 /* Error */, key: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1_Colon: { code: 2322, category: 1 /* Error */, key: "Type '{0}' is not assignable to type '{1}':" }, Type_0_is_not_assignable_to_type_1: { code: 2323, category: 1 /* Error */, key: "Type '{0}' is not assignable to type '{1}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: 1 /* Error */, key: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: 1 /* Error */, key: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible_Colon: { code: 2326, category: 1 /* Error */, key: "Types of property '{0}' are incompatible:" }, + Types_of_property_0_are_incompatible: { code: 2326, category: 1 /* Error */, key: "Types of property '{0}' are incompatible." }, Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: 1 /* Error */, key: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible_Colon: { code: 2328, category: 1 /* Error */, key: "Types of parameters '{0}' and '{1}' are incompatible:" }, + Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: 1 /* Error */, key: "Types of parameters '{0}' and '{1}' are incompatible." }, Index_signature_is_missing_in_type_0: { code: 2329, category: 1 /* Error */, key: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible_Colon: { code: 2330, category: 1 /* Error */, key: "Index signatures are incompatible:" }, + Index_signatures_are_incompatible: { code: 2330, category: 1 /* Error */, key: "Index signatures are incompatible." }, this_cannot_be_referenced_in_a_module_body: { code: 2331, category: 1 /* Error */, key: "'this' cannot be referenced in a module body." }, this_cannot_be_referenced_in_current_location: { code: 2332, category: 1 /* Error */, key: "'this' cannot be referenced in current location." }, this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: 1 /* Error */, key: "'this' cannot be referenced in constructor arguments." }, @@ -178,7 +177,6 @@ var ts; Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: 1 /* Error */, key: "Only public and protected methods of the base class are accessible via the 'super' keyword" }, Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: 1 /* Error */, key: "Property '{0}' is private and only accessible within class '{1}'." }, An_index_expression_argument_must_be_of_type_string_number_or_any: { code: 2342, category: 1 /* Error */, key: "An index expression argument must be of type 'string', 'number', or 'any'." }, - Type_0_does_not_satisfy_the_constraint_1_Colon: { code: 2343, category: 1 /* Error */, key: "Type '{0}' does not satisfy the constraint '{1}':" }, Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: 1 /* Error */, key: "Type '{0}' does not satisfy the constraint '{1}'." }, Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: 1 /* Error */, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: 1 /* Error */, key: "Supplied parameters do not match any signature of call target." }, @@ -188,7 +186,6 @@ var ts; Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: 1 /* Error */, key: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: 1 /* Error */, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: 1 /* Error */, key: "Neither type '{0}' nor type '{1}' is assignable to the other." }, - Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon: { code: 2353, category: 1 /* Error */, key: "Neither type '{0}' nor type '{1}' is assignable to the other:" }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: 1 /* Error */, key: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: 1 /* Error */, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: 1 /* Error */, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, @@ -249,12 +246,9 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: 1 /* Error */, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, Class_name_cannot_be_0: { code: 2414, category: 1 /* Error */, key: "Class name cannot be '{0}'" }, Class_0_incorrectly_extends_base_class_1: { code: 2415, category: 1 /* Error */, key: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_0_incorrectly_extends_base_class_1_Colon: { code: 2416, category: 1 /* Error */, key: "Class '{0}' incorrectly extends base class '{1}':" }, Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: 1 /* Error */, key: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon: { code: 2418, category: 1 /* Error */, key: "Class static side '{0}' incorrectly extends base class static side '{1}':" }, Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: 1 /* Error */, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, Class_0_incorrectly_implements_interface_1: { code: 2420, category: 1 /* Error */, key: "Class '{0}' incorrectly implements interface '{1}'." }, - Class_0_incorrectly_implements_interface_1_Colon: { code: 2421, category: 1 /* Error */, key: "Class '{0}' incorrectly implements interface '{1}':" }, A_class_may_only_implement_another_class_or_interface: { code: 2422, category: 1 /* Error */, key: "A class may only implement another class or interface." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: 1 /* Error */, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: 1 /* Error */, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, @@ -262,7 +256,6 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: 1 /* Error */, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, Interface_name_cannot_be_0: { code: 2427, category: 1 /* Error */, key: "Interface name cannot be '{0}'" }, All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: 1 /* Error */, key: "All declarations of an interface must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1_Colon: { code: 2429, category: 1 /* Error */, key: "Interface '{0}' incorrectly extends interface '{1}':" }, Interface_0_incorrectly_extends_interface_1: { code: 2430, category: 1 /* Error */, key: "Interface '{0}' incorrectly extends interface '{1}'." }, Enum_name_cannot_be_0: { code: 2431, category: 1 /* Error */, key: "Enum name cannot be '{0}'" }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: 1 /* Error */, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, @@ -286,7 +279,9 @@ var ts; Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: 1 /* Error */, key: "Left-hand side of assignment expression cannot be a constant.", isEarly: true }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: 1 /* Error */, key: "Cannot redeclare block-scoped variable '{0}'.", isEarly: true }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: 1 /* Error */, key: "An enum member cannot have a numeric name." }, - Type_alias_0_circularly_references_itself: { code: 2453, category: 1 /* Error */, key: "Type alias '{0}' circularly references itself." }, + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: 1 /* Error */, key: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: 1 /* Error */, key: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, + Type_alias_0_circularly_references_itself: { code: 2456, category: 1 /* Error */, key: "Type alias '{0}' circularly references itself." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: 1 /* Error */, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4001, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, @@ -2130,6 +2125,12 @@ var ts; }; } ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + Debug.assert(!headChain.next); + headChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; function flattenDiagnosticChain(file, start, length, diagnosticChain, newLine) { Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); @@ -9149,6 +9150,7 @@ var ts; var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var inferenceFailureType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); var globals = {}; @@ -9322,21 +9324,100 @@ var ts; } } function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { - var errorLocation = location; var result; var lastLocation; - var memberWithInitializerThatReferencesIdentifierFromConstructor; - function returnResolvedSymbol(s) { - if (s && memberWithInitializerThatReferencesIdentifierFromConstructor) { - var propertyName = memberWithInitializerThatReferencesIdentifierFromConstructor.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.identifierToString(propertyName), nameArg); + var propertyWithInvalidInitializer; + var errorLocation = location; + loop: while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = getSymbol(location.locals, name, meaning)) { + break loop; + } + } + switch (location.kind) { + case 186 /* SourceFile */: + if (!ts.isExternalModule(location)) + break; + case 181 /* ModuleDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & ts.SymbolFlags.ModuleMember)) { + break loop; + } + break; + case 180 /* EnumDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 120 /* Property */: + if (location.parent.kind === 177 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (getSymbol(ctor.locals, name, meaning & ts.SymbolFlags.Value)) { + propertyWithInvalidInitializer = location; + } + } + } + break; + case 177 /* ClassDeclaration */: + case 178 /* InterfaceDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & ts.SymbolFlags.Type)) { + if (lastLocation && lastLocation.flags & 128 /* Static */) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + break; + case 121 /* Method */: + case 122 /* Constructor */: + case 123 /* GetAccessor */: + case 124 /* SetAccessor */: + case 175 /* FunctionDeclaration */: + case 145 /* ArrowFunction */: + if (name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 144 /* FunctionExpression */: + if (name === "arguments") { + result = argumentsSymbol; + break loop; + } + var id = location.name; + if (id && name === id.text) { + result = location.symbol; + break loop; + } + break; + case 171 /* CatchBlock */: + var id = location.variable; + if (name === id.text) { + result = location.symbol; + break loop; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (!result) { + result = getSymbol(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.identifierToString(nameArg)); + } + return undefined; + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.identifierToString(propertyName), typeof nameArg === "string" ? nameArg : ts.identifierToString(nameArg)); return undefined; } - if (!s && nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, nameArg); - } - if (s && s.flags & 2 /* BlockScopedVariable */) { - var declaration = ts.forEach(s.declarations, function (d) { return d.flags & ts.NodeFlags.BlockScoped ? d : undefined; }); + if (result.flags & 2 /* BlockScopedVariable */) { + var declaration = ts.forEach(result.declarations, function (d) { return d.flags & ts.NodeFlags.BlockScoped ? d : undefined; }); ts.Debug.assert(declaration, "Block-scoped variable declaration is undefined"); var declarationSourceFile = ts.getSourceFileOfNode(declaration); var referenceSourceFile = ts.getSourceFileOfNode(errorLocation); @@ -9352,83 +9433,8 @@ var ts; } } } - return s; } - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - if (result = getSymbol(location.locals, name, meaning)) { - return returnResolvedSymbol(result); - } - } - switch (location.kind) { - case 186 /* SourceFile */: - if (!ts.isExternalModule(location)) - break; - case 181 /* ModuleDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & ts.SymbolFlags.ModuleMember)) { - return returnResolvedSymbol(result); - } - break; - case 180 /* EnumDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { - return returnResolvedSymbol(result); - } - break; - case 120 /* Property */: - if (location.parent.kind === 177 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (getSymbol(ctor.locals, name, meaning & ts.SymbolFlags.Value)) { - memberWithInitializerThatReferencesIdentifierFromConstructor = location; - } - } - } - break; - case 177 /* ClassDeclaration */: - case 178 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & ts.SymbolFlags.Type)) { - if (lastLocation && lastLocation.flags & 128 /* Static */) { - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - else { - return returnResolvedSymbol(result); - } - } - break; - case 121 /* Method */: - case 122 /* Constructor */: - case 123 /* GetAccessor */: - case 124 /* SetAccessor */: - case 175 /* FunctionDeclaration */: - case 145 /* ArrowFunction */: - if (name === "arguments") { - return returnResolvedSymbol(argumentsSymbol); - } - break; - case 144 /* FunctionExpression */: - if (name === "arguments") { - return returnResolvedSymbol(argumentsSymbol); - } - var id = location.name; - if (id && name === id.text) { - return returnResolvedSymbol(location.symbol); - } - break; - case 171 /* CatchBlock */: - var id = location.variable; - if (name === id.text) { - return returnResolvedSymbol(location.symbol); - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result = getSymbol(globals, name, meaning)) { - return returnResolvedSymbol(result); - } - return returnResolvedSymbol(undefined); + return result; } function resolveImport(symbol) { ts.Debug.assert((symbol.flags & 16777216 /* Import */) !== 0, "Should only get Imports here."); @@ -9470,7 +9476,7 @@ var ts; } function resolveEntityName(location, name, meaning) { if (name.kind === 59 /* Identifier */) { - var symbol = resolveName(location, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(name)); + var symbol = resolveName(location, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, name); if (!symbol) { return; } @@ -9556,7 +9562,7 @@ var ts; } if (node.exportName.text) { var meaning = ts.SymbolFlags.Value | ts.SymbolFlags.Type | ts.SymbolFlags.Namespace; - var exportSymbol = resolveName(node, node.exportName.text, meaning, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(node.exportName)); + var exportSymbol = resolveName(node, node.exportName.text, meaning, ts.Diagnostics.Cannot_find_name_0, node.exportName); } } symbolLinks.exportAssignSymbol = exportSymbol || unknownSymbol; @@ -9827,10 +9833,9 @@ var ts; } function isImportDeclarationEntityNameReferenceDeclarationVisibile(entityName) { var firstIdentifier = getFirstIdentifier(entityName); - var firstIdentifierName = ts.identifierToString(firstIdentifier); - var symbolOfNameSpace = resolveName(entityName.parent, firstIdentifier.text, ts.SymbolFlags.Namespace, ts.Diagnostics.Cannot_find_name_0, firstIdentifierName); + var symbolOfNameSpace = resolveName(entityName.parent, firstIdentifier.text, ts.SymbolFlags.Namespace, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); var hasNamespaceDeclarationsVisibile = hasVisibleDeclarations(symbolOfNameSpace); - return hasNamespaceDeclarationsVisibile ? { accessibility: 0 /* Accessible */, aliasesToMakeVisible: hasNamespaceDeclarationsVisibile.aliasesToMakeVisible } : { accessibility: 1 /* NotAccessible */, errorSymbolName: firstIdentifierName }; + return hasNamespaceDeclarationsVisibile ? { accessibility: 0 /* Accessible */, aliasesToMakeVisible: hasNamespaceDeclarationsVisibile.aliasesToMakeVisible } : { accessibility: 1 /* NotAccessible */, errorSymbolName: ts.identifierToString(firstIdentifier) }; } function releaseStringWriter(writer) { writer.clear(); @@ -11730,27 +11735,27 @@ var ts; var assignableRelation = {}; var identityRelation = {}; function isTypeIdenticalTo(source, target) { - return checkTypeRelatedTo(source, target, identityRelation, undefined, undefined, undefined); + return checkTypeRelatedTo(source, target, identityRelation, undefined); } function isTypeSubtypeOf(source, target) { - return checkTypeSubtypeOf(source, target, undefined, undefined, undefined); + return checkTypeSubtypeOf(source, target, undefined); } - function checkTypeSubtypeOf(source, target, errorNode, chainedMessage, terminalMessage) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, chainedMessage, terminalMessage); + function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } function isTypeAssignableTo(source, target) { - return checkTypeAssignableTo(source, target, undefined, undefined, undefined); + return checkTypeAssignableTo(source, target, undefined); } - function checkTypeAssignableTo(source, target, errorNode, chainedMessage, terminalMessage) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, chainedMessage, terminalMessage); + function checkTypeAssignableTo(source, target, errorNode, headMessage) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); } function isTypeRelatedTo(source, target, relation) { - return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + return checkTypeRelatedTo(source, target, relation, undefined); } function isSignatureAssignableTo(source, target) { var sourceType = getOrCreateTypeFromSignature(source); var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined, undefined, undefined); + return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined); } function isPropertyIdenticalTo(sourceProp, targetProp) { return isPropertyIdenticalToRecursive(sourceProp, targetProp, false, function (s, t, _reportErrors) { return isTypeIdenticalTo(s, t); }); @@ -11780,7 +11785,7 @@ var ts; var typeName1 = typeToString(existing.containingType); var typeName2 = typeToString(base); var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon, typeToString(type), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); } } @@ -11804,7 +11809,7 @@ var ts; return isOptionalProperty(sourceProp) === isOptionalProperty(targetProp) && relate(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); } } - function checkTypeRelatedTo(source, target, relation, errorNode, chainedMessage, terminalMessage) { + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; var sourceStack; var targetStack; @@ -11812,11 +11817,14 @@ var ts; var depth = 0; var overflow = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, chainedMessage, terminalMessage); + var result = isRelatedToWithCustomErrors(source, target, errorNode !== undefined, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); } return result; @@ -11824,9 +11832,9 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function isRelatedTo(source, target, reportErrors) { - return isRelatedToWithCustomErrors(source, target, reportErrors, undefined, undefined); + return isRelatedToWithCustomErrors(source, target, reportErrors, undefined); } - function isRelatedToWithCustomErrors(source, target, reportErrors, chainedMessage, terminalMessage) { + function isRelatedToWithCustomErrors(source, target, reportErrors, headMessage) { if (relation === identityRelation) { if (source === target) return true; @@ -11881,11 +11889,9 @@ var ts; } } if (reportErrors) { - chainedMessage = chainedMessage || ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Colon; - terminalMessage = terminalMessage || ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - var diagnosticKey = errorInfo ? chainedMessage : terminalMessage; - ts.Debug.assert(diagnosticKey); - reportError(diagnosticKey, typeToString(source), typeToString(target)); + headMessage = headMessage || ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + ts.Debug.assert(headMessage); + reportError(headMessage, typeToString(source), typeToString(target)); } return false; } @@ -12044,7 +12050,7 @@ var ts; } if (!isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors)) { if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible_Colon, symbolToString(targetProp)); + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); } return false; } @@ -12137,7 +12143,7 @@ var ts; if (!isRelatedTo(s, t, reportErrors)) { if (!isRelatedTo(t, s, false)) { if (reportErrors) { - reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible_Colon, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); + reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); } return false; } @@ -12178,7 +12184,7 @@ var ts; } if (!isRelatedTo(sourceType, targetType, reportErrors)) { if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible_Colon); + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } return false; } @@ -12207,7 +12213,7 @@ var ts; } if (!compatible) { if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible_Colon); + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } return false; } @@ -12261,6 +12267,32 @@ var ts; function getCommonSupertype(types) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } + function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { + var bestSupertype; + var bestSupertypeDownfallType; + var bestSupertypeScore = 0; + for (var i = 0; i < types.length; i++) { + var score = 0; + var downfallType = undefined; + for (var j = 0; j < types.length; j++) { + if (isTypeSubtypeOf(types[j], types[i])) { + score++; + } + else if (!downfallType) { + downfallType = types[j]; + } + } + if (score > bestSupertypeScore) { + bestSupertype = types[i]; + bestSupertypeDownfallType = downfallType; + bestSupertypeScore = score; + } + if (bestSupertypeScore === types.length - 1) { + break; + } + } + checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + } function isTypeOfObjectLiteral(type) { return (type.flags & 32768 /* Anonymous */) && type.symbol && (type.symbol.flags & 2048 /* ObjectLiteral */) ? true : false; } @@ -12499,27 +12531,28 @@ var ts; } } function getInferredType(context, index) { - var result = context.inferredTypes[index]; - if (!result) { + var inferredType = context.inferredTypes[index]; + if (!inferredType) { var inferences = context.inferences[index]; if (inferences.length) { var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); - var inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : undefinedType; + inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : inferenceFailureType; } else { inferredType = emptyObjectType; } - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - var result = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; - context.inferredTypes[index] = result; + if (inferredType !== inferenceFailureType) { + var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + } + context.inferredTypes[index] = inferredType; } - return result; + return inferredType; } function getInferredTypes(context) { for (var i = 0; i < context.inferredTypes.length; i++) { getInferredType(context, i); } - context.inferences = undefined; return context.inferredTypes; } function hasAncestor(node, kind) { @@ -12528,7 +12561,7 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = resolveName(node, node.text, ts.SymbolFlags.Value | 2097152 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(node)) || unknownSymbol; + links.resolvedSymbol = resolveName(node, node.text, ts.SymbolFlags.Value | 2097152 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node) || unknownSymbol; } return links.resolvedSymbol; } @@ -13336,21 +13369,29 @@ var ts; } } var inferredTypes = getInferredTypes(context); - return ts.contains(inferredTypes, undefinedType) ? undefined : inferredTypes; + context.failedTypeParameterIndex = ts.indexOf(inferredTypes, inferenceFailureType); + for (var i = 0; i < inferredTypes.length; i++) { + if (inferredTypes[i] === inferenceFailureType) { + inferredTypes[i] = unknownType; + } + } + return context; } - function checkTypeArguments(signature, typeArguments) { + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors) { var typeParameters = signature.typeParameters; - var result = []; + var typeArgumentsAreAssignable = true; for (var i = 0; i < typeParameters.length; i++) { var typeArgNode = typeArguments[i]; var typeArgument = getTypeFromTypeNode(typeArgNode); - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint && fullTypeCheck) { - checkTypeAssignableTo(typeArgument, constraint, typeArgNode, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1_Colon, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + typeArgumentResultTypes[i] = typeArgument; + if (typeArgumentsAreAssignable) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } } - result.push(typeArgument); } - return result; + return typeArgumentsAreAssignable; } function checkApplicableSignature(node, signature, relation, excludeArgument, reportErrors) { if (node.arguments) { @@ -13361,7 +13402,7 @@ var ts; } var paramType = getTypeAtPosition(signature, i); var argType = arg.kind === 7 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - var isValidArgument = checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1); + var isValidArgument = checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1); if (!isValidArgument) { return false; } @@ -13386,40 +13427,36 @@ var ts; excludeArgument[i] = true; } } - var relation = candidates.length === 1 ? assignableRelation : subtypeRelation; - var lastCandidate; - while (true) { - for (var i = 0; i < candidates.length; i++) { - if (!signatureHasCorrectArity(node, candidates[i])) { - continue; - } - while (true) { - var candidate = candidates[i]; - if (candidate.typeParameters) { - var typeArguments = node.typeArguments ? checkTypeArguments(candidate, node.typeArguments) : inferTypeArguments(candidate, args, excludeArgument); - if (!typeArguments) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArguments); - } - lastCandidate = candidate; - if (!checkApplicableSignature(node, candidate, relation, excludeArgument, false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - } - if (relation === assignableRelation) { - break; - } - relation = assignableRelation; + var candidateForArgumentError; + var candidateForTypeArgumentError; + var resultOfFailedInference; + var result; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, excludeArgument); } - if (lastCandidate) { - checkApplicableSignature(node, lastCandidate, relation, undefined, true); + if (!result) { + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + resultOfFailedInference = undefined; + result = chooseOverload(candidates, assignableRelation, excludeArgument); + } + if (result) { + return result; + } + if (candidateForArgumentError) { + checkApplicableSignature(node, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForTypeArgumentError) { + if (node.typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true); + } + else { + ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); + var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; + var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex]; + var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + reportNoCommonSupertypeError(inferenceCandidates, node.func, diagnosticChainHead); + } } else { error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); @@ -13432,6 +13469,60 @@ var ts; } } return resolveErrorCall(node); + function chooseOverload(candidates, relation, excludeArgument) { + for (var i = 0; i < candidates.length; i++) { + if (!signatureHasCorrectArity(node, candidates[i])) { + continue; + } + var originalCandidate = candidates[i]; + var inferenceResult; + while (true) { + var candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes; + var typeArgumentsAreValid; + if (node.typeArguments) { + typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentsAreValid = checkTypeArguments(candidate, node.typeArguments, typeArgumentTypes, false); + } + else { + inferenceResult = inferTypeArguments(candidate, args, excludeArgument); + typeArgumentsAreValid = inferenceResult.failedTypeParameterIndex < 0; + typeArgumentTypes = inferenceResult.inferredTypes; + } + if (!typeArgumentsAreValid) { + break; + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, candidate, relation, excludeArgument, false)) { + break; + } + var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; + if (index < 0) { + return candidate; + } + excludeArgument[index] = false; + } + if (originalCandidate.typeParameters) { + var instantiatedCandidate = candidate; + if (typeArgumentsAreValid) { + candidateForArgumentError = instantiatedCandidate; + } + else { + candidateForTypeArgumentError = originalCandidate; + if (!node.typeArguments) { + resultOfFailedInference = inferenceResult; + } + } + } + else { + ts.Debug.assert(originalCandidate === candidate); + candidateForArgumentError = originalCandidate; + } + } + return undefined; + } function collectCandidates() { var result = candidates; var lastParent; @@ -13555,7 +13646,7 @@ var ts; if (fullTypeCheck && targetType !== unknownType) { var widenedType = getWidenedType(exprType, true); if (!(isTypeAssignableTo(targetType, widenedType))) { - checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); + checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } return targetType; @@ -13685,7 +13776,7 @@ var ts; else { var exprType = checkExpression(node.body); if (node.type) { - checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined, undefined); + checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined); } checkFunctionExpressionBodies(node.body); } @@ -13915,7 +14006,7 @@ var ts; if (fullTypeCheck && operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment) { var ok = checkReferenceExpression(node.left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); if (ok) { - checkTypeAssignableTo(valueType, leftType, node.left, undefined, undefined); + checkTypeAssignableTo(valueType, leftType, node.left, undefined); } } } @@ -14219,7 +14310,7 @@ var ts; var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); if (fullTypeCheck && constraint) { var typeArgument = type.typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1_Colon, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } } @@ -14657,7 +14748,7 @@ var ts; } if (node.initializer) { if (!(getNodeLinks(node.initializer).flags & 1 /* TypeChecked */)) { - checkTypeAssignableTo(checkAndMarkExpression(node.initializer), type, node, undefined, undefined); + checkTypeAssignableTo(checkAndMarkExpression(node.initializer), type, node, undefined); } checkCollisionWithConstDeclarations(node); } @@ -14738,7 +14829,7 @@ var ts; var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); var checkAssignability = func.type || (func.kind === 123 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(func.symbol, 124 /* SetAccessor */))); if (checkAssignability) { - checkTypeAssignableTo(checkExpression(node.expression), returnType, node.expression, undefined, undefined); + checkTypeAssignableTo(checkExpression(node.expression), returnType, node.expression, undefined); } else if (func.kind == 122 /* Constructor */) { if (!isTypeAssignableTo(checkExpression(node.expression), returnType)) { @@ -14759,7 +14850,7 @@ var ts; if (fullTypeCheck && clause.expression) { var caseType = checkExpression(clause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { - checkTypeAssignableTo(caseType, expressionType, clause.expression, undefined, undefined); + checkTypeAssignableTo(caseType, expressionType, clause.expression, undefined); } } checkBlock(clause); @@ -14866,9 +14957,9 @@ var ts; if (type.baseTypes.length) { if (fullTypeCheck) { var baseType = type.baseTypes[0]; - checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1_Colon, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); var staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseType.symbol !== resolveEntityName(node, node.baseType.typeName, ts.SymbolFlags.Value)) { error(node.baseType, ts.Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); } @@ -14884,7 +14975,7 @@ var ts; if (t !== unknownType) { var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { - checkTypeAssignableTo(type, t, node.name, ts.Diagnostics.Class_0_incorrectly_implements_interface_1_Colon, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + checkTypeAssignableTo(type, t, node.name, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -14989,7 +15080,7 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); if (checkInheritedPropertiesAreIdentical(type, node.name)) { ts.forEach(type.baseTypes, function (baseType) { - checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1_Colon, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); }); checkIndexConstraints(type); } @@ -15034,7 +15125,7 @@ var ts; if (initializer) { autoValue = getConstantValueForExpression(initializer); if (autoValue === undefined && !ambient) { - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined, undefined); + checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined); } } else if (ambient) { @@ -28155,9 +28246,6 @@ var ts; listItemIndex: 0 }; } - if (node.kind === 20 /* GreaterThanToken */ || node.kind === 12 /* CloseParenToken */ || node === parent.func) { - return undefined; - } return ts.findListItemInfo(node); } function getContainingArgumentInfo(node) { @@ -28282,6 +28370,9 @@ var ts; (function (ts) { function findListItemInfo(node) { var syntaxList = findContainingList(node); + if (!syntaxList) { + return undefined; + } var children = syntaxList.getChildren(); var index = ts.indexOf(children, node); return { @@ -28300,9 +28391,6 @@ var ts; return c; } }); - if (!syntaxList) { - ts.Debug.assert(findChildOfKind(node.parent, 188 /* SyntaxList */), "Node of kind " + ts.SyntaxKind[node.parent.kind] + " has no list children"); - } return syntaxList; } ts.findContainingList = findContainingList; @@ -28343,11 +28431,12 @@ var ts; var child = current.getChildAt(i); var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); if (start <= position) { - if (position < child.getEnd()) { + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { current = child; continue outer; } - else if (includeItemAtEndPosition && child.getEnd() === position) { + else if (includeItemAtEndPosition && end === position) { var previousToken = findPrecedingToken(position, sourceFile, child); if (previousToken && includeItemAtEndPosition(previousToken)) { return previousToken; @@ -28402,7 +28491,7 @@ var ts; for (var i = 0, len = children.length; i < len; ++i) { var child = children[i]; if (nodeHasTokens(child)) { - if (position < child.end) { + if (position <= child.end) { if (child.getStart(sourceFile) >= position) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -30423,7 +30512,7 @@ var ts; SmartIndenter.getIndentation = getIndentation; function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { var commaItemInfo = ts.findListItemInfo(commaToken); - ts.Debug.assert(commaItemInfo.listItemIndex > 0); + ts.Debug.assert(commaItemInfo && commaItemInfo.listItemIndex > 0); return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { @@ -32078,6 +32167,9 @@ var ts; NodeObject.prototype.getFullText = function (sourceFile) { return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); }; + NodeObject.prototype.getText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + }; NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { scanner.setTextPos(pos); while (pos < end) { @@ -32473,15 +32565,9 @@ var ts; SourceFileObject.prototype.getPositionFromLineAndCharacter = function (line, character) { return -1; }; - SourceFileObject.prototype.getSourceUnit = function () { - return this.getSyntaxTree().sourceUnit(); - }; SourceFileObject.prototype.getScriptSnapshot = function () { return this.scriptSnapshot; }; - SourceFileObject.prototype.getLineMap = function () { - return this.getSyntaxTree().lineMap(); - }; SourceFileObject.prototype.getNamedDeclarations = function () { if (!this.namedDeclarations) { var sourceFile = this; @@ -32537,19 +32623,10 @@ var ts; } return this.namedDeclarations; }; - SourceFileObject.prototype.getSyntaxTree = function () { - if (!this.syntaxTree) { - var start = new Date().getTime(); - this.syntaxTree = TypeScript.Parser.parse(this.filename, TypeScript.SimpleText.fromScriptSnapshot(this.scriptSnapshot), this.languageVersion, this.isDeclareFile()); - var time = new Date().getTime() - start; - } - return this.syntaxTree; - }; SourceFileObject.prototype.isDeclareFile = function () { return TypeScript.isDTSFile(this.filename); }; SourceFileObject.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { - var oldSyntaxTree = this.syntaxTree; if (textChangeRange && ts.Debug.shouldAssert(1 /* Normal */)) { var oldText = this.scriptSnapshot; var newText = scriptSnapshot; @@ -32563,14 +32640,11 @@ var ts; TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); } } - var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); - var newSyntaxTree = !textChangeRange || !oldSyntaxTree ? TypeScript.Parser.parse(this.filename, text, this.languageVersion, TypeScript.isDTSFile(this.filename)) : TypeScript.IncrementalParser.parse(oldSyntaxTree, textChangeRange, text); - return SourceFileObject.createSourceFileObject(this.filename, scriptSnapshot, this.languageVersion, version, isOpen, newSyntaxTree); + return SourceFileObject.createSourceFileObject(this.filename, scriptSnapshot, this.languageVersion, version, isOpen); }; - SourceFileObject.createSourceFileObject = function (filename, scriptSnapshot, languageVersion, version, isOpen, syntaxTree) { + SourceFileObject.createSourceFileObject = function (filename, scriptSnapshot, languageVersion, version, isOpen) { var newSourceFile = ts.createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), languageVersion, version, isOpen); newSourceFile.scriptSnapshot = scriptSnapshot; - newSourceFile.syntaxTree = syntaxTree; return newSourceFile; }; return SourceFileObject; @@ -32992,22 +33066,36 @@ var ts; } SyntaxTreeCache.prototype.initialize = function (filename) { ts.Debug.assert(!!this.currentFileSyntaxTree === !!this.currentSourceFile); + var start = new Date().getTime(); this.hostCache = new HostCache(this.host); + this.host.log("SyntaxTreeCache.Initialize: new HostCache: " + (new Date().getTime() - start)); var version = this.hostCache.getVersion(filename); var syntaxTree = null; var sourceFile; if (this.currentFileSyntaxTree === null || this.currentFilename !== filename) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); + var start = new Date().getTime(); syntaxTree = this.createSyntaxTree(filename, scriptSnapshot); + this.host.log("SyntaxTreeCache.Initialize: createSyntaxTree: " + (new Date().getTime() - start)); + var start = new Date().getTime(); sourceFile = createSourceFileFromScriptSnapshot(filename, scriptSnapshot, getDefaultCompilerOptions(), version, true); + this.host.log("SyntaxTreeCache.Initialize: createSourceFile: " + (new Date().getTime() - start)); + var start = new Date().getTime(); fixupParentReferences(sourceFile); + this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } else if (this.currentFileVersion !== version) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); + var start = new Date().getTime(); syntaxTree = this.updateSyntaxTree(filename, scriptSnapshot, this.currentSourceFile.getScriptSnapshot(), this.currentFileSyntaxTree, this.currentFileVersion); + this.host.log("SyntaxTreeCache.Initialize: updateSyntaxTree: " + (new Date().getTime() - start)); var editRange = this.hostCache.getChangeRange(filename, this.currentFileVersion, this.currentSourceFile.getScriptSnapshot()); + var start = new Date().getTime(); sourceFile = !editRange ? createSourceFileFromScriptSnapshot(filename, scriptSnapshot, getDefaultCompilerOptions(), version, true) : this.currentSourceFile.update(scriptSnapshot, version, true, editRange); + this.host.log("SyntaxTreeCache.Initialize: updateSourceFile: " + (new Date().getTime() - start)); + var start = new Date().getTime(); fixupParentReferences(sourceFile); + this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } if (syntaxTree !== null) { ts.Debug.assert(sourceFile); @@ -33212,19 +33300,19 @@ var ts; return node.parent.kind === 117 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node.parent.kind === 138 /* PropertyAccess */ && node.parent.right === node; + return node && node.parent && node.parent.kind === 138 /* PropertyAccess */ && node.parent.right === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 140 /* CallExpression */ && node.parent.func === node; + return node && node.parent && node.parent.kind === 140 /* CallExpression */ && node.parent.func === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 141 /* NewExpression */ && node.parent.func === node; + return node && node.parent && node.parent.kind === 141 /* NewExpression */ && node.parent.func === node; } function isNameOfModuleDeclaration(node) { return node.parent.kind === 181 /* ModuleDeclaration */ && node.parent.name === node; @@ -33255,6 +33343,27 @@ var ts; function isNameOfExternalModuleImportOrDeclaration(node) { return node.kind === 7 /* StringLiteral */ && (isNameOfModuleDeclaration(node) || (node.parent.kind === 183 /* ImportDeclaration */ && node.parent.externalModuleName === node)); } + function isInsideComment(sourceFile, token, position) { + return position <= token.getStart(sourceFile) && (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); + function isInsideCommentRange(comments) { + return ts.forEach(comments, function (comment) { + if (comment.pos < position && position < comment.end) { + return true; + } + else if (position === comment.end) { + var text = sourceFile.text; + var width = comment.end - comment.pos; + if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { + return true; + } + else { + return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && text.charCodeAt(comment.end - 2) === 42 /* asterisk */); + } + } + return false; + }); + } + } var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0x0] = "None"; @@ -33456,6 +33565,93 @@ var ts; }; } function getCompletionsAtPosition(filename, position, isMemberCompletion) { + synchronizeHostData(); + filename = TypeScript.switchToForwardSlashes(filename); + var sourceFile = getSourceFile(filename); + var currentToken = ts.getTokenAtPosition(sourceFile, position); + if (isInsideComment(sourceFile, currentToken, position)) { + host.log("Returning an empty list because completion was inside a comment."); + return undefined; + } + var previousToken = ts.findPrecedingToken(position, sourceFile); + if (previousToken && position <= previousToken.end && previousToken.kind === 59 /* Identifier */) { + previousToken = ts.findPrecedingToken(previousToken.pos, sourceFile); + } + if (previousToken && isCompletionListBlocker(previousToken)) { + host.log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var node; + var isRightOfDot; + if (previousToken && previousToken.kind === 15 /* DotToken */ && (previousToken.parent.kind === 138 /* PropertyAccess */ || previousToken.parent.kind === 117 /* QualifiedName */)) { + node = previousToken.parent.left; + isRightOfDot = true; + } + else { + node = currentToken; + isRightOfDot = false; + } + activeCompletionSession = { + filename: filename, + position: position, + entries: [], + symbols: {}, + typeChecker: typeInfoResolver + }; + if (isRightOfDot) { + var symbols = []; + isMemberCompletion = true; + if (node.kind === 59 /* Identifier */ || node.kind === 117 /* QualifiedName */ || node.kind === 138 /* PropertyAccess */) { + var symbol = typeInfoResolver.getSymbolInfo(node); + if (symbol && symbol.flags & 16777216 /* Import */) { + symbol = typeInfoResolver.getAliasedSymbol(symbol); + } + if (symbol && symbol.flags & ts.SymbolFlags.HasExports) { + ts.forEachValue(symbol.exports, function (symbol) { + if (typeInfoResolver.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + } + var type = typeInfoResolver.getTypeOfNode(node); + if (type) { + ts.forEach(type.getApparentProperties(), function (symbol) { + if (typeInfoResolver.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + getCompletionEntriesFromSymbols(symbols, activeCompletionSession); + } + else { + var containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(previousToken); + if (containingObjectLiteral) { + isMemberCompletion = true; + var contextualType = typeInfoResolver.getContextualType(containingObjectLiteral); + if (!contextualType) { + return undefined; + } + var contextualTypeMembers = typeInfoResolver.getPropertiesOfType(contextualType); + if (contextualTypeMembers && contextualTypeMembers.length > 0) { + var filteredMembers = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); + getCompletionEntriesFromSymbols(filteredMembers, activeCompletionSession); + } + } + else { + isMemberCompletion = false; + var symbolMeanings = ts.SymbolFlags.Type | ts.SymbolFlags.Value | ts.SymbolFlags.Namespace | 16777216 /* Import */; + var symbols = typeInfoResolver.getSymbolsInScope(node, symbolMeanings); + getCompletionEntriesFromSymbols(symbols, activeCompletionSession); + } + } + if (!isMemberCompletion) { + Array.prototype.push.apply(activeCompletionSession.entries, keywordCompletions); + } + return { + isMemberCompletion: isMemberCompletion, + entries: activeCompletionSession.entries + }; function getCompletionEntriesFromSymbols(symbols, session) { ts.forEach(symbols, function (symbol) { var entry = createCompletionEntry(symbol, session.typeChecker); @@ -33465,23 +33661,34 @@ var ts; } }); } - function isCompletionListBlocker(sourceUnit, position) { - if (position < 0 || position > TypeScript.fullWidth(sourceUnit)) { - return true; - } - return TypeScript.Syntax.isEntirelyInsideComment(sourceUnit, position) || TypeScript.Syntax.isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) || isIdentifierDefinitionLocation(sourceUnit, position) || isRightOfIllegalDot(sourceUnit, position); + function isCompletionListBlocker(previousToken) { + return isInStringOrRegularExpressionLiteral(previousToken) || isIdentifierDefinitionLocation(previousToken) || isRightOfIllegalDot(previousToken); } - function getContainingObjectLiteralApplicableForCompletion(sourceUnit, position) { - var previousToken = getNonIdentifierCompleteTokenOnLeft(sourceUnit, position); + function isInStringOrRegularExpressionLiteral(previousToken) { + if (previousToken.kind === 7 /* StringLiteral */) { + var start = previousToken.getStart(); + var end = previousToken.getEnd(); + if (start < position && position < end) { + return true; + } + else if (position === end) { + var width = end - start; + var text = previousToken.getSourceFile().text; + return width <= 1 || text.charCodeAt(start) !== text.charCodeAt(end - 1) || text.charCodeAt(end - 2) === 92 /* backslash */; + } + } + else if (previousToken.kind === 8 /* RegularExpressionLiteral */) { + return previousToken.getStart() < position && position < previousToken.getEnd(); + } + return false; + } + function getContainingObjectLiteralApplicableForCompletion(previousToken) { if (previousToken) { var parent = previousToken.parent; - switch (previousToken.kind()) { - case 70 /* OpenBraceToken */: - case 79 /* CommaToken */: - if (parent && parent.kind() === 2 /* SeparatedList */) { - parent = parent.parent; - } - if (parent && parent.kind() === 216 /* ObjectLiteralExpression */) { + switch (previousToken.kind) { + case 9 /* OpenBraceToken */: + case 18 /* CommaToken */: + if (parent && parent.kind === 136 /* ObjectLiteral */) { return parent; } break; @@ -33489,69 +33696,68 @@ var ts; } return undefined; } - function isIdentifierDefinitionLocation(sourceUnit, position) { - var positionedToken = getNonIdentifierCompleteTokenOnLeft(sourceUnit, position); - if (positionedToken) { - var containingNodeKind = TypeScript.Syntax.containingNode(positionedToken) && TypeScript.Syntax.containingNode(positionedToken).kind(); - switch (positionedToken.kind()) { - case 79 /* CommaToken */: - return containingNodeKind === 228 /* ParameterList */ || containingNodeKind === 225 /* VariableDeclaration */ || containingNodeKind === 133 /* EnumDeclaration */; - case 72 /* OpenParenToken */: - return containingNodeKind === 228 /* ParameterList */ || containingNodeKind === 237 /* CatchClause */; - case 70 /* OpenBraceToken */: - return containingNodeKind === 133 /* EnumDeclaration */; - case 57 /* PublicKeyword */: - case 55 /* PrivateKeyword */: - case 58 /* StaticKeyword */: - case 77 /* DotDotDotToken */: - return containingNodeKind === 243 /* Parameter */; - case 44 /* ClassKeyword */: - case 65 /* ModuleKeyword */: - case 46 /* EnumKeyword */: - case 52 /* InterfaceKeyword */: - case 27 /* FunctionKeyword */: - case 40 /* VarKeyword */: - case 64 /* GetKeyword */: - case 68 /* SetKeyword */: + function isFunction(kind) { + switch (kind) { + case 144 /* FunctionExpression */: + case 145 /* ArrowFunction */: + case 175 /* FunctionDeclaration */: + case 121 /* Method */: + case 122 /* Constructor */: + case 123 /* GetAccessor */: + case 124 /* SetAccessor */: + case 125 /* CallSignature */: + case 126 /* ConstructSignature */: + case 127 /* IndexSignature */: + return true; + } + return false; + } + function isIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + switch (previousToken.kind) { + case 18 /* CommaToken */: + return containingNodeKind === 174 /* VariableDeclaration */ || containingNodeKind === 152 /* VariableStatement */ || containingNodeKind === 180 /* EnumDeclaration */ || isFunction(containingNodeKind); + case 11 /* OpenParenToken */: + return containingNodeKind === 171 /* CatchBlock */ || isFunction(containingNodeKind); + case 9 /* OpenBraceToken */: + return containingNodeKind === 180 /* EnumDeclaration */ || containingNodeKind === 178 /* InterfaceDeclaration */; + case 17 /* SemicolonToken */: + return containingNodeKind === 120 /* Property */ && previousToken.parent.parent.kind === 178 /* InterfaceDeclaration */; + case 102 /* PublicKeyword */: + case 100 /* PrivateKeyword */: + case 103 /* StaticKeyword */: + case 16 /* DotDotDotToken */: + return containingNodeKind === 119 /* Parameter */; + case 63 /* ClassKeyword */: + case 110 /* ModuleKeyword */: + case 71 /* EnumKeyword */: + case 97 /* InterfaceKeyword */: + case 77 /* FunctionKeyword */: + case 92 /* VarKeyword */: + case 109 /* GetKeyword */: + case 113 /* SetKeyword */: return true; } - switch (positionedToken.text()) { + switch (previousToken.getText()) { case "class": case "interface": case "enum": case "module": + case "function": + case "var": return true; } } return false; } - function getNonIdentifierCompleteTokenOnLeft(sourceUnit, position) { - var positionedToken = TypeScript.Syntax.findCompleteTokenOnLeft(sourceUnit, position, true); - if (positionedToken && position === TypeScript.end(positionedToken) && positionedToken.kind() == 10 /* EndOfFileToken */) { - positionedToken = TypeScript.previousToken(positionedToken, true); - } - if (positionedToken && position === TypeScript.end(positionedToken) && positionedToken.kind() === 11 /* IdentifierName */) { - positionedToken = TypeScript.previousToken(positionedToken, true); - } - return positionedToken; - } - function isRightOfIllegalDot(sourceUnit, position) { - var positionedToken = getNonIdentifierCompleteTokenOnLeft(sourceUnit, position); - if (positionedToken) { - switch (positionedToken.kind()) { - case 76 /* DotToken */: - var leftOfDotPositionedToken = TypeScript.previousToken(positionedToken, true); - return leftOfDotPositionedToken && leftOfDotPositionedToken.kind() === 13 /* NumericLiteral */; - case 13 /* NumericLiteral */: - var text = positionedToken.text(); - return text.charAt(text.length - 1) === "."; - } + function isRightOfIllegalDot(previousToken) { + if (previousToken && previousToken.kind === 6 /* NumericLiteral */) { + var text = previousToken.getFullText(); + return text.charAt(text.length - 1) === "."; } return false; } - function isPunctuation(kind) { - return (ts.SyntaxKind.FirstPunctuation <= kind && kind <= ts.SyntaxKind.LastPunctuation); - } function filterContextualMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; @@ -33574,114 +33780,10 @@ var ts; }); return filteredMembers; } - synchronizeHostData(); - filename = TypeScript.switchToForwardSlashes(filename); - var sourceFile = getSourceFile(filename); - var sourceUnit = sourceFile.getSourceUnit(); - if (isCompletionListBlocker(sourceFile.getSyntaxTree().sourceUnit(), position)) { - host.log("Returning an empty list because completion was blocked."); - return null; - } - var node = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position, true, true); - if (node && node.kind() === 11 /* IdentifierName */ && TypeScript.start(node) === TypeScript.end(node)) { - node = node.parent; - } - var isRightOfDot = false; - if (node && node.kind() === 213 /* MemberAccessExpression */ && TypeScript.end(node.expression) < position) { - isRightOfDot = true; - node = node.expression; - } - else if (node && node.kind() === 121 /* QualifiedName */ && TypeScript.end(node.left) < position) { - isRightOfDot = true; - node = node.left; - } - else if (node && node.parent && node.kind() === 11 /* IdentifierName */ && node.parent.kind() === 213 /* MemberAccessExpression */ && node.parent.name === node) { - isRightOfDot = true; - node = node.parent.expression; - } - else if (node && node.parent && node.kind() === 11 /* IdentifierName */ && node.parent.kind() === 121 /* QualifiedName */ && node.parent.right === node) { - isRightOfDot = true; - node = node.parent.left; - } - var precedingToken = ts.findTokenOnLeftOfPosition(sourceFile, TypeScript.end(node)); - var mappedNode; - if (!precedingToken) { - mappedNode = sourceFile; - } - else if (isPunctuation(precedingToken.kind)) { - mappedNode = precedingToken.parent; - } - else { - mappedNode = precedingToken; - } - ts.Debug.assert(mappedNode, "Could not map a Fidelity node to an AST node"); - activeCompletionSession = { - filename: filename, - position: position, - entries: [], - symbols: {}, - location: mappedNode, - typeChecker: typeInfoResolver - }; - if (isRightOfDot) { - var symbols = []; - isMemberCompletion = true; - if (mappedNode.kind === 59 /* Identifier */ || mappedNode.kind === 117 /* QualifiedName */ || mappedNode.kind === 138 /* PropertyAccess */) { - var symbol = typeInfoResolver.getSymbolInfo(mappedNode); - if (symbol && symbol.flags & 16777216 /* Import */) { - symbol = typeInfoResolver.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & ts.SymbolFlags.HasExports) { - ts.forEachValue(symbol.exports, function (symbol) { - if (typeInfoResolver.isValidPropertyAccess((mappedNode.parent), symbol.name)) { - symbols.push(symbol); - } - }); - } - } - var type = typeInfoResolver.getTypeOfNode(mappedNode); - if (type) { - ts.forEach(type.getApparentProperties(), function (symbol) { - if (typeInfoResolver.isValidPropertyAccess((mappedNode.parent), symbol.name)) { - symbols.push(symbol); - } - }); - } - getCompletionEntriesFromSymbols(symbols, activeCompletionSession); - } - else { - var containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(sourceFile.getSyntaxTree().sourceUnit(), position); - if (containingObjectLiteral) { - var objectLiteral = (mappedNode.kind === 136 /* ObjectLiteral */ ? mappedNode : ts.getAncestor(mappedNode, 136 /* ObjectLiteral */)); - ts.Debug.assert(objectLiteral); - isMemberCompletion = true; - var contextualType = typeInfoResolver.getContextualType(objectLiteral); - if (!contextualType) { - return undefined; - } - var contextualTypeMembers = typeInfoResolver.getPropertiesOfType(contextualType); - if (contextualTypeMembers && contextualTypeMembers.length > 0) { - var filteredMembers = filterContextualMembersList(contextualTypeMembers, objectLiteral.properties); - getCompletionEntriesFromSymbols(filteredMembers, activeCompletionSession); - } - } - else { - isMemberCompletion = false; - var symbolMeanings = ts.SymbolFlags.Type | ts.SymbolFlags.Value | ts.SymbolFlags.Namespace | 16777216 /* Import */; - var symbols = typeInfoResolver.getSymbolsInScope(mappedNode, symbolMeanings); - getCompletionEntriesFromSymbols(symbols, activeCompletionSession); - } - } - if (!isMemberCompletion) { - Array.prototype.push.apply(activeCompletionSession.entries, keywordCompletions); - } - return { - isMemberCompletion: isMemberCompletion, - entries: activeCompletionSession.entries - }; } function getCompletionEntryDetails(filename, position, entryName) { filename = TypeScript.switchToForwardSlashes(filename); + var sourceFile = getSourceFile(filename); var session = activeCompletionSession; if (!session || session.filename !== filename || session.position !== position) { return undefined; @@ -33691,7 +33793,8 @@ var ts; var type = session.typeChecker.getTypeOfSymbol(symbol); ts.Debug.assert(type, "Could not find type for symbol"); var completionEntry = createCompletionEntry(symbol, session.typeChecker); - var displayPartsDocumentationsAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getSourceFile(filename), session.location, session.typeChecker, session.location, SemanticMeaning.All); + var location = ts.getTouchingPropertyName(sourceFile, position); + var displayPartsDocumentationsAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getSourceFile(filename), location, session.typeChecker, location, SemanticMeaning.All); return { name: entryName, kind: displayPartsDocumentationsAndSymbolKind.symbolKind, @@ -33871,12 +33974,20 @@ var ts; } var type = typeResolver.getTypeOfSymbol(symbol); if (type) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { - var callExpression; - if (location.parent.kind === 138 /* PropertyAccess */ && location.parent.right === location) { + if (location.parent && location.parent.kind === 138 /* PropertyAccess */) { + var right = location.parent.right; + if (right === location || (right && right.kind === 116 /* Missing */)) { location = location.parent; } + } + var callExpression; + if (location.kind === 140 /* CallExpression */ || location.kind === 141 /* NewExpression */) { + callExpression = location; + } + else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { callExpression = location.parent; + } + if (callExpression) { var candidateSignatures = []; signature = typeResolver.getResolvedSignature(callExpression, candidateSignatures); if (!signature && candidateSignatures.length) { @@ -34667,7 +34778,7 @@ var ts; if (symbol.getFlags() && (4 /* Property */ | 4096 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return privateDeclaration.parent; + return ts.getAncestor(privateDeclaration, 177 /* ClassDeclaration */); } } if (symbol.parent) { @@ -35546,9 +35657,14 @@ var ts; } function getIndentationAtPosition(filename, position, editorOptions) { filename = TypeScript.switchToForwardSlashes(filename); + var start = new Date().getTime(); var sourceFile = getCurrentSourceFile(filename); + host.log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + var start = new Date().getTime(); var options = new TypeScript.FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter); - return ts.formatting.SmartIndenter.getIndentation(position, sourceFile, options); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, options); + host.log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + return result; } function getFormattingManager(filename, options) { if (formattingRulesProvider == null) { @@ -35603,10 +35719,7 @@ var ts; var preamble = matchArray[1]; var matchPosition = matchArray.index + preamble.length; var token = ts.getTokenAtPosition(sourceFile, matchPosition); - if (token.getStart() <= matchPosition && matchPosition < token.getEnd()) { - continue; - } - if (!getContainingComment(ts.getTrailingCommentRanges(fileContents, token.getFullStart()), matchPosition) && !getContainingComment(ts.getLeadingCommentRanges(fileContents, token.getFullStart()), matchPosition)) { + if (!isInsideComment(sourceFile, token, matchPosition)) { continue; } var descriptor = undefined; From 32b8a0e69d474eaec92b3d39c721f1c7085dc234 Mon Sep 17 00:00:00 2001 From: Jason Freeman Date: Wed, 29 Oct 2014 12:55:18 -0700 Subject: [PATCH 4/9] Remove while true guard --- src/compiler/checker.ts | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ae371c41686..fbed37c7c30 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5469,31 +5469,29 @@ module ts { Debug.assert(!result.length); for (var i = 0; i < signatures.length; i++) { var signature = signatures[i]; - if (true) { - var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent = signature.declaration && signature.declaration.parent; - if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent === lastParent) { - pos++; - } - else { - lastParent = parent; - pos = cutoffPos; - } + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent === lastParent) { + pos++; } else { - // current declaration belongs to a different symbol - // set cutoffPos so re-orderings in the future won't change result set from 0 to cutoffPos - pos = cutoffPos = result.length; lastParent = parent; + pos = cutoffPos; } - lastSymbol = symbol; - - for (var j = result.length; j > pos; j--) { - result[j] = result[j - 1]; - } - result[pos] = signature; } + else { + // current declaration belongs to a different symbol + // set cutoffPos so re-orderings in the future won't change result set from 0 to cutoffPos + pos = cutoffPos = result.length; + lastParent = parent; + } + lastSymbol = symbol; + + for (var j = result.length; j > pos; j--) { + result[j] = result[j - 1]; + } + result[pos] = signature; } } } From 782239b6b14d6827e9098eb3c3d9bfb8d6c254d4 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Wed, 29 Oct 2014 14:18:29 -0700 Subject: [PATCH 5/9] use .pop() on an array instead of setting the length directly. The latter causes v8 to stop optimizing the method. --- src/services/syntax/scanner.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/services/syntax/scanner.ts b/src/services/syntax/scanner.ts index 29ced029f1c..a30b8b7d4b2 100644 --- a/src/services/syntax/scanner.ts +++ b/src/services/syntax/scanner.ts @@ -1628,13 +1628,12 @@ module TypeScript.Scanner { var diagnostic = _tokenDiagnostics[tokenDiagnosticsLength - 1]; if (diagnostic.start() >= position) { tokenDiagnosticsLength--; + _tokenDiagnostics.pop(); } else { break; } } - - _tokenDiagnostics.length = tokenDiagnosticsLength; } function resetToPosition(absolutePosition: number): void { From cd1a1dbfc54825f1590de07c5b931dc0afaca9a2 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Wed, 29 Oct 2014 22:29:48 -0700 Subject: [PATCH 6/9] Remove nulls from the syntax layer. --- src/services/core/arrayUtilities.ts | 6 +- src/services/core/debug.ts | 3 +- src/services/core/diagnosticCore.ts | 6 +- src/services/core/lineMap.ts | 4 +- .../syntax/defaultSyntaxVisitor.generated.ts | 2 +- src/services/syntax/incrementalParser.ts | 68 ++--- src/services/syntax/parser.ts | 277 +++++++++--------- src/services/syntax/prettyPrinter.ts | 18 +- src/services/syntax/scanner.ts | 30 +- src/services/syntax/slidingWindow.ts | 2 +- src/services/syntax/syntax.ts | 18 +- src/services/syntax/syntaxElement.ts | 36 +-- src/services/syntax/syntaxFacts.ts | 2 +- src/services/syntax/syntaxGenerator.ts | 68 ++--- src/services/syntax/syntaxList.ts | 4 +- .../syntax/syntaxNodes.abstract.generated.ts | 4 +- .../syntax/syntaxNodes.concrete.generated.ts | 4 +- src/services/syntax/syntaxToken.ts | 22 +- src/services/syntax/syntaxTree.ts | 34 +-- src/services/syntax/syntaxTriviaList.ts | 2 +- src/services/syntax/syntaxUtilities.ts | 12 +- .../syntax/syntaxVisitor.generated.ts | 2 +- src/services/syntax/syntaxWalker.generated.ts | 6 +- src/services/syntax/testUtilities.ts | 8 +- src/services/text/scriptSnapshot.ts | 2 +- src/services/text/textFactory.ts | 6 +- src/services/text/textSpan.ts | 8 +- 27 files changed, 328 insertions(+), 326 deletions(-) diff --git a/src/services/core/arrayUtilities.ts b/src/services/core/arrayUtilities.ts index 4bfec137664..cfb9a1fd4a2 100644 --- a/src/services/core/arrayUtilities.ts +++ b/src/services/core/arrayUtilities.ts @@ -7,7 +7,7 @@ module TypeScript { return true; } - if (array1 === null || array2 === null) { + if (!array1 || !array2) { return false; } @@ -71,7 +71,7 @@ module TypeScript { } } - return null; + return undefined; } public static firstOrDefault(array: T[], func: (v: T, index: number) => boolean): T { @@ -82,7 +82,7 @@ module TypeScript { } } - return null; + return undefined; } public static first(array: T[], func?: (v: T, index: number) => boolean): T { diff --git a/src/services/core/debug.ts b/src/services/core/debug.ts index e57f9745353..d9e20c27870 100644 --- a/src/services/core/debug.ts +++ b/src/services/core/debug.ts @@ -14,13 +14,14 @@ module TypeScript { return this.currentAssertionLevel >= level; } - public static assert(expression: any, message: string = "", verboseDebugInfo: () => string = null): void { + public static assert(expression: any, message?: string, verboseDebugInfo?: () => string): void { if (!expression) { var verboseDebugString = ""; if (verboseDebugInfo) { verboseDebugString = "\r\nVerbose Debug Information:" + verboseDebugInfo(); } + message = message || ""; throw new Error("Debug Failure. False expression: " + message + verboseDebugString); } } diff --git a/src/services/core/diagnosticCore.ts b/src/services/core/diagnosticCore.ts index 369b8114eac..5b860dcd31f 100644 --- a/src/services/core/diagnosticCore.ts +++ b/src/services/core/diagnosticCore.ts @@ -50,11 +50,11 @@ module TypeScript { private _arguments: any[]; private _additionalLocations: Location[]; - constructor(fileName: string, lineMap: LineMap, start: number, length: number, diagnosticKey: string, _arguments: any[]= null, additionalLocations: Location[] = null) { + constructor(fileName: string, lineMap: LineMap, start: number, length: number, diagnosticKey: string, _arguments?: any[], additionalLocations?: Location[]) { super(fileName, lineMap, start, length); this._diagnosticKey = diagnosticKey; - this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; - this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : undefined; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : undefined; } public toJSON(key: any): any { diff --git a/src/services/core/lineMap.ts b/src/services/core/lineMap.ts index 8820f55b920..e4bd7d01bcd 100644 --- a/src/services/core/lineMap.ts +++ b/src/services/core/lineMap.ts @@ -3,7 +3,7 @@ module TypeScript { export class LineMap { public static empty = new LineMap(() => [0], 0); - private _lineStarts: number[] = null; + private _lineStarts: number[] = undefined; constructor(private _computeLineStarts: () => number[], private length: number) { } @@ -18,7 +18,7 @@ module TypeScript { } public lineStarts(): number[] { - if (this._lineStarts === null) { + if (!this._lineStarts) { this._lineStarts = this._computeLineStarts(); } diff --git a/src/services/syntax/defaultSyntaxVisitor.generated.ts b/src/services/syntax/defaultSyntaxVisitor.generated.ts index 32a0cfad4a5..7d4832f5fe6 100644 --- a/src/services/syntax/defaultSyntaxVisitor.generated.ts +++ b/src/services/syntax/defaultSyntaxVisitor.generated.ts @@ -3,7 +3,7 @@ module TypeScript { export class SyntaxVisitor implements ISyntaxVisitor { public defaultVisit(node: ISyntaxNodeOrToken): any { - return null; + return undefined; } public visitToken(token: ISyntaxToken): any { diff --git a/src/services/syntax/incrementalParser.ts b/src/services/syntax/incrementalParser.ts index 94423418f42..6c6d81c0fef 100644 --- a/src/services/syntax/incrementalParser.ts +++ b/src/services/syntax/incrementalParser.ts @@ -88,8 +88,8 @@ module TypeScript.IncrementalParser { function release() { _scannerParserSource.release(); - _scannerParserSource = null; - _oldSourceUnitCursor = null; + _scannerParserSource = undefined; + _oldSourceUnitCursor = undefined; _outstandingRewindPointCount = 0; } @@ -177,13 +177,13 @@ module TypeScript.IncrementalParser { // Null out the cursor that the rewind point points to. This way we don't try // to return it in 'releaseRewindPoint'. - rewindPoint.oldSourceUnitCursor = null; + rewindPoint.oldSourceUnitCursor = undefined; _scannerParserSource.rewind(rewindPoint); } function releaseRewindPoint(rewindPoint: IParserRewindPoint): void { - if (rewindPoint.oldSourceUnitCursor !== null) { + if (rewindPoint.oldSourceUnitCursor) { returnSyntaxCursor(rewindPoint.oldSourceUnitCursor); } @@ -220,7 +220,7 @@ module TypeScript.IncrementalParser { // If our current absolute position is in the middle of the changed range in the new text // then we definitely can't read from the old source unit right now. - if (_changeRange !== null && _changeRangeNewSpan.intersectsWithPosition(absolutePosition())) { + if (_changeRange && _changeRangeNewSpan.intersectsWithPosition(absolutePosition())) { return false; } @@ -258,7 +258,7 @@ module TypeScript.IncrementalParser { // Try to read a node. If we can't then our caller will call back in and just try // to get a token. var node = tryGetNodeFromOldSourceUnit(); - if (node !== null) { + if (node) { // Make sure the positions for the tokens in this node are correct. updateTokens(node); return node; @@ -266,13 +266,13 @@ module TypeScript.IncrementalParser { } // Either we were ahead of the old text, or we were pinned. No node can be read here. - return null; + return undefined; } function currentToken(): ISyntaxToken { if (canReadFromOldSourceUnit()) { var token = tryGetTokenFromOldSourceUnit(); - if (token !== null) { + if (token) { // Make sure the token's position/text is correct. updateTokens(token); return token; @@ -354,9 +354,9 @@ module TypeScript.IncrementalParser { // e) we are still in the same strict or non-strict state that the node was originally parsed in. while (true) { var node = _oldSourceUnitCursor.currentNode(); - if (node === null) { + if (node === undefined) { // Couldn't even read a node, nothing to return. - return null; + return undefined; } if (!intersectsWithChangeRangeSpanInOriginalText(absolutePosition(), fullWidth(node))) { @@ -395,7 +395,7 @@ module TypeScript.IncrementalParser { // need to make sure that if that the parser asks for a *token* we don't return it. // Converted identifiers can't ever be created by the scanner, and as such, should not // be returned by this source. - if (token !== null) { + if (token) { if (!intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { // Didn't intersect with the change range. if (!token.isIncrementallyUnusable() && !Scanner.isContextualToken(token)) { @@ -417,13 +417,13 @@ module TypeScript.IncrementalParser { var token = _oldSourceUnitCursor.currentToken(); return canReuseTokenFromOldSourceUnit(absolutePosition(), token) - ? token : null; + ? token : undefined; } function peekToken(n: number): ISyntaxToken { if (canReadFromOldSourceUnit()) { var token = tryPeekTokenFromOldSourceUnit(n); - if (token !== null) { + if (token) { return token; } } @@ -462,7 +462,7 @@ module TypeScript.IncrementalParser { var interimToken = _oldSourceUnitCursor.currentToken(); if (!canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { - return null; + return undefined; } currentPosition += interimToken.fullWidth(); @@ -471,7 +471,7 @@ module TypeScript.IncrementalParser { var token = _oldSourceUnitCursor.currentToken(); return canReuseTokenFromOldSourceUnit(currentPosition, token) - ? token : null; + ? token : undefined; } function consumeNode(node: ISyntaxNode): void { @@ -486,7 +486,7 @@ module TypeScript.IncrementalParser { var _absolutePosition = absolutePosition() + fullWidth(node); _scannerParserSource.resetToPosition(_absolutePosition); - // Debug.assert(previousToken !== null); + // Debug.assert(previousToken !== undefined); // Debug.assert(previousToken.width() > 0); //if (!isPastChangeRange()) { @@ -515,7 +515,7 @@ module TypeScript.IncrementalParser { var _absolutePosition = absolutePosition() + currentToken.fullWidth(); _scannerParserSource.resetToPosition(_absolutePosition); - // Debug.assert(previousToken !== null); + // Debug.assert(previousToken !== undefined); // Debug.assert(previousToken.width() > 0); //if (!isPastChangeRange()) { @@ -543,15 +543,15 @@ module TypeScript.IncrementalParser { // Once we're past the change range, we no longer need it. Null it out. // From now on we can check if we're past the change range just by seeing - // if this is null. - _changeRange = null; + // if this is undefined. + _changeRange = undefined; } } } } function isPastChangeRange(): boolean { - return _changeRange === null; + return _changeRange === undefined; } return { @@ -605,7 +605,7 @@ module TypeScript.IncrementalParser { if (syntaxCursorPoolCount > 0) { // If we reused an existing cursor, take it out of the pool so no one else uses it. syntaxCursorPoolCount--; - syntaxCursorPool[syntaxCursorPoolCount] = null; + syntaxCursorPool[syntaxCursorPoolCount] = undefined; } return cursor; @@ -652,11 +652,11 @@ module TypeScript.IncrementalParser { for (var i = 0, n = pieces.length; i < n; i++) { var piece = pieces[i]; - if (piece.element === null) { + if (piece.element === undefined) { break; } - piece.element = null; + piece.element = undefined; piece.indexInParent = -1; } @@ -669,7 +669,7 @@ module TypeScript.IncrementalParser { for (var i = 0, n = other.pieces.length; i < n; i++) { var piece = other.pieces[i]; - if (piece.element === null) { + if (piece.element === undefined) { break; } @@ -685,13 +685,13 @@ module TypeScript.IncrementalParser { function currentNodeOrToken(): ISyntaxNodeOrToken { if (isFinished()) { - return null; + return undefined; } var result = pieces[currentPieceIndex].element; // The current element must always be a node or a token. - // Debug.assert(result !== null); + // Debug.assert(result !== undefined); // Debug.assert(result.isNode() || result.isToken()); return result; @@ -699,12 +699,12 @@ module TypeScript.IncrementalParser { function currentNode(): ISyntaxNode { var element = currentNodeOrToken(); - return isNode(element) ? element : null; + return isNode(element) ? element : undefined; } function moveToFirstChild() { var nodeOrToken = currentNodeOrToken(); - if (nodeOrToken === null) { + if (nodeOrToken === undefined) { return; } @@ -721,7 +721,7 @@ module TypeScript.IncrementalParser { // next sibling of the empty node. for (var i = 0, n = childCount(nodeOrToken); i < n; i++) { var child = childAt(nodeOrToken, i); - if (child !== null && !isShared(child)) { + if (child && !isShared(child)) { // Great, we found a real child. Push that. pushElement(child, /*indexInParent:*/ i); @@ -749,7 +749,7 @@ module TypeScript.IncrementalParser { for (var i = currentPiece.indexInParent + 1, n = childCount(parent); i < n; i++) { var sibling = childAt(parent, i); - if (sibling !== null && !isShared(sibling)) { + if (sibling && !isShared(sibling)) { // We found a good sibling that we can move to. Just reuse our existing piece // so we don't have to push/pop. currentPiece.element = sibling; @@ -766,7 +766,7 @@ module TypeScript.IncrementalParser { // Clear the data from the old piece. We don't want to keep any elements around // unintentionally. - currentPiece.element = null; + currentPiece.element = undefined; currentPiece.indexInParent = -1; // Point at the parent. if we move past the top of the path, then we're finished. @@ -787,7 +787,7 @@ module TypeScript.IncrementalParser { } function pushElement(element: ISyntaxElement, indexInParent: number): void { - // Debug.assert(element !== null); + // Debug.assert(element !== undefined); // Debug.assert(indexInParent >= 0); currentPieceIndex++; @@ -819,8 +819,8 @@ module TypeScript.IncrementalParser { moveToFirstToken(); var element = currentNodeOrToken(); - // Debug.assert(element === null || element.isToken()); - return element === null ? null : element; + // Debug.assert(element === undefined || element.isToken()); + return element; } return { diff --git a/src/services/syntax/parser.ts b/src/services/syntax/parser.ts index a35ddc5737b..c5b38f98e24 100644 --- a/src/services/syntax/parser.ts +++ b/src/services/syntax/parser.ts @@ -130,7 +130,7 @@ module TypeScript.Parser { arrayPoolCount--; var result = arrayPool[arrayPoolCount]; - arrayPool[arrayPoolCount] = null; + arrayPool[arrayPoolCount] = undefined; return result; } @@ -212,9 +212,10 @@ module TypeScript.Parser { // Now, clear out our state so that our singleton parser doesn't keep things alive. diagnostics = []; parseNodeData = SyntaxConstants.None; - fileName = null; + fileName = undefined; source.release(); - source = null; _source = null; + source = undefined; + _source = undefined; return result; } @@ -265,8 +266,8 @@ module TypeScript.Parser { // Note: we *can* reuse tokens when the strict mode changes. That's because tokens // are unaffected by strict mode. It's just the parser will decide what to do with it // differently depending on what mode it is in. - if (node === null || parsedInStrictMode(node) !== isInStrictMode) { - return null; + if (!node || parsedInStrictMode(node) !== isInStrictMode) { + return undefined; } return node; @@ -314,7 +315,7 @@ module TypeScript.Parser { return consumeToken(_currentToken); } - return null; + return undefined; } // An identifier is basically any word, unless it is a reserved keyword. so 'foo' is an @@ -367,7 +368,7 @@ module TypeScript.Parser { } function eatOptionalIdentifierToken(): ISyntaxToken { - return isIdentifier(currentToken()) ? eatIdentifierToken() : null; + return isIdentifier(currentToken()) ? eatIdentifierToken() : undefined; } // This method should be called when the grammar calls for an *Identifier* and not an @@ -448,10 +449,10 @@ module TypeScript.Parser { } // Check if an automatic semicolon could go here. If so, then there's no problem and - // we can proceed without error. Return 'null' as there's no actual token for this + // we can proceed without error. Return 'undefined' as there's no actual token for this // position. if (canEatAutomaticSemicolon(allowWithoutNewline)) { - return null; + return undefined; } // No semicolon could be consumed here at all. Just call the standard eating function @@ -471,7 +472,7 @@ module TypeScript.Parser { function getExpectedTokenDiagnostic(expectedKind: SyntaxKind, actual: ISyntaxToken, diagnosticCode: string): Diagnostic { var token = currentToken(); - var args: any[] = null; + var args: any[] = undefined; // If a specialized diagnostic message was provided, just use that. if (!diagnosticCode) { // They wanted something specific, just report that that token was missing. @@ -483,7 +484,7 @@ module TypeScript.Parser { // They wanted an identifier. // If the user supplied a keyword, give them a specialized message. - if (actual !== null && SyntaxFacts.isAnyKeyword(actual.kind())) { + if (actual && SyntaxFacts.isAnyKeyword(actual.kind())) { diagnosticCode = DiagnosticCode.Identifier_expected_0_is_a_keyword; args = [SyntaxFacts.getText(actual.kind())]; } @@ -860,7 +861,7 @@ module TypeScript.Parser { function tryParseTypeArgumentList(inExpression: boolean): TypeArgumentListSyntax { var _currentToken = currentToken(); if (_currentToken.kind() !== SyntaxKind.LessThanToken) { - return null; + return undefined; } if (!inExpression) { @@ -895,7 +896,7 @@ module TypeScript.Parser { if (greaterThanToken.fullWidth() === 0 || !canFollowTypeArgumentListInExpression(currentToken().kind())) { rewind(rewindPoint); releaseRewindPoint(rewindPoint); - return null; + return undefined; } else { releaseRewindPoint(rewindPoint); @@ -982,7 +983,7 @@ module TypeScript.Parser { var token0 = currentToken(); var shouldContinue = isIdentifier(token0); if (!shouldContinue) { - return null; + return undefined; } // Call eatIdentifierName to convert the token to an identifier if it is as keyword. @@ -1018,7 +1019,7 @@ module TypeScript.Parser { function isEnumElement(inErrorRecovery: boolean): boolean { var node = currentNode(); - if (node !== null && node.kind() === SyntaxKind.EnumElement) { + if (node && node.kind() === SyntaxKind.EnumElement) { return true; } @@ -1026,18 +1027,18 @@ module TypeScript.Parser { } function tryParseEnumElementEqualsValueClause(): EqualsValueClauseSyntax { - return isEqualsValueClause(/*inParameter*/ false) ? parseEqualsValueClause(/*allowIn:*/ true) : null; + return isEqualsValueClause(/*inParameter*/ false) ? parseEqualsValueClause(/*allowIn:*/ true) : undefined; } function tryParseEnumElement(inErrorRecovery: boolean): EnumElementSyntax { var node = currentNode(); - if (node !== null && node.kind() === SyntaxKind.EnumElement) { + if (node && node.kind() === SyntaxKind.EnumElement) { consumeNode(node); return node; } if (!isPropertyName(currentToken(), inErrorRecovery)) { - return null; + return undefined; } return new syntaxFactory.EnumElementSyntax(parseNodeData, eatPropertyName(), tryParseEnumElementEqualsValueClause()); @@ -1115,17 +1116,17 @@ module TypeScript.Parser { var heritageClauses = Syntax.emptyList(); if (isHeritageClause()) { - // NOTE: we can pass "null" for the skipped tokens here as we know we can't get + // NOTE: we can pass "undefined" for the skipped tokens here as we know we can't get // any leading skipped tokens. We have an 'extends' or 'implements' keyword, so // any skipped tokeds will get attached to that instead. - heritageClauses= parseSyntaxList(ListParsingState.ClassOrInterfaceDeclaration_HeritageClauses, null); + heritageClauses = parseSyntaxList(ListParsingState.ClassOrInterfaceDeclaration_HeritageClauses, undefined); } return heritageClauses; } function tryParseHeritageClauseTypeName(): ITypeSyntax { - return isHeritageClauseTypeName() ? tryParseNameOrGenericType() : null; + return isHeritageClauseTypeName() ? tryParseNameOrGenericType() : undefined; } function parseClassDeclaration(): ClassDeclarationSyntax { @@ -1226,7 +1227,7 @@ module TypeScript.Parser { return parseIndexMemberDeclaration(); } else { - return null; + return undefined; } } @@ -1243,8 +1244,8 @@ module TypeScript.Parser { var constructorKeyword = eatToken(SyntaxKind.ConstructorKeyword); var callSignature = parseCallSignature(/*requireCompleteTypeParameterList:*/ false); - var semicolonToken: ISyntaxToken = null; - var block: BlockSyntax = null; + var semicolonToken: ISyntaxToken = undefined; + var block: BlockSyntax = undefined; if (isBlock()) { block = parseBlock(/*parseStatementsEvenWithNoOpenBrace:*/ false, /*checkForStrictMode:*/ true); @@ -1269,8 +1270,8 @@ module TypeScript.Parser { // open brace. var parseBlockEvenWithNoOpenBrace = tryAddUnexpectedEqualsGreaterThanToken(callSignature); - var block: BlockSyntax = null; - var semicolon: ISyntaxToken = null; + var block: BlockSyntax = undefined; + var semicolon: ISyntaxToken = undefined; if (parseBlockEvenWithNoOpenBrace || isBlock()) { block = parseBlock(parseBlockEvenWithNoOpenBrace, /*checkForStrictMode:*/ true); @@ -1375,8 +1376,8 @@ module TypeScript.Parser { // open brace. var parseBlockEvenWithNoOpenBrace = tryAddUnexpectedEqualsGreaterThanToken(callSignature); - var semicolonToken: ISyntaxToken = null; - var block: BlockSyntax = null; + var semicolonToken: ISyntaxToken = undefined; + var block: BlockSyntax = undefined; // Parse a block if we're on a bock, or if we saw a '=>' if (parseBlockEvenWithNoOpenBrace || isBlock()) { @@ -1393,8 +1394,8 @@ module TypeScript.Parser { var modifiers = parseModifiers(); var moduleKeyword = eatToken(SyntaxKind.ModuleKeyword); - var moduleName: INameSyntax = null; - var stringLiteral: ISyntaxToken = null; + var moduleName: INameSyntax = undefined; + var stringLiteral: ISyntaxToken = undefined; if (currentToken().kind() === SyntaxKind.StringLiteral) { stringLiteral = eatToken(SyntaxKind.StringLiteral); @@ -1485,7 +1486,7 @@ module TypeScript.Parser { return parsePropertySignature(); } else { - return null; + return undefined; } } @@ -1606,7 +1607,7 @@ module TypeScript.Parser { var extendsOrImplementsKeyword = currentToken(); var tokenKind = extendsOrImplementsKeyword.kind(); if (tokenKind !== SyntaxKind.ExtendsKeyword && tokenKind !== SyntaxKind.ImplementsKeyword) { - return null; + return undefined; } consumeToken(extendsOrImplementsKeyword); @@ -1754,7 +1755,7 @@ module TypeScript.Parser { // and we should not parse it out here. if (SyntaxFacts.isIdentifierNameOrAnyKeyword(peekToken(1))) { // Definitely not a statement. - return null; + return undefined; } else { break; @@ -1780,7 +1781,7 @@ module TypeScript.Parser { // existing block properly. We don't want to accidently consume these as expression // below. if (isInterfaceEnumClassModuleImportOrExport(modifierCount)) { - return null; + return undefined; } else if (isVariableStatement(modifierCount)) { return parseVariableStatement(); @@ -1798,7 +1799,7 @@ module TypeScript.Parser { return parseExpressionStatement(); } else { - return null; + return undefined; } } @@ -1833,15 +1834,15 @@ module TypeScript.Parser { var block = parseBlock(/*parseStatementsEvenWithNoOpenBrace:*/ false, /*checkForStrictMode:*/ false); listParsingState = savedListParsingState; - var catchClause: CatchClauseSyntax = null; + var catchClause: CatchClauseSyntax = undefined; if (currentToken().kind() === SyntaxKind.CatchKeyword) { catchClause = parseCatchClause(); } // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - var finallyClause: FinallyClauseSyntax = null; - if (catchClause === null || currentToken().kind() === SyntaxKind.FinallyKeyword) { + var finallyClause: FinallyClauseSyntax = undefined; + if (!catchClause || currentToken().kind() === SyntaxKind.FinallyKeyword) { finallyClause = parseFinallyClause(); } @@ -1929,8 +1930,8 @@ module TypeScript.Parser { var variableDeclaration = parseVariableDeclaration(/*allowIn:*/ false); return currentToken().kind() === SyntaxKind.InKeyword - ? parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null) - : parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + ? parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, undefined) + : parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, undefined); } function parseForInStatementWithVariableDeclarationOrInitializer(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax): ForInStatementSyntax { @@ -1949,8 +1950,8 @@ module TypeScript.Parser { var initializer = parseExpression(/*allowIn:*/ false); return currentToken().kind() === SyntaxKind.InKeyword - ? parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer) - : parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + ? parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, undefined, initializer) + : parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, undefined, initializer); } function parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken): ForStatementSyntax { @@ -1958,7 +1959,7 @@ module TypeScript.Parser { // Debug.assert(currentToken().kind() === SyntaxKind.SemicolonToken); // for ( ; Expressionopt ; Expressionopt ) Statement - return parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, /*variableDeclaration:*/ null, /*initializer:*/ null); + return parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, /*variableDeclaration:*/ undefined, /*initializer:*/ undefined); } function tryParseForStatementCondition(): IExpressionSyntax { @@ -1969,7 +1970,7 @@ module TypeScript.Parser { return parseExpression(/*allowIn:*/ true); } - return null; + return undefined; } function tryParseForStatementIncrementor(): IExpressionSyntax { @@ -1979,7 +1980,7 @@ module TypeScript.Parser { return parseExpression(/*allowIn:*/ true); } - return null; + return undefined; } function parseForStatementWithVariableDeclarationOrInitializer(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax): ForStatementSyntax { @@ -1997,14 +1998,14 @@ module TypeScript.Parser { function tryEatBreakOrContinueLabel(): ISyntaxToken { // If there is no newline after the break keyword, then we can consume an optional // identifier. - var identifier: ISyntaxToken = null; + var identifier: ISyntaxToken = undefined; if (!canEatExplicitOrAutomaticSemicolon(/*allowWithoutNewline:*/ false)) { if (isIdentifier(currentToken())) { return eatIdentifierToken(); } } - return null; + return undefined; } function parseBreakStatement(breakKeyword: ISyntaxToken): BreakStatementSyntax { @@ -2062,7 +2063,7 @@ module TypeScript.Parser { return parseDefaultSwitchClause(_currentToken); } else { - return null; + return undefined; } } @@ -2108,7 +2109,7 @@ module TypeScript.Parser { // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' // directly as that might consume an expression on the following line. return canEatExplicitOrAutomaticSemicolon(/*allowWithoutNewline:*/ false) - ? createMissingToken(SyntaxKind.IdentifierName, null) + ? createMissingToken(SyntaxKind.IdentifierName, undefined) : parseExpression(/*allowIn:*/ true); } @@ -2118,7 +2119,7 @@ module TypeScript.Parser { } function tryParseReturnStatementExpression(): IExpressionSyntax { - return !canEatExplicitOrAutomaticSemicolon(/*allowWithoutNewline:*/ false) ? parseExpression(/*allowIn:*/ true) : null; + return !canEatExplicitOrAutomaticSemicolon(/*allowWithoutNewline:*/ false) ? parseExpression(/*allowIn:*/ true) : undefined; } function parseReturnStatement(returnKeyword: ISyntaxToken): ReturnStatementSyntax { @@ -2225,7 +2226,7 @@ module TypeScript.Parser { } function parseOptionalElseClause(): ElseClauseSyntax { - return currentToken().kind() === SyntaxKind.ElseKeyword ? parseElseClause() : null; + return currentToken().kind() === SyntaxKind.ElseKeyword ? parseElseClause() : undefined; } function parseElseClause(): ElseClauseSyntax { @@ -2260,7 +2261,7 @@ module TypeScript.Parser { function isVariableDeclarator(): boolean { var node = currentNode(); - if (node !== null && node.kind() === SyntaxKind.VariableDeclarator) { + if (node && node.kind() === SyntaxKind.VariableDeclarator) { return true; } @@ -2268,7 +2269,7 @@ module TypeScript.Parser { } function canReuseVariableDeclaratorNode(node: ISyntaxNode) { - if (node === null || node.kind() !== SyntaxKind.VariableDeclarator) { + if (!node || node.kind() !== SyntaxKind.VariableDeclarator) { return false; } @@ -2287,7 +2288,7 @@ module TypeScript.Parser { // In order to prevent this, we do not allow a variable declarator to be reused if it // has an initializer. var variableDeclarator = node; - return variableDeclarator.equalsValueClause === null; + return variableDeclarator.equalsValueClause === undefined; } function tryParseVariableDeclarator(allowIn: boolean, allowPropertyName: boolean): VariableDeclaratorSyntax { @@ -2308,12 +2309,12 @@ module TypeScript.Parser { } if (!allowPropertyName && !isIdentifier(currentToken())) { - return null; + return undefined; } var propertyName = allowPropertyName ? eatPropertyName() : eatIdentifierToken(); - var equalsValueClause: EqualsValueClauseSyntax = null; - var typeAnnotation: TypeAnnotationSyntax = null; + var equalsValueClause: EqualsValueClauseSyntax = undefined; + var typeAnnotation: TypeAnnotationSyntax = undefined; if (propertyName.fullWidth() > 0) { typeAnnotation = parseOptionalTypeAnnotation(/*allowStringLiteral:*/ false); @@ -2419,7 +2420,7 @@ module TypeScript.Parser { // with AssignmentExpression if we see one. var _currentToken = currentToken(); var arrowFunction = tryParseAnyArrowFunctionExpression(_currentToken); - if (arrowFunction !== null) { + if (arrowFunction) { return arrowFunction; } @@ -2433,8 +2434,8 @@ module TypeScript.Parser { // binary expression here, so we pass in the 'lowest' precedence here so that it matches // and consumes anything. var leftOperand = tryParseBinaryExpressionOrHigher(_currentToken, force, BinaryExpressionPrecedence.Lowest, allowIn); - if (leftOperand === null) { - return null; + if (leftOperand === undefined) { + return undefined; } if (SyntaxUtilities.isLeftHandSizeExpression(leftOperand)) { @@ -2488,8 +2489,8 @@ module TypeScript.Parser { // MultiplicativeExpression: See 11.5 // UnaryExpression var leftOperand = tryParseUnaryExpressionOrHigher(_currentToken, force); - if (leftOperand === null) { - return null; + if (leftOperand === undefined) { + return undefined; } // We then pop up the stack consuming the other side of the binary exprssion if it exists. @@ -2622,8 +2623,8 @@ module TypeScript.Parser { // Because CallExpression and MemberExpression are left recursive, we need to bottom out // of the recursion immediately. So we parse out a primary expression to start with. var expression: IMemberExpressionSyntax = tryParsePrimaryExpression(_currentToken, force); - if (expression === null) { - return null; + if (expression === undefined) { + return undefined; } return parseMemberExpressionRest(expression, inObjectCreation); @@ -2636,7 +2637,7 @@ module TypeScript.Parser { switch (currentTokenKind) { case SyntaxKind.OpenParenToken: - expression = new syntaxFactory.InvocationExpressionSyntax(parseNodeData, expression, parseArgumentList(/*typeArgumentList:*/ null)); + expression = new syntaxFactory.InvocationExpressionSyntax(parseNodeData, expression, parseArgumentList(/*typeArgumentList:*/ undefined)); continue; case SyntaxKind.LessThanToken: @@ -2645,7 +2646,7 @@ module TypeScript.Parser { // part of an arithmetic expression. Break out so we consume it higher in the // stack. var argumentList = tryParseArgumentList(); - if (argumentList === null) { + if (argumentList === undefined) { break; } @@ -2716,14 +2717,14 @@ module TypeScript.Parser { // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - var expression: ILeftHandSideExpressionSyntax = null; + var expression: ILeftHandSideExpressionSyntax = undefined; if (_currentToken.kind() === SyntaxKind.SuperKeyword) { expression = parseSuperExpression(_currentToken); } else { expression = tryParseMemberExpressionOrHigher(_currentToken, force, /*inObjectCreation:*/ false); - if (expression === null) { - return null; + if (expression === undefined) { + return undefined; } } @@ -2745,8 +2746,8 @@ module TypeScript.Parser { function tryParsePostfixExpressionOrHigher(_currentToken: ISyntaxToken, force: boolean): IPostfixExpressionSyntax { var expression = tryParseLeftHandSideExpressionOrHigher(_currentToken, force); - if (expression === null) { - return null; + if (expression === undefined) { + return undefined; } var _currentToken = currentToken(); @@ -2781,13 +2782,13 @@ module TypeScript.Parser { var isDot = tokenKind === SyntaxKind.DotToken; var isOpenParenOrDot = isOpenParen || isDot; - var argumentList: ArgumentListSyntax = null; - if (typeArgumentList === null || !isOpenParenOrDot) { + var argumentList: ArgumentListSyntax = undefined; + if (!typeArgumentList || !isOpenParenOrDot) { // Wasn't generic. Rewind to where we started so this can be parsed as an // arithmetic expression. rewind(rewindPoint); releaseRewindPoint(rewindPoint); - return null; + return undefined; } else { releaseRewindPoint(rewindPoint); @@ -2800,7 +2801,7 @@ module TypeScript.Parser { if (isDot) { // A parameter list must follow a generic type argument list. var diagnostic = new Diagnostic(fileName, source.text.lineMap(), start(token0, source.text), width(token0), - DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, null); + DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, undefined); addDiagnostic(diagnostic); return new syntaxFactory.ArgumentListSyntax(parseNodeData, typeArgumentList, @@ -2819,10 +2820,10 @@ module TypeScript.Parser { } if (tokenKind === SyntaxKind.OpenParenToken) { - return parseArgumentList(null); + return parseArgumentList(undefined); } - return null; + return undefined; } function parseArgumentList(typeArgumentList: TypeArgumentListSyntax): ArgumentListSyntax { @@ -2859,7 +2860,7 @@ module TypeScript.Parser { var errorStart = start(openBracketToken, source.text); var errorEnd = end(currentToken(), source.text); var diagnostic = new Diagnostic(fileName, source.text.lineMap(), errorStart, errorEnd - errorStart, - DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, null); + DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, undefined); addDiagnostic(diagnostic); return Syntax.emptyToken(SyntaxKind.IdentifierName); @@ -2911,7 +2912,7 @@ module TypeScript.Parser { } if (!force) { - return null; + return undefined; } // Nothing else worked, report an error and produce a missing token. @@ -2937,7 +2938,7 @@ module TypeScript.Parser { var tokenKind = currentToken.kind(); if (tokenKind === SyntaxKind.SlashToken || tokenKind === SyntaxKind.SlashEqualsToken) { // Still came back as a / or /=. This is not a regular expression literal. - return null; + return undefined; } else if (tokenKind === SyntaxKind.RegularExpressionLiteral) { return consumeToken(currentToken); @@ -2995,7 +2996,7 @@ module TypeScript.Parser { function tryParseParenthesizedArrowFunctionExpression(): ParenthesizedArrowFunctionExpressionSyntax { var tokenKind = currentToken().kind(); if (tokenKind !== SyntaxKind.OpenParenToken && tokenKind !== SyntaxKind.LessThanToken) { - return null; + return undefined; } // Because arrow functions and parenthesized expressions look similar, we have to check far @@ -3016,14 +3017,14 @@ module TypeScript.Parser { // Now, look for cases where we're sure it's not an arrow function. This will help save us // a costly parse. if (!isPossiblyArrowFunctionExpression()) { - return null; + return undefined; } // Then, try to actually parse it as a arrow function, and only return if we see an => var rewindPoint = getRewindPoint(); var arrowFunction = tryParseParenthesizedArrowFunctionExpressionWorker(/*requiresArrow:*/ true); - if (arrowFunction === null) { + if (arrowFunction === undefined) { rewind(rewindPoint); } @@ -3038,14 +3039,14 @@ module TypeScript.Parser { var callSignature = parseCallSignature(/*requireCompleteTypeParameterList:*/ true); if (requireArrow && currentToken().kind() !== SyntaxKind.EqualsGreaterThanToken) { - return null; + return undefined; } var equalsGreaterThanToken = eatToken(SyntaxKind.EqualsGreaterThanToken); var block = tryParseArrowFunctionBlock(); - var expression: IExpressionSyntax = null; - if (block === null) { + var expression: IExpressionSyntax = undefined; + if (block === undefined) { expression = tryParseAssignmentExpressionOrHigher(/*force:*/ true, /*allowIn:*/ true); } @@ -3076,7 +3077,7 @@ module TypeScript.Parser { return parseBlock(/*parseStatementsEvenWithNoOpenBrace:*/ true, /*checkForStrictMode:*/ false); } else { - return null; + return undefined; } } } @@ -3100,8 +3101,8 @@ module TypeScript.Parser { var equalsGreaterThanToken = eatToken(SyntaxKind.EqualsGreaterThanToken); var block = tryParseArrowFunctionBlock(); - var expression: IExpressionSyntax = null; - if (block === null) { + var expression: IExpressionSyntax = undefined; + if (block === undefined) { expression = tryParseAssignmentExpressionOrHigher(/*force:*/ true, /*allowIn:*/ true); } @@ -3297,7 +3298,7 @@ module TypeScript.Parser { return parseSimplePropertyAssignment(); } else { - return null; + return undefined; } } @@ -3376,7 +3377,7 @@ module TypeScript.Parser { if (parseBlockEvenWithNoOpenBrace || openBraceToken.fullWidth() > 0) { var savedIsInStrictMode = isInStrictMode; - var processItems = checkForStrictMode ? updateStrictModeState : null; + var processItems = checkForStrictMode ? updateStrictModeState : undefined; var skippedTokens: ISyntaxToken[] = getArray(); var statements = parseSyntaxList(ListParsingState.Block_Statements, skippedTokens, processItems); openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); @@ -3395,7 +3396,7 @@ module TypeScript.Parser { function tryParseTypeParameterList(requireCompleteTypeParameterList: boolean): TypeParameterListSyntax { var _currentToken = currentToken(); if (_currentToken.kind() !== SyntaxKind.LessThanToken) { - return null; + return undefined; } var rewindPoint = getRewindPoint(); @@ -3408,11 +3409,11 @@ module TypeScript.Parser { var greaterThanToken = eatToken(SyntaxKind.GreaterThanToken); - // return null if we were required to have a '>' token and we did not have one. + // return undefined if we were required to have a '>' token and we did not have one. if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { rewind(rewindPoint); releaseRewindPoint(rewindPoint); - return null; + return undefined; } else { releaseRewindPoint(rewindPoint); @@ -3427,7 +3428,7 @@ module TypeScript.Parser { function tryParseTypeParameter(): TypeParameterSyntax { // Debug.assert(isTypeParameter()); if (!isIdentifier(currentToken())) { - return null; + return undefined; } return new syntaxFactory.TypeParameterSyntax(parseNodeData, eatIdentifierToken(), tryParseConstraint()); @@ -3435,7 +3436,7 @@ module TypeScript.Parser { function tryParseConstraint(): ConstraintSyntax { if (currentToken().kind() !== SyntaxKind.ExtendsKeyword) { - return null; + return undefined; } return new syntaxFactory.ConstraintSyntax(parseNodeData, eatToken(SyntaxKind.ExtendsKeyword), parseTypeOrExpression()); @@ -3450,7 +3451,7 @@ module TypeScript.Parser { } } - return null; + return undefined; } function parseParameterList(): ParameterListSyntax { @@ -3467,7 +3468,7 @@ module TypeScript.Parser { } function parseOptionalTypeAnnotation(allowStringLiteral: boolean): TypeAnnotationSyntax { - return currentToken().kind() === SyntaxKind.ColonToken ? parseTypeAnnotation(allowStringLiteral) : null; + return currentToken().kind() === SyntaxKind.ColonToken ? parseTypeAnnotation(allowStringLiteral) : undefined; } function parseTypeAnnotationType(allowStringLiteral: boolean): ITypeSyntax { @@ -3586,8 +3587,8 @@ module TypeScript.Parser { function tryParseNameOrGenericType(): ITypeSyntax { var name = tryParseName(/*allowIdentifierNames*/ false); - if (name === null) { - return null; + if (name === undefined) { + return undefined; } // TypeReference: @@ -3599,18 +3600,18 @@ module TypeScript.Parser { } var typeArgumentList = tryParseTypeArgumentList(/*inExpression:*/ false); - return typeArgumentList === null + return !typeArgumentList ? name : new syntaxFactory.GenericTypeSyntax(parseNodeData, name, typeArgumentList); } function tryParseFunctionType(): FunctionTypeSyntax { var typeParameterList = tryParseTypeParameterList(/*requireCompleteTypeParameterList:*/ false); - var parameterList: ParameterListSyntax = null; - if (typeParameterList === null) { + var parameterList: ParameterListSyntax = undefined; + if (typeParameterList === undefined) { parameterList = tryParseParameterList(); - if (parameterList === null) { - return null; + if (parameterList === undefined) { + return undefined; } } else { @@ -3628,7 +3629,7 @@ module TypeScript.Parser { } function isParameter(): boolean { - if (currentNode() !== null && currentNode().kind() === SyntaxKind.Parameter) { + if (currentNode() && currentNode().kind() === SyntaxKind.Parameter) { return true; } @@ -3644,13 +3645,13 @@ module TypeScript.Parser { function eatSimpleParameter() { return new syntaxFactory.ParameterSyntax(parseNodeData, - /*dotDotDotToken:*/ null, /*modifiers:*/ Syntax.emptyList(), eatIdentifierToken(), - /*questionToken:*/ null, /*typeAnnotation:*/ null, /*equalsValueClause:*/ null); + /*dotDotDotToken:*/ undefined, /*modifiers:*/ Syntax.emptyList(), eatIdentifierToken(), + /*questionToken:*/ undefined, /*typeAnnotation:*/ undefined, /*equalsValueClause:*/ undefined); } function tryParseParameter(): ParameterSyntax { var node = currentNode(); - if (node !== null && node.kind() === SyntaxKind.Parameter) { + if (node && node.kind() === SyntaxKind.Parameter) { consumeNode(node); return node; } @@ -3661,7 +3662,7 @@ module TypeScript.Parser { // If we're not forcing, and we don't see anything to indicate this is a parameter, then // bail out. var _currentToken = currentToken(); - if (!isIdentifier(_currentToken) && dotDotDotToken === null && modifiers.length === 0) { + if (!isIdentifier(_currentToken) && !dotDotDotToken && modifiers.length === 0) { // ERROR RECOVERY: // If we see a modifier alone in a parameter list, like: foo(static) // @@ -3670,7 +3671,7 @@ module TypeScript.Parser { modifiers = Syntax.list([consumeToken(_currentToken)]); } else { - return null; + return undefined; } } @@ -3678,7 +3679,7 @@ module TypeScript.Parser { var questionToken = tryEatToken(SyntaxKind.QuestionToken); var typeAnnotation = parseOptionalTypeAnnotation(/*allowStringLiteral:*/ true); - var equalsValueClause: EqualsValueClauseSyntax = null; + var equalsValueClause: EqualsValueClauseSyntax = undefined; if (isEqualsValueClause(/*inParameter*/ true)) { equalsValueClause = parseEqualsValueClause(/*allowIn:*/ true); } @@ -3687,7 +3688,7 @@ module TypeScript.Parser { } function parseSyntaxList( - currentListType: ListParsingState, skippedTokens: ISyntaxToken[], processItems: (items: any[]) => void = null): T[] { + currentListType: ListParsingState, skippedTokens: ISyntaxToken[], processItems?: (items: any[]) => void): T[] { var savedListParsingState = listParsingState; listParsingState |= (1 << currentListType); @@ -3769,14 +3770,14 @@ module TypeScript.Parser { currentListType: ListParsingState, inErrorRecovery: boolean, items: ISyntaxElement[], processItems: (items: any[]) => void): boolean { var item = tryParseExpectedListItemWorker(currentListType, inErrorRecovery); - if (item === null) { + if (item === undefined) { return false; } - // Debug.assert(item !== null); + // Debug.assert(item !== undefined); items.push(item); - if (processItems !== null) { + if (processItems) { processItems(items); } @@ -3807,7 +3808,7 @@ module TypeScript.Parser { // List wasn't complete and we didn't get an item. Figure out if we should bail out // or skip a token and continue. - var abort = abortParsingListOrMoveToNextToken(currentListType, items, null, skippedTokens); + var abort = abortParsingListOrMoveToNextToken(currentListType, items, /*separators:*/ undefined, skippedTokens); if (abort) { break; } @@ -3846,11 +3847,11 @@ module TypeScript.Parser { // continue parsing. // Debug.assert(oldItemsCount % 2 === 0); - var succeeded = tryParseExpectedListItem(currentListType, inErrorRecovery, nodes, null); + var succeeded = tryParseExpectedListItem(currentListType, inErrorRecovery, nodes, /*processItems:*/ undefined); if (!succeeded) { // We weren't able to parse out a list element. - // Debug.assert(items === null || items.length % 2 === 0); + // Debug.assert(items === undefined || items.length % 2 === 0); // That may have been because the list is complete. In that case, break out // and return the items we were able parse. @@ -4267,26 +4268,26 @@ module TypeScript.Parser { function getExpectedListElementType(currentListType: ListParsingState): string { switch (currentListType) { - case ListParsingState.SourceUnit_ModuleElements: return getLocalizedText(DiagnosticCode.module_class_interface_enum_import_or_statement, null); + case ListParsingState.SourceUnit_ModuleElements: return getLocalizedText(DiagnosticCode.module_class_interface_enum_import_or_statement, undefined); case ListParsingState.ClassOrInterfaceDeclaration_HeritageClauses: return '{'; - case ListParsingState.ClassDeclaration_ClassElements: return getLocalizedText(DiagnosticCode.constructor_function_accessor_or_variable, null); - case ListParsingState.ModuleDeclaration_ModuleElements: return getLocalizedText(DiagnosticCode.module_class_interface_enum_import_or_statement, null); - case ListParsingState.SwitchStatement_SwitchClauses: return getLocalizedText(DiagnosticCode.case_or_default_clause, null); - case ListParsingState.SwitchClause_Statements: return getLocalizedText(DiagnosticCode.statement, null); - case ListParsingState.Block_Statements: return getLocalizedText(DiagnosticCode.statement, null); - case ListParsingState.VariableDeclaration_VariableDeclarators_AllowIn: return getLocalizedText(DiagnosticCode.identifier, null); - case ListParsingState.VariableDeclaration_VariableDeclarators_DisallowIn: return getLocalizedText(DiagnosticCode.identifier, null); - case ListParsingState.EnumDeclaration_EnumElements: return getLocalizedText(DiagnosticCode.identifier, null); - case ListParsingState.ObjectType_TypeMembers: return getLocalizedText(DiagnosticCode.call_construct_index_property_or_function_signature, null); - case ListParsingState.ArgumentList_AssignmentExpressions: return getLocalizedText(DiagnosticCode.expression, null); - case ListParsingState.HeritageClause_TypeNameList: return getLocalizedText(DiagnosticCode.type_name, null); - case ListParsingState.ObjectLiteralExpression_PropertyAssignments: return getLocalizedText(DiagnosticCode.property_or_accessor, null); - case ListParsingState.ParameterList_Parameters: return getLocalizedText(DiagnosticCode.parameter, null); - case ListParsingState.IndexSignature_Parameters: return getLocalizedText(DiagnosticCode.parameter, null); - case ListParsingState.TypeArgumentList_Types: return getLocalizedText(DiagnosticCode.type, null); - case ListParsingState.TypeParameterList_TypeParameters: return getLocalizedText(DiagnosticCode.type_parameter, null); - case ListParsingState.TupleType_Types: return getLocalizedText(DiagnosticCode.type, null); - case ListParsingState.ArrayLiteralExpression_AssignmentExpressions: return getLocalizedText(DiagnosticCode.expression, null); + case ListParsingState.ClassDeclaration_ClassElements: return getLocalizedText(DiagnosticCode.constructor_function_accessor_or_variable, undefined); + case ListParsingState.ModuleDeclaration_ModuleElements: return getLocalizedText(DiagnosticCode.module_class_interface_enum_import_or_statement, undefined); + case ListParsingState.SwitchStatement_SwitchClauses: return getLocalizedText(DiagnosticCode.case_or_default_clause, undefined); + case ListParsingState.SwitchClause_Statements: return getLocalizedText(DiagnosticCode.statement, undefined); + case ListParsingState.Block_Statements: return getLocalizedText(DiagnosticCode.statement, undefined); + case ListParsingState.VariableDeclaration_VariableDeclarators_AllowIn: return getLocalizedText(DiagnosticCode.identifier, undefined); + case ListParsingState.VariableDeclaration_VariableDeclarators_DisallowIn: return getLocalizedText(DiagnosticCode.identifier, undefined); + case ListParsingState.EnumDeclaration_EnumElements: return getLocalizedText(DiagnosticCode.identifier, undefined); + case ListParsingState.ObjectType_TypeMembers: return getLocalizedText(DiagnosticCode.call_construct_index_property_or_function_signature, undefined); + case ListParsingState.ArgumentList_AssignmentExpressions: return getLocalizedText(DiagnosticCode.expression, undefined); + case ListParsingState.HeritageClause_TypeNameList: return getLocalizedText(DiagnosticCode.type_name, undefined); + case ListParsingState.ObjectLiteralExpression_PropertyAssignments: return getLocalizedText(DiagnosticCode.property_or_accessor, undefined); + case ListParsingState.ParameterList_Parameters: return getLocalizedText(DiagnosticCode.parameter, undefined); + case ListParsingState.IndexSignature_Parameters: return getLocalizedText(DiagnosticCode.parameter, undefined); + case ListParsingState.TypeArgumentList_Types: return getLocalizedText(DiagnosticCode.type, undefined); + case ListParsingState.TypeParameterList_TypeParameters: return getLocalizedText(DiagnosticCode.type_parameter, undefined); + case ListParsingState.TupleType_Types: return getLocalizedText(DiagnosticCode.type, undefined); + case ListParsingState.ArrayLiteralExpression_AssignmentExpressions: return getLocalizedText(DiagnosticCode.expression, undefined); default: throw Errors.invalidOperation(); } } diff --git a/src/services/syntax/prettyPrinter.ts b/src/services/syntax/prettyPrinter.ts index df22bcab559..53d77930380 100644 --- a/src/services/syntax/prettyPrinter.ts +++ b/src/services/syntax/prettyPrinter.ts @@ -16,7 +16,7 @@ module TypeScript.PrettyPrinter { } private newLineCountBetweenModuleElements(element1: IModuleElementSyntax, element2: IModuleElementSyntax): number { - if (element1 === null || element2 === null) { + if (!element1 || !element2) { return 0; } @@ -28,7 +28,7 @@ module TypeScript.PrettyPrinter { } private newLineCountBetweenClassElements(element1: IClassElementSyntax, element2: IClassElementSyntax): number { - if (element1 === null || element2 === null) { + if (!element1 || !element2) { return 0; } @@ -36,7 +36,7 @@ module TypeScript.PrettyPrinter { } private newLineCountBetweenStatements(element1: IClassElementSyntax, element2: IClassElementSyntax): number { - if (element1 === null || element2 === null) { + if (!element1 || !element2) { return 0; } @@ -48,7 +48,7 @@ module TypeScript.PrettyPrinter { } private newLineCountBetweenSwitchClauses(element1: ISwitchClauseSyntax, element2: ISwitchClauseSyntax): number { - if (element1 === null || element2 === null) { + if (!element1 || !element2) { return 0; } @@ -120,7 +120,7 @@ module TypeScript.PrettyPrinter { } private appendToken(token: ISyntaxToken): void { - if (token !== null && token.fullWidth() > 0) { + if (token && token.fullWidth() > 0) { this.appendIndentationIfAfterNewLine(); this.appendText(token.text()); } @@ -174,7 +174,7 @@ module TypeScript.PrettyPrinter { } private appendModuleElements(list: IModuleElementSyntax[]): void { - var lastModuleElement: IModuleElementSyntax = null; + var lastModuleElement: IModuleElementSyntax = undefined; for (var i = 0, n = list.length; i < n; i++) { var moduleElement = list[i]; var newLineCount = this.newLineCountBetweenModuleElements(lastModuleElement, moduleElement); @@ -236,7 +236,7 @@ module TypeScript.PrettyPrinter { this.indentation++; - var lastClassElement: IClassElementSyntax = null; + var lastClassElement: IClassElementSyntax = undefined; for (var i = 0, n = node.classElements.length; i < n; i++) { var classElement = node.classElements[i]; var newLineCount = this.newLineCountBetweenClassElements(lastClassElement, classElement); @@ -472,7 +472,7 @@ module TypeScript.PrettyPrinter { } private appendStatements(statements: IStatementSyntax[]): void { - var lastStatement: IStatementSyntax = null; + var lastStatement: IStatementSyntax = undefined; for (var i = 0, n = statements.length; i < n; i++) { var statement = statements[i]; @@ -743,7 +743,7 @@ module TypeScript.PrettyPrinter { this.appendToken(node.openBraceToken); this.ensureNewLine(); - var lastSwitchClause: ISwitchClauseSyntax = null; + var lastSwitchClause: ISwitchClauseSyntax = undefined; for (var i = 0, n = node.switchClauses.length; i < n; i++) { var switchClause = node.switchClauses[i]; diff --git a/src/services/syntax/scanner.ts b/src/services/syntax/scanner.ts index a30b8b7d4b2..62959e458ff 100644 --- a/src/services/syntax/scanner.ts +++ b/src/services/syntax/scanner.ts @@ -700,7 +700,7 @@ module TypeScript.Scanner { while (true) { if (index === end) { - reportDiagnostic(end, 0, DiagnosticCode.AsteriskSlash_expected, null); + reportDiagnostic(end, 0, DiagnosticCode.AsteriskSlash_expected, undefined); return; } @@ -916,7 +916,7 @@ module TypeScript.Scanner { if (languageVersion >= ts.ScriptTarget.ES5) { reportDiagnostic( - start, index - start, DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, null); + start, index - start, DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, undefined); } } @@ -1223,7 +1223,7 @@ module TypeScript.Scanner { switch (ch) { case CharacterCodes.backslash: // We're now in an escape. Consume the next character we see (unless it's - // a newline or null. + // a newline or undefined. inEscape = true; continue; @@ -1364,7 +1364,7 @@ module TypeScript.Scanner { break; } else if (isNaN(ch) || isNewLineCharacter(ch)) { - reportDiagnostic(Math.min(index, end), 1, DiagnosticCode.Missing_close_quote_character, null); + reportDiagnostic(Math.min(index, end), 1, DiagnosticCode.Missing_close_quote_character, undefined); break; } else { @@ -1431,7 +1431,7 @@ module TypeScript.Scanner { var ch2 = str.charCodeAt(index); if (!CharacterInfo.isHexDigit(ch2)) { if (report) { - reportDiagnostic(start, index - start, DiagnosticCode.Unrecognized_escape_sequence, null) + reportDiagnostic(start, index - start, DiagnosticCode.Unrecognized_escape_sequence, undefined) } break; @@ -1511,30 +1511,30 @@ module TypeScript.Scanner { var rewindPointPool: IScannerRewindPoint[] = []; var rewindPointPoolCount = 0; - var lastDiagnostic: Diagnostic = null; + var lastDiagnostic: Diagnostic = undefined; var reportDiagnostic = (position: number, fullWidth: number, diagnosticKey: string, args: any[]) => { lastDiagnostic = new Diagnostic(fileName, text.lineMap(), position, fullWidth, diagnosticKey, args); }; // The sliding window that we store tokens in. - var slidingWindow = new SlidingWindow(fetchNextItem, ArrayUtilities.createArray(/*defaultWindowSize:*/ 1024, null), null); + var slidingWindow = new SlidingWindow(fetchNextItem, ArrayUtilities.createArray(/*defaultWindowSize:*/ 1024, undefined), undefined); // The scanner we're pulling tokens from. var scanner = createScanner(languageVersion, text, reportDiagnostic); function release() { - slidingWindow = null; - scanner = null; + slidingWindow = undefined; + scanner = undefined; _tokenDiagnostics = []; rewindPointPool = []; - lastDiagnostic = null; - reportDiagnostic = null; + lastDiagnostic = undefined; + reportDiagnostic = undefined; } function currentNode(): ISyntaxNode { // The normal parser source never returns nodes. They're only returned by the // incremental parser source. - return null; + return undefined; } function consumeNode(node: ISyntaxNode): void { @@ -1557,7 +1557,7 @@ module TypeScript.Scanner { rewindPointPoolCount--; var result = rewindPointPool[rewindPointPoolCount]; - rewindPointPool[rewindPointPoolCount] = null; + rewindPointPool[rewindPointPoolCount] = undefined; return result; } @@ -1593,7 +1593,7 @@ module TypeScript.Scanner { // Debug.assert(spaceAvailable > 0); var token = scanner.scan(allowContextualToken); - if (lastDiagnostic === null) { + if (lastDiagnostic === undefined) { return token; } @@ -1601,7 +1601,7 @@ module TypeScript.Scanner { // it won't be reused in incremental scenarios. _tokenDiagnostics.push(lastDiagnostic); - lastDiagnostic = null; + lastDiagnostic = undefined; return Syntax.realizeToken(token, text); } diff --git a/src/services/syntax/slidingWindow.ts b/src/services/syntax/slidingWindow.ts index d90fa4892c9..4bb79023f2f 100644 --- a/src/services/syntax/slidingWindow.ts +++ b/src/services/syntax/slidingWindow.ts @@ -167,7 +167,7 @@ module TypeScript { // Assert disabled because it is actually expensive enugh to affect perf. // Debug.assert(n >= 0); while (this.currentRelativeItemIndex + n >= this.windowCount) { - if (!this.addMoreItemsToWindow(/*argument:*/ null)) { + if (!this.addMoreItemsToWindow(/*argument:*/ undefined)) { return this.defaultValue; } } diff --git a/src/services/syntax/syntax.ts b/src/services/syntax/syntax.ts index 2cc55ba0620..b81856e29bd 100644 --- a/src/services/syntax/syntax.ts +++ b/src/services/syntax/syntax.ts @@ -63,8 +63,8 @@ module TypeScript.Syntax { export function isEntirelyInsideComment(sourceUnit: SourceUnitSyntax, position: number): boolean { var positionedToken = findToken(sourceUnit, position); var fullStart = positionedToken.fullStart(); - var triviaList: ISyntaxTriviaList = null; - var lastTriviaBeforeToken: ISyntaxTrivia = null; + var triviaList: ISyntaxTriviaList = undefined; + var lastTriviaBeforeToken: ISyntaxTrivia = undefined; if (positionedToken.kind() === SyntaxKind.EndOfFileToken) { // Check if the trivia is leading on the EndOfFile token @@ -133,7 +133,7 @@ module TypeScript.Syntax { } function findSkippedTokenOnLeftInTriviaList(positionedToken: ISyntaxToken, position: number, lookInLeadingTriviaList: boolean): ISyntaxToken { - var triviaList: TypeScript.ISyntaxTriviaList = null; + var triviaList: TypeScript.ISyntaxTriviaList = undefined; var fullEnd: number; if (lookInLeadingTriviaList) { @@ -158,7 +158,7 @@ module TypeScript.Syntax { } } - return null; + return undefined; } export function findSkippedTokenOnLeft(positionedToken: ISyntaxToken, position: number): ISyntaxToken { @@ -175,11 +175,11 @@ module TypeScript.Syntax { positionedToken = positionedToken.parent; } - return null; + return undefined; } export function hasAncestorOfKind(positionedToken: ISyntaxElement, kind: SyntaxKind): boolean { - return getAncestorOfKind(positionedToken, kind) !== null; + return !!getAncestorOfKind(positionedToken, kind); } export function isIntegerLiteral(expression: IExpressionSyntax): boolean { @@ -207,7 +207,7 @@ module TypeScript.Syntax { export function containingNode(element: ISyntaxElement): ISyntaxNode { var current = element.parent; - while (current !== null && !isNode(current)) { + while (current && !isNode(current)) { current = current.parent; } @@ -234,7 +234,7 @@ module TypeScript.Syntax { // we're in the trivia before the start of the token. Need to return the previous token. if (positionedToken.fullStart() === 0) { // Already on the first token. Nothing before us. - return null; + return undefined; } return previousToken(positionedToken, includeSkippedTokens); @@ -274,7 +274,7 @@ module TypeScript.Syntax { function isFirstTokenInLine(token: ISyntaxToken, lineMap: LineMap): boolean { var _previousToken = previousToken(token); - if (_previousToken === null) { + if (_previousToken === undefined) { return true; } diff --git a/src/services/syntax/syntaxElement.ts b/src/services/syntax/syntaxElement.ts index 211e8b1dd86..53d16e7ef67 100644 --- a/src/services/syntax/syntaxElement.ts +++ b/src/services/syntax/syntaxElement.ts @@ -54,7 +54,7 @@ module TypeScript { } } - return null; + return undefined; } export function parsedInStrictMode(node: ISyntaxNode): boolean { @@ -84,7 +84,7 @@ module TypeScript { var start = token.fullStart(); if (start === 0) { - return null; + return undefined; } return findToken(syntaxTree(token).sourceUnit(), start - 1, includeSkippedTokens); @@ -105,7 +105,7 @@ module TypeScript { */ export function findToken(element: ISyntaxElement, position: number, includeSkippedTokens: boolean = false): ISyntaxToken { var endOfFileToken = tryGetEndOfFileAt(element, position); - if (endOfFileToken !== null) { + if (endOfFileToken) { return endOfFileToken; } @@ -137,7 +137,7 @@ module TypeScript { } function findSkippedTokenInTriviaList(positionedToken: ISyntaxToken, position: number, lookInLeadingTriviaList: boolean): ISyntaxToken { - var triviaList: TypeScript.ISyntaxTriviaList = null; + var triviaList: TypeScript.ISyntaxTriviaList = undefined; var fullStart: number; if (lookInLeadingTriviaList) { @@ -162,7 +162,7 @@ module TypeScript { } } - return null; + return undefined; } function findTokenWorker(element: ISyntaxElement, position: number): ISyntaxToken { @@ -182,7 +182,7 @@ module TypeScript { for (var i = 0, n = childCount(element); i < n; i++) { var child = childAt(element, i); - if (child !== null) { + if (child) { var childFullWidth = fullWidth(child); if (childFullWidth > 0) { var childFullStart = fullStart(child); @@ -207,12 +207,12 @@ module TypeScript { return sourceUnit.endOfFileToken; } - return null; + return undefined; } export function nextToken(token: ISyntaxToken, text?: ISimpleText, includeSkippedTokens: boolean = false): ISyntaxToken { if (token.kind() === SyntaxKind.EndOfFileToken) { - return null; + return undefined; } if (includeSkippedTokens) { @@ -231,7 +231,7 @@ module TypeScript { } export function isNode(element: ISyntaxElement): boolean { - if (element !== null) { + if (element) { var kind = element.kind(); return kind >= SyntaxKind.FirstNode && kind <= SyntaxKind.LastNode; } @@ -244,7 +244,7 @@ module TypeScript { } export function isToken(element: ISyntaxElement): boolean { - if (element !== null) { + if (element) { return isTokenKind(element.kind()); } @@ -252,11 +252,11 @@ module TypeScript { } export function isList(element: ISyntaxElement): boolean { - return element !== null && element.kind() === SyntaxKind.List; + return element && element.kind() === SyntaxKind.List; } export function isSeparatedList(element: ISyntaxElement): boolean { - return element !== null && element.kind() === SyntaxKind.SeparatedList; + return element && element.kind() === SyntaxKind.SeparatedList; } export function syntaxID(element: ISyntaxElement): number { @@ -311,7 +311,7 @@ module TypeScript { var kind = element.kind(); if (isTokenKind(kind)) { - return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? element : null; + return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? element : undefined; } if (kind === SyntaxKind.List) { @@ -349,12 +349,12 @@ module TypeScript { } } - return null; + return undefined; } export function lastToken(element: ISyntaxElement): ISyntaxToken { if (isToken(element)) { - return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? element : null; + return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? element : undefined; } if (element.kind() === SyntaxKind.SourceUnit) { @@ -363,7 +363,7 @@ module TypeScript { for (var i = childCount(element) - 1; i >= 0; i--) { var child = childAt(element, i); - if (child !== null) { + if (child) { var token = lastToken(child); if (token) { return token; @@ -371,7 +371,7 @@ module TypeScript { } } - return null; + return undefined; } export function fullStart(element: ISyntaxElement): number { @@ -474,7 +474,7 @@ module TypeScript { return false; } - if (token1 === null || token2 === null) { + if (!token1 || !token2) { return true; } diff --git a/src/services/syntax/syntaxFacts.ts b/src/services/syntax/syntaxFacts.ts index 3b8d877429c..fcd152a19b1 100644 --- a/src/services/syntax/syntaxFacts.ts +++ b/src/services/syntax/syntaxFacts.ts @@ -134,7 +134,7 @@ module TypeScript.SyntaxFacts { export function getText(kind: SyntaxKind): string { var result = kindToText[kind]; - return result !== undefined ? result : null; + return result;// !== undefined ? result : undefined; } export function isAnyKeyword(kind: SyntaxKind): boolean { diff --git a/src/services/syntax/syntaxGenerator.ts b/src/services/syntax/syntaxGenerator.ts index ebc2673b98c..109bc023850 100644 --- a/src/services/syntax/syntaxGenerator.ts +++ b/src/services/syntax/syntaxGenerator.ts @@ -1065,7 +1065,7 @@ function generateProperties(definition: ITypeDefinition): string { var result = ""; if (definition.name === "SourceUnitSyntax") { - result += " public syntaxTree: SyntaxTree = null;\r\n"; + result += " public syntaxTree: SyntaxTree = undefined;\r\n"; } var newLine = false; @@ -1097,7 +1097,7 @@ function generateNullChecks(definition: ITypeDefinition): string { var child = definition.children[i]; if (!child.isOptional && !child.isToken) { - result += " if (" + child.name + " === null) { throw Errors.argumentNull('" + child.name + "'); }\r\n"; + result += " if (!" + child.name + ") { throw Errors.argumentNull('" + child.name + "'); }\r\n"; } } @@ -1211,7 +1211,7 @@ function generateKindCheck(child: IMemberDefinition): string { if (child.isOptional) { indent = " "; - result += " if (" + child.name + " !== null) {\r\n"; + result += " if (" + child.name + ") {\r\n"; } var kinds = tokenKinds(child); @@ -1268,7 +1268,7 @@ function generateConstructor(definition: ITypeDefinition): string { result += " constructor(" var children = definition.children; - var kindChild: IMemberDefinition = null; + var kindChild: IMemberDefinition = undefined; for (i = 0; i < children.length; i++) { child = children[i]; @@ -1385,7 +1385,7 @@ function generateFactory1Method(definition: ITypeDefinition): string { result += "Syntax.emptySeparatedList<" + child.elementType + ">()"; } else { - result += "null"; + result += "undefined"; } result += ", "; @@ -1412,7 +1412,7 @@ function isKeywordOrPunctuation(kind: string): boolean { } function isDefaultConstructable(definition: ITypeDefinition): boolean { - if (definition === null) { + if (!definition) { return false; } @@ -1489,7 +1489,7 @@ function generateFactory2Method(definition: ITypeDefinition): string { result += "Syntax.emptySeparatedList<" + child.elementType + ">()"; } else if (isOptional(child)) { - result += "null"; + result += "undefined"; } else if (child.isToken) { result += "Syntax.token(SyntaxKind." + tokenKinds(child)[0] + ")"; @@ -1615,7 +1615,7 @@ function generateFirstTokenMethod(definition: ITypeDefinition): string { result += "\r\n"; result += " public firstToken(): ISyntaxToken {\r\n"; - result += " var token = null;\r\n"; + result += " var token: ISyntaxToken = undefined;\r\n"; for (var i = 0; i < definition.children.length; i++) { var child = definition.children[i]; @@ -1631,7 +1631,7 @@ function generateFirstTokenMethod(definition: ITypeDefinition): string { result += " if ("; if (child.isOptional) { - result += getPropertyAccess(child) + " !== null && "; + result += getPropertyAccess(child) + " && "; } if (child.isToken) { @@ -1639,7 +1639,7 @@ function generateFirstTokenMethod(definition: ITypeDefinition): string { result += ") { return " + getPropertyAccess(child) + "; }\r\n"; } else { - result += "(token = " + getPropertyAccess(child) + ".firstToken()) !== null"; + result += "(token = " + getPropertyAccess(child) + ".firstToken())"; result += ") { return token; }\r\n"; } } @@ -1648,7 +1648,7 @@ function generateFirstTokenMethod(definition: ITypeDefinition): string { result += " return this._endOfFileToken;\r\n"; } else { - result += " return null;\r\n"; + result += " return undefined;\r\n"; } result += " }\r\n"; @@ -1668,7 +1668,7 @@ function generateLastTokenMethod(definition: ITypeDefinition): string { result += " return this._endOfFileToken;\r\n"; } else { - result += " var token = null;\r\n"; + result += " var token: ISyntaxToken = undefined;\r\n"; for (var i = definition.children.length - 1; i >= 0; i--) { var child = definition.children[i]; @@ -1684,7 +1684,7 @@ function generateLastTokenMethod(definition: ITypeDefinition): string { result += " if ("; if (child.isOptional) { - result += getPropertyAccess(child) + " !== null && "; + result += getPropertyAccess(child) + " && "; } if (child.isToken) { @@ -1692,12 +1692,12 @@ function generateLastTokenMethod(definition: ITypeDefinition): string { result += ") { return " + getPropertyAccess(child) + "; }\r\n"; } else { - result += "(token = " + getPropertyAccess(child) + ".lastToken()) !== null"; + result += "(token = " + getPropertyAccess(child) + ".lastToken())"; result += ") { return token; }\r\n"; } } - result += " return null;\r\n"; + result += " return undefined;\r\n"; } result += " }\r\n"; @@ -1716,7 +1716,7 @@ function memberDefinitionType(child: IMemberDefinition): ITypeDefinition { function derivesFrom(def1: ITypeDefinition, def2: ITypeDefinition): boolean { var current = def1; - while (current !== null) { + while (current) { var base = baseType(current); if (base === def2) { return true; @@ -1909,7 +1909,7 @@ function generateNode(definition: ITypeDefinition, abstract: boolean): string { result += " {\r\n"; if (definition.name === "SourceUnitSyntax") { - result += " public syntaxTree: SyntaxTree = null;\r\n"; + result += " public syntaxTree: SyntaxTree = undefined;\r\n"; } for (var i = 0; i < definition.children.length; i++) { @@ -1930,7 +1930,7 @@ function generateNode(definition: ITypeDefinition, abstract: boolean): string { result += " super(data);\r\n"; if (definition.name === "SourceUnitSyntax") { - result += " this.parent = null,\r\n"; + result += " this.parent = undefined,\r\n"; } if (definition.children) { @@ -2173,13 +2173,13 @@ function generateRewriter(): string { " }\r\n" + "\r\n" + " public visitList(list: T[]): T[] {\r\n" + -" var newItems: T[] = null;\r\n" + +" var newItems: T[] = undefined;\r\n" + "\r\n" + " for (var i = 0, n = list.length; i < n; i++) {\r\n" + " var item = list[i];\r\n" + " var newItem = this.visitNodeOrToken(item);\r\n" + "\r\n" + -" if (item !== newItem && newItems === null) {\r\n" + +" if (item !== newItem && !newItems) {\r\n" + " newItems = [];\r\n" + " for (var j = 0; j < i; j++) {\r\n" + " newItems.push(list[j]);\r\n" + @@ -2191,18 +2191,18 @@ function generateRewriter(): string { " }\r\n" + " }\r\n" + "\r\n" + -" // Debug.assert(newItems === null || newItems.length === childCount(list));\r\n" + -" return newItems === null ? list : Syntax.list(newItems);\r\n" + +" // Debug.assert(!newItems || newItems.length === childCount(list));\r\n" + +" return !newItems ? list : Syntax.list(newItems);\r\n" + " }\r\n" + "\r\n" + " public visitSeparatedList(list: T[]): T[] {\r\n" + -" var newItems: ISyntaxNodeOrToken[] = null;\r\n" + +" var newItems: ISyntaxNodeOrToken[] = undefined;\r\n" + "\r\n" + " for (var i = 0, n = childCount(list); i < n; i++) {\r\n" + " var item = childAt(list, i);\r\n" + " var newItem = isToken(item) ? this.visitToken(item) : this.visitNode(item);\r\n" + "\r\n" + -" if (item !== newItem && newItems === null) {\r\n" + +" if (item !== newItem && !newItems) {\r\n" + " newItems = [];\r\n" + " for (var j = 0; j < i; j++) {\r\n" + " newItems.push(childAt(list, j));\r\n" + @@ -2214,8 +2214,8 @@ function generateRewriter(): string { " }\r\n" + " }\r\n" + "\r\n" + -" // Debug.assert(newItems === null || newItems.length === childCount(list));\r\n" + -" return newItems === null ? list : Syntax.separatedList(newItems);\r\n" + +" // Debug.assert(newItems === undefined || newItems.length === childCount(list));\r\n" + +" return !newItems ? list : Syntax.separatedList(newItems);\r\n" + " }\r\n"; for (var i = 0; i < definitions.length; i++) { @@ -2242,7 +2242,7 @@ function generateRewriter(): string { result += " "; if (child.isOptional) { - result += "node." + child.name + " === null ? null : "; + result += "!node." + child.name + " ? undefined : "; } if (child.isToken) { @@ -2303,7 +2303,7 @@ function generateWalker(): string { " }\r\n" + "\r\n" + " private visitOptionalToken(token: ISyntaxToken): void {\r\n" + -" if (token === null) {\r\n" + +" if (token === undefined) {\r\n" + " return;\r\n" + " }\r\n" + "\r\n" + @@ -2311,7 +2311,7 @@ function generateWalker(): string { " }\r\n" + "\r\n" + " public visitOptionalNode(node: ISyntaxNode): void {\r\n" + -" if (node === null) {\r\n" + +" if (node === undefined) {\r\n" + " return;\r\n" + " }\r\n" + "\r\n" + @@ -2319,7 +2319,7 @@ function generateWalker(): string { " }\r\n" + "\r\n" + " public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + -" if (nodeOrToken === null) {\r\n" + +" if (nodeOrToken === undefined) {\r\n" + " return;\r\n" + " }\r\n" + "\r\n" + @@ -2535,7 +2535,7 @@ function generateVisitor(): string { result += "module TypeScript {\r\n"; result += " export function visitNodeOrToken(visitor: ISyntaxVisitor, element: ISyntaxNodeOrToken): any {\r\n"; - result += " if (element === null) { return null; }\r\n"; + result += " if (element === undefined) { return undefined; }\r\n"; result += " if (isToken(element)) { return visitor.visitToken(element); }\r\n"; result += " switch (element.kind()) {\r\n"; @@ -2584,7 +2584,7 @@ function generateDefaultVisitor(): string { if (!forPrettyPrinter) { result += " export class SyntaxVisitor implements ISyntaxVisitor {\r\n"; result += " public defaultVisit(node: ISyntaxNodeOrToken): any {\r\n"; - result += " return null;\r\n"; + result += " return undefined;\r\n"; result += " }\r\n"; result += "\r\n"; result += " public visitToken(token: ISyntaxToken): any {\r\n"; @@ -2738,7 +2738,7 @@ function generateIsTypeScriptSpecific(): string { result += " }\r\n\r\n"; result += " export function isTypeScriptSpecific(element: ISyntaxElement): boolean {\r\n" - result += " if (element === null) { return false; }\r\n"; + result += " if (!element) { return false; }\r\n"; result += " if (isToken(element)) { return false; }\r\n"; result += " if (isList(element)) { return isListTypeScriptSpecific(element); }\r\n"; result += " if (isSeparatedList(element)) { return isSeparatedListTypeScriptSpecific(element); }\r\n\r\n"; @@ -2855,7 +2855,7 @@ function generateIsTypeScriptSpecificMethod(definition: ITypeDefinition): string result += getPropertyAccess(child, "node") + ".childCount() > 0"; } else { - result += getPropertyAccess(child, "node") + " !== null"; + result += "!!" + getPropertyAccess(child, "node"); } } else { diff --git a/src/services/syntax/syntaxList.ts b/src/services/syntax/syntaxList.ts index 52bc02ecdca..df33153def6 100644 --- a/src/services/syntax/syntaxList.ts +++ b/src/services/syntax/syntaxList.ts @@ -51,7 +51,7 @@ module TypeScript.Syntax { } export function list(nodes: T[]): T[] { - if (nodes === undefined || nodes === null || nodes.length === 0) { + if (!nodes || nodes.length === 0) { return emptyList(); } @@ -63,7 +63,7 @@ module TypeScript.Syntax { } export function separatedList(nodes: T[], separators: ISyntaxToken[]): T[] { - if (nodes === undefined || nodes === null || nodes.length === 0) { + if (!nodes || nodes.length === 0) { return emptySeparatedList(); } diff --git a/src/services/syntax/syntaxNodes.abstract.generated.ts b/src/services/syntax/syntaxNodes.abstract.generated.ts index 9cba7f66d00..530bbb13fe6 100644 --- a/src/services/syntax/syntaxNodes.abstract.generated.ts +++ b/src/services/syntax/syntaxNodes.abstract.generated.ts @@ -6,12 +6,12 @@ module TypeScript.Syntax.Abstract { export var isConcrete: boolean = false; export class SourceUnitSyntax extends SyntaxNode { - public syntaxTree: SyntaxTree = null; + public syntaxTree: SyntaxTree = undefined; public moduleElements: IModuleElementSyntax[]; public endOfFileToken: ISyntaxToken; constructor(data: number, moduleElements: IModuleElementSyntax[], endOfFileToken: ISyntaxToken) { super(data); - this.parent = null, + this.parent = undefined, this.moduleElements = moduleElements, this.endOfFileToken = endOfFileToken, !isShared(moduleElements) && (moduleElements.parent = this), diff --git a/src/services/syntax/syntaxNodes.concrete.generated.ts b/src/services/syntax/syntaxNodes.concrete.generated.ts index fa593fd1976..5839297d154 100644 --- a/src/services/syntax/syntaxNodes.concrete.generated.ts +++ b/src/services/syntax/syntaxNodes.concrete.generated.ts @@ -6,12 +6,12 @@ module TypeScript.Syntax.Concrete { export var isConcrete: boolean = true; export class SourceUnitSyntax extends SyntaxNode { - public syntaxTree: SyntaxTree = null; + public syntaxTree: SyntaxTree = undefined; public moduleElements: IModuleElementSyntax[]; public endOfFileToken: ISyntaxToken; constructor(data: number, moduleElements: IModuleElementSyntax[], endOfFileToken: ISyntaxToken) { super(data); - this.parent = null, + this.parent = undefined, this.moduleElements = moduleElements, this.endOfFileToken = endOfFileToken, !isShared(moduleElements) && (moduleElements.parent = this), diff --git a/src/services/syntax/syntaxToken.ts b/src/services/syntax/syntaxToken.ts index 4f3906e1fe9..857ffde59c0 100644 --- a/src/services/syntax/syntaxToken.ts +++ b/src/services/syntax/syntaxToken.ts @@ -71,7 +71,7 @@ module TypeScript { module TypeScript { export function tokenValue(token: ISyntaxToken): any { if (token.fullWidth() === 0) { - return null; + return undefined; } var kind = token.kind(); @@ -87,7 +87,7 @@ module TypeScript { case SyntaxKind.FalseKeyword: return false; case SyntaxKind.NullKeyword: - return null; + return undefined; } if (SyntaxFacts.isAnyKeyword(kind) || SyntaxFacts.isAnyPunctuation(kind)) { @@ -112,7 +112,7 @@ module TypeScript { return regularExpressionValue(text); } else if (kind === SyntaxKind.EndOfFileToken || kind === SyntaxKind.ErrorToken) { - return null; + return undefined; } else { throw Errors.invalidOperation(); @@ -121,7 +121,7 @@ module TypeScript { export function tokenValueText(token: ISyntaxToken): string { var value = tokenValue(token); - return value === null ? "" : massageDisallowedIdentifiers(value.toString()); + return value === undefined ? "" : massageDisallowedIdentifiers(value.toString()); } export function massageEscapes(text: string): string { @@ -136,7 +136,7 @@ module TypeScript { return new RegExp(body, flags); } catch (e) { - return null; + return undefined; } } @@ -235,13 +235,13 @@ module TypeScript { characterArray.push(ch); if (i && !(i % 1024)) { - result = result.concat(String.fromCharCode.apply(null, characterArray)); + result = result.concat(String.fromCharCode.apply(undefined, characterArray)); characterArray.length = 0; } } if (characterArray.length) { - result = result.concat(String.fromCharCode.apply(null, characterArray)); + result = result.concat(String.fromCharCode.apply(undefined, characterArray)); } return result; @@ -330,14 +330,14 @@ module TypeScript.Syntax { // the full-start of this token to be at the full-end of that element. var previousElement = this.previousNonZeroWidthElement(); - return previousElement === null ? 0 : fullStart(previousElement) + fullWidth(previousElement); + return !previousElement ? 0 : fullStart(previousElement) + fullWidth(previousElement); } private previousNonZeroWidthElement(): ISyntaxElement { var current: ISyntaxElement = this; while (true) { var parent = current.parent; - if (parent === null) { + if (parent === undefined) { Debug.assert(current.kind() === SyntaxKind.SourceUnit, "We had a node without a parent that was not the root node!"); // We walked all the way to the top, and never found a previous element. This @@ -346,9 +346,9 @@ module TypeScript.Syntax { // / b; // // We will have an empty identifier token as the first token in the tree. In - // this case, return null so that the position of the empty token will be + // this case, return undefined so that the position of the empty token will be // considered to be 0. - return null; + return undefined; } // Ok. We have a parent. First, find out which slot we're at in the parent. diff --git a/src/services/syntax/syntaxTree.ts b/src/services/syntax/syntaxTree.ts index 1c68350d918..23e475d2463 100644 --- a/src/services/syntax/syntaxTree.ts +++ b/src/services/syntax/syntaxTree.ts @@ -8,7 +8,7 @@ module TypeScript { private _sourceUnit: SourceUnitSyntax; private _isDeclaration: boolean; private _parserDiagnostics: Diagnostic[]; - private _allDiagnostics: Diagnostic[] = null; + private _allDiagnostics: Diagnostic[] = undefined; private _fileName: string; private _lineMap: LineMap; private _languageVersion: ts.ScriptTarget; @@ -60,7 +60,7 @@ module TypeScript { } public diagnostics(): Diagnostic[] { - if (this._allDiagnostics === null) { + if (!this._allDiagnostics) { var start = new Date().getTime(); this._allDiagnostics = this.computeDiagnostics(); syntaxDiagnosticsTime += new Date().getTime() - start; @@ -87,7 +87,7 @@ module TypeScript { var firstToken = firstSyntaxTreeToken(this); var leadingTrivia = firstToken.leadingTrivia(this.text); - this._isExternalModule = externalModuleIndicatorSpanWorker(this, firstToken) !== null; + this._isExternalModule = !!externalModuleIndicatorSpanWorker(this, firstToken); var amdDependencies: string[] = []; for (var i = 0, n = leadingTrivia.count(); i < n; i++) { @@ -106,7 +106,7 @@ module TypeScript { private getAmdDependency(comment: string): string { var amdDependencyRegEx = /^\/\/\/\s*moduleElement).modifiers, SyntaxKind.ExportKeyword); default: - return null; + return undefined; } } diff --git a/src/services/syntax/syntaxVisitor.generated.ts b/src/services/syntax/syntaxVisitor.generated.ts index 55aaef53255..493743f334e 100644 --- a/src/services/syntax/syntaxVisitor.generated.ts +++ b/src/services/syntax/syntaxVisitor.generated.ts @@ -2,7 +2,7 @@ module TypeScript { export function visitNodeOrToken(visitor: ISyntaxVisitor, element: ISyntaxNodeOrToken): any { - if (element === null) { return null; } + if (element === undefined) { return undefined; } if (isToken(element)) { return visitor.visitToken(element); } switch (element.kind()) { case SyntaxKind.SourceUnit: return visitor.visitSourceUnit(element); diff --git a/src/services/syntax/syntaxWalker.generated.ts b/src/services/syntax/syntaxWalker.generated.ts index 7b335709853..58b7404842c 100644 --- a/src/services/syntax/syntaxWalker.generated.ts +++ b/src/services/syntax/syntaxWalker.generated.ts @@ -19,7 +19,7 @@ module TypeScript { } private visitOptionalToken(token: ISyntaxToken): void { - if (token === null) { + if (token === undefined) { return; } @@ -27,7 +27,7 @@ module TypeScript { } public visitOptionalNode(node: ISyntaxNode): void { - if (node === null) { + if (node === undefined) { return; } @@ -35,7 +35,7 @@ module TypeScript { } public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void { - if (nodeOrToken === null) { + if (nodeOrToken === undefined) { return; } diff --git a/src/services/syntax/testUtilities.ts b/src/services/syntax/testUtilities.ts index 2dd0055e068..6144c6cffb7 100644 --- a/src/services/syntax/testUtilities.ts +++ b/src/services/syntax/testUtilities.ts @@ -7,7 +7,7 @@ module TypeScript { export function nodeStructuralEquals(node1: TypeScript.ISyntaxNode, node2: TypeScript.ISyntaxNode, checkParents: boolean, text1: ISimpleText, text2: ISimpleText): boolean { if (node1 === node2) { return true; } - if (node1 === null || node2 === null) { return false; } + if (!node1 || !node2) { return false; } Debug.assert(node1.kind() === TypeScript.SyntaxKind.SourceUnit || node1.parent); Debug.assert(node2.kind() === TypeScript.SyntaxKind.SourceUnit || node2.parent); @@ -37,7 +37,7 @@ module TypeScript { return true; } - if (node1 === null || node2 === null) { + if (!node1 || !node2) { return false; } @@ -56,7 +56,7 @@ module TypeScript { return true; } - if (token1 === null || token2 === null) { + if (!token1 || !token2) { return false; } @@ -156,7 +156,7 @@ module TypeScript { return true; } - if (element1 === null || element2 === null) { + if (!element1 || !element2) { return false; } diff --git a/src/services/text/scriptSnapshot.ts b/src/services/text/scriptSnapshot.ts index 574657f6c40..4e61d131cec 100644 --- a/src/services/text/scriptSnapshot.ts +++ b/src/services/text/scriptSnapshot.ts @@ -32,7 +32,7 @@ module TypeScript { export module ScriptSnapshot { class StringScriptSnapshot implements IScriptSnapshot { - private _lineStartPositions: number[] = null; + private _lineStartPositions: number[] = undefined; constructor(private text: string) { } diff --git a/src/services/text/textFactory.ts b/src/services/text/textFactory.ts index 21d215c291e..235a451b158 100644 --- a/src/services/text/textFactory.ts +++ b/src/services/text/textFactory.ts @@ -2,7 +2,7 @@ module TypeScript.SimpleText { class SimpleStringText implements ISimpleText { - private _lineMap: LineMap = null; + private _lineMap: LineMap = undefined; constructor(private value: string) { } @@ -30,7 +30,7 @@ module TypeScript.SimpleText { // Class which wraps a host IScriptSnapshot and exposes an ISimpleText for newer compiler code. class SimpleScriptSnapshotText implements ISimpleText { - private _lineMap: LineMap = null; + private _lineMap: LineMap = undefined; constructor(public scriptSnapshot: IScriptSnapshot) { } @@ -48,7 +48,7 @@ module TypeScript.SimpleText { } public lineMap(): LineMap { - if (this._lineMap === null) { + if (!this._lineMap) { this._lineMap = new LineMap(() => this.scriptSnapshot.getLineStartPositions(), this.length()); } diff --git a/src/services/text/textSpan.ts b/src/services/text/textSpan.ts index 999070a73b4..9ecef2b95fa 100644 --- a/src/services/text/textSpan.ts +++ b/src/services/text/textSpan.ts @@ -79,7 +79,7 @@ module TypeScript { } /** - * Returns the overlap with the given span, or null if there is no overlap. + * Returns the overlap with the given span, or undefined if there is no overlap. * @param span The span to check. */ public overlap(span: TextSpan): TextSpan { @@ -90,7 +90,7 @@ module TypeScript { return TextSpan.fromBounds(overlapStart, overlapEnd); } - return null; + return undefined; } /** @@ -119,7 +119,7 @@ module TypeScript { } /** - * Returns the intersection with the given span, or null if there is no intersection. + * Returns the intersection with the given span, or undefined if there is no intersection. * @param span The span to check. */ public intersection(span: TextSpan): TextSpan { @@ -130,7 +130,7 @@ module TypeScript { return TextSpan.fromBounds(intersectStart, intersectEnd); } - return null; + return undefined; } /** From 0e2058c0ab64cde487126aedad720348c8abd8d9 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Thu, 30 Oct 2014 01:19:41 -0700 Subject: [PATCH 7/9] Adding support in fidelity for parsing union and parenthesized types --- src/services/compiler/astHelpers.ts | 69 -- src/services/compiler/astWalker.ts | 721 ------------------ .../syntax/defaultSyntaxVisitor.generated.ts | 8 + src/services/syntax/parser.ts | 113 ++- src/services/syntax/prettyPrinter.ts | 14 + src/services/syntax/syntaxGenerator.ts | 23 + src/services/syntax/syntaxKind.ts | 2 + .../syntax/syntaxNodes.abstract.generated.ts | 26 +- .../syntax/syntaxNodes.concrete.generated.ts | 32 +- .../syntaxNodes.interfaces.generated.ts | 14 +- .../syntax/syntaxVisitor.generated.ts | 4 + src/services/syntax/syntaxWalker.generated.ts | 12 + 12 files changed, 232 insertions(+), 806 deletions(-) diff --git a/src/services/compiler/astHelpers.ts b/src/services/compiler/astHelpers.ts index 589ef4b6340..44eee84ebf0 100644 --- a/src/services/compiler/astHelpers.ts +++ b/src/services/compiler/astHelpers.ts @@ -70,75 +70,6 @@ module TypeScript.ASTHelpers { return true; } - /// - /// Return the ISyntaxElement containing "position" - /// - export function getAstAtPosition(script: ISyntaxElement, pos: number, useTrailingTriviaAsLimChar: boolean = true, forceInclusive: boolean = false): ISyntaxElement { - var top: ISyntaxElement = null; - - var pre = function (cur: ISyntaxElement, walker: IAstWalker) { - if (!isShared(cur) && isValidAstNode(cur)) { - var isInvalid1 = cur.kind() === SyntaxKind.ExpressionStatement && width(cur) === 0; - - if (isInvalid1) { - walker.options.goChildren = false; - } - else { - // Add "cur" to the stack if it contains our position - // For "identifier" nodes, we need a special case: A position equal to "limChar" is - // valid, since the position corresponds to a caret position (in between characters) - // For example: - // bar - // 0123 - // If "position === 3", the caret is at the "right" of the "r" character, which should be considered valid - var inclusive = - forceInclusive || - cur.kind() === SyntaxKind.IdentifierName || - cur.kind() === SyntaxKind.MemberAccessExpression || - cur.kind() === SyntaxKind.QualifiedName || - //cur.kind() === SyntaxKind.TypeRef || - cur.kind() === SyntaxKind.VariableDeclaration || - cur.kind() === SyntaxKind.VariableDeclarator || - cur.kind() === SyntaxKind.InvocationExpression || - pos === end(script) + lastToken(script).trailingTriviaWidth(); // Special "EOF" case - - var minChar = start(cur); - var limChar = end(cur) + (useTrailingTriviaAsLimChar ? trailingTriviaWidth(cur) : 0) + (inclusive ? 1 : 0); - if (pos >= minChar && pos < limChar) { - - // Ignore empty lists - if ((cur.kind() !== SyntaxKind.List && cur.kind() !== SyntaxKind.SeparatedList) || end(cur) > start(cur)) { - // TODO: Since ISyntaxElement is sometimes not correct wrt to position, only add "cur" if it's better - // than top of the stack. - if (top === null) { - top = cur; - } - else if (start(cur) >= start(top) && - (end(cur) + (useTrailingTriviaAsLimChar ? trailingTriviaWidth(cur) : 0)) <= (end(top) + (useTrailingTriviaAsLimChar ? trailingTriviaWidth(top) : 0))) { - // this new node appears to be better than the one we're - // storing. Make this the new node. - - // However, If the current top is a missing identifier, we - // don't want to replace it with another missing identifier. - // We want to return the first missing identifier found in a - // depth first walk of the tree. - if (width(top) !== 0 || width(cur) !== 0) { - top = cur; - } - } - } - } - - // Don't go further down the tree if pos is outside of [minChar, limChar] - walker.options.goChildren = (minChar <= pos && pos <= limChar); - } - } - }; - - getAstWalkerFactory().walk(script, pre); - return top; - } - export function getExtendsHeritageClause(clauses: HeritageClauseSyntax[]): HeritageClauseSyntax { return getHeritageClause(clauses, SyntaxKind.ExtendsHeritageClause); } diff --git a/src/services/compiler/astWalker.ts b/src/services/compiler/astWalker.ts index 9f6897c4e1e..e69de29bb2d 100644 --- a/src/services/compiler/astWalker.ts +++ b/src/services/compiler/astWalker.ts @@ -1,721 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/// - -module TypeScript { - function walkListChildren(preAst: ISyntaxNodeOrToken[], walker: AstWalker): void { - for (var i = 0, n = preAst.length; i < n; i++) { - walker.walk(preAst[i]); - } - } - - function walkThrowStatementChildren(preAst: ThrowStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkPrefixUnaryExpressionChildren(preAst: PrefixUnaryExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.operand); - } - - function walkPostfixUnaryExpressionChildren(preAst: PostfixUnaryExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.operand); - } - - function walkDeleteExpressionChildren(preAst: DeleteExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkTypeArgumentListChildren(preAst: TypeArgumentListSyntax, walker: AstWalker): void { - walker.walk(preAst.typeArguments); - } - - function walkTupleTypeChildren(preAst: TupleTypeSyntax, walker: AstWalker): void { - walker.walk(preAst.types); - } - - function walkTypeOfExpressionChildren(preAst: TypeOfExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkVoidExpressionChildren(preAst: VoidExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkArgumentListChildren(preAst: ArgumentListSyntax, walker: AstWalker): void { - walker.walk(preAst.typeArgumentList); - walker.walk(preAst.arguments); - } - - function walkArrayLiteralExpressionChildren(preAst: ArrayLiteralExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expressions); - } - - function walkSimplePropertyAssignmentChildren(preAst: SimplePropertyAssignmentSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.expression); - } - - function walkFunctionPropertyAssignmentChildren(preAst: FunctionPropertyAssignmentSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkGetAccessorChildren(preAst: GetAccessorSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkSeparatedListChildren(preAst: ISyntaxNodeOrToken[], walker: AstWalker): void { - for (var i = 0, n = preAst.length; i < n; i++) { - walker.walk(preAst[i]); - } - } - - function walkSetAccessorChildren(preAst: SetAccessorSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkObjectLiteralExpressionChildren(preAst: ObjectLiteralExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyAssignments); - } - - function walkCastExpressionChildren(preAst: CastExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.type); - walker.walk(preAst.expression); - } - - function walkParenthesizedExpressionChildren(preAst: ParenthesizedExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkElementAccessExpressionChildren(preAst: ElementAccessExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - walker.walk(preAst.argumentExpression); - } - - function walkMemberAccessExpressionChildren(preAst: MemberAccessExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - walker.walk(preAst.name); - } - - function walkQualifiedNameChildren(preAst: QualifiedNameSyntax, walker: AstWalker): void { - walker.walk(preAst.left); - walker.walk(preAst.right); - } - - function walkBinaryExpressionChildren(preAst: BinaryExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.left); - walker.walk(preAst.right); - } - - function walkEqualsValueClauseChildren(preAst: EqualsValueClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.value); - } - - function walkTypeParameterChildren(preAst: TypeParameterSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.constraint); - } - - function walkTypeParameterListChildren(preAst: TypeParameterListSyntax, walker: AstWalker): void { - walker.walk(preAst.typeParameters); - } - - function walkGenericTypeChildren(preAst: GenericTypeSyntax, walker: AstWalker): void { - walker.walk(preAst.name); - walker.walk(preAst.typeArgumentList); - } - - function walkTypeAnnotationChildren(preAst: TypeAnnotationSyntax, walker: AstWalker): void { - walker.walk(preAst.type); - } - - function walkTypeQueryChildren(preAst: TypeQuerySyntax, walker: AstWalker): void { - walker.walk(preAst.name); - } - - function walkInvocationExpressionChildren(preAst: InvocationExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - walker.walk(preAst.argumentList); - } - - function walkObjectCreationExpressionChildren(preAst: ObjectCreationExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - walker.walk(preAst.argumentList); - } - - function walkTrinaryExpressionChildren(preAst: ConditionalExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.condition); - walker.walk(preAst.whenTrue); - walker.walk(preAst.whenFalse); - } - - function walkFunctionExpressionChildren(preAst: FunctionExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkFunctionTypeChildren(preAst: FunctionTypeSyntax, walker: AstWalker): void { - walker.walk(preAst.typeParameterList); - walker.walk(preAst.parameterList); - walker.walk(preAst.type); - } - - function walkParenthesizedArrowFunctionExpressionChildren(preAst: ParenthesizedArrowFunctionExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - walker.walk(preAst.expression); - } - - function walkSimpleArrowFunctionExpressionChildren(preAst: SimpleArrowFunctionExpressionSyntax, walker: AstWalker): void { - walker.walk(preAst.parameter); - walker.walk(preAst.block); - walker.walk(preAst.expression); - } - - function walkMemberFunctionDeclarationChildren(preAst: MemberFunctionDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkFuncDeclChildren(preAst: FunctionDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkIndexMemberDeclarationChildren(preAst: IndexMemberDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.indexSignature); - } - - function walkIndexSignatureChildren(preAst: IndexSignatureSyntax, walker: AstWalker): void { - walker.walk(preAst.parameters); - walker.walk(preAst.typeAnnotation); - } - - function walkCallSignatureChildren(preAst: CallSignatureSyntax, walker: AstWalker): void { - walker.walk(preAst.typeParameterList); - walker.walk(preAst.parameterList); - walker.walk(preAst.typeAnnotation); - } - - function walkConstraintChildren(preAst: ConstraintSyntax, walker: AstWalker): void { - walker.walk(preAst.typeOrExpression); - } - - function walkConstructorDeclarationChildren(preAst: ConstructorDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.callSignature); - walker.walk(preAst.block); - } - - function walkConstructorTypeChildren(preAst: FunctionTypeSyntax, walker: AstWalker): void { - walker.walk(preAst.typeParameterList); - walker.walk(preAst.parameterList); - walker.walk(preAst.type); - } - - function walkConstructSignatureChildren(preAst: ConstructSignatureSyntax, walker: AstWalker): void { - walker.walk(preAst.callSignature); - } - - function walkParameterChildren(preAst: ParameterSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.typeAnnotation); - walker.walk(preAst.equalsValueClause); - } - - function walkParameterListChildren(preAst: ParameterListSyntax, walker: AstWalker): void { - walker.walk(preAst.parameters); - } - - function walkPropertySignatureChildren(preAst: PropertySignatureSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.typeAnnotation); - } - - function walkVariableDeclaratorChildren(preAst: VariableDeclaratorSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.typeAnnotation); - walker.walk(preAst.equalsValueClause); - } - - function walkMemberVariableDeclarationChildren(preAst: MemberVariableDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.variableDeclarator); - } - - function walkMethodSignatureChildren(preAst: MethodSignatureSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.callSignature); - } - - function walkReturnStatementChildren(preAst: ReturnStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkForStatementChildren(preAst: ForStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.variableDeclaration); - walker.walk(preAst.initializer); - walker.walk(preAst.condition); - walker.walk(preAst.incrementor); - walker.walk(preAst.statement); - } - - function walkForInStatementChildren(preAst: ForInStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.variableDeclaration); - walker.walk(preAst.left); - walker.walk(preAst.expression); - walker.walk(preAst.statement); - } - - function walkIfStatementChildren(preAst: IfStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.condition); - walker.walk(preAst.statement); - walker.walk(preAst.elseClause); - } - - function walkElseClauseChildren(preAst: ElseClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.statement); - } - - function walkWhileStatementChildren(preAst: WhileStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.condition); - walker.walk(preAst.statement); - } - - function walkDoStatementChildren(preAst: DoStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.condition); - walker.walk(preAst.statement); - } - - function walkBlockChildren(preAst: BlockSyntax, walker: AstWalker): void { - walker.walk(preAst.statements); - } - - function walkVariableDeclarationChildren(preAst: VariableDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.variableDeclarators); - } - - function walkCaseSwitchClauseChildren(preAst: CaseSwitchClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - walker.walk(preAst.statements); - } - - function walkDefaultSwitchClauseChildren(preAst: DefaultSwitchClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.statements); - } - - function walkSwitchStatementChildren(preAst: SwitchStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - walker.walk(preAst.switchClauses); - } - - function walkTryStatementChildren(preAst: TryStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.block); - walker.walk(preAst.catchClause); - walker.walk(preAst.finallyClause); - } - - function walkCatchClauseChildren(preAst: CatchClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.typeAnnotation); - walker.walk(preAst.block); - } - - function walkExternalModuleReferenceChildren(preAst: ExternalModuleReferenceSyntax, walker: AstWalker): void { - walker.walk(preAst.stringLiteral); - } - - function walkFinallyClauseChildren(preAst: FinallyClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.block); - } - - function walkClassDeclChildren(preAst: ClassDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.typeParameterList); - walker.walk(preAst.heritageClauses); - walker.walk(preAst.classElements); - } - - function walkScriptChildren(preAst: SourceUnitSyntax, walker: AstWalker): void { - walker.walk(preAst.moduleElements); - } - - function walkHeritageClauseChildren(preAst: HeritageClauseSyntax, walker: AstWalker): void { - walker.walk(preAst.typeNames); - } - - function walkInterfaceDeclerationChildren(preAst: InterfaceDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.typeParameterList); - walker.walk(preAst.heritageClauses); - walker.walk(preAst.body); - } - - function walkObjectTypeChildren(preAst: ObjectTypeSyntax, walker: AstWalker): void { - walker.walk(preAst.typeMembers); - } - - function walkArrayTypeChildren(preAst: ArrayTypeSyntax, walker: AstWalker): void { - walker.walk(preAst.type); - } - - function walkModuleDeclarationChildren(preAst: ModuleDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.name); - walker.walk(preAst.stringLiteral); - walker.walk(preAst.moduleElements); - } - - function walkModuleNameModuleReferenceChildren(preAst: ModuleNameModuleReferenceSyntax, walker: AstWalker): void { - walker.walk(preAst.moduleName); - } - - function walkEnumDeclarationChildren(preAst: EnumDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.enumElements); - } - - function walkEnumElementChildren(preAst: EnumElementSyntax, walker: AstWalker): void { - walker.walk(preAst.propertyName); - walker.walk(preAst.equalsValueClause); - } - - function walkImportDeclarationChildren(preAst: ImportDeclarationSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.moduleReference); - } - - function walkExportAssignmentChildren(preAst: ExportAssignmentSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - } - - function walkWithStatementChildren(preAst: WithStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.condition); - walker.walk(preAst.statement); - } - - function walkExpressionStatementChildren(preAst: ExpressionStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.expression); - } - - function walkLabeledStatementChildren(preAst: LabeledStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.identifier); - walker.walk(preAst.statement); - } - - function walkVariableStatementChildren(preAst: VariableStatementSyntax, walker: AstWalker): void { - walker.walk(preAst.variableDeclaration); - } - - var childrenWalkers: IAstWalkChildren[] = new Array(SyntaxKind.LastNode + 1); - - // Tokens/trivia can't ever be walked into. - for (var i = SyntaxKind.FirstToken, n = SyntaxKind.LastToken; i <= n; i++) { - childrenWalkers[i] = null; - } - for (var i = SyntaxKind.FirstTrivia, n = SyntaxKind.LastTrivia; i <= n; i++) { - childrenWalkers[i] = null; - } - - childrenWalkers[SyntaxKind.AddAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.AddExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.AndAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.AnyKeyword] = null; - childrenWalkers[SyntaxKind.ArgumentList] = walkArgumentListChildren; - childrenWalkers[SyntaxKind.ArrayLiteralExpression] = walkArrayLiteralExpressionChildren; - childrenWalkers[SyntaxKind.ArrayType] = walkArrayTypeChildren; - childrenWalkers[SyntaxKind.SimpleArrowFunctionExpression] = walkSimpleArrowFunctionExpressionChildren; - childrenWalkers[SyntaxKind.ParenthesizedArrowFunctionExpression] = walkParenthesizedArrowFunctionExpressionChildren; - childrenWalkers[SyntaxKind.AssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.BitwiseAndExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.BitwiseExclusiveOrExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.BitwiseNotExpression] = walkPrefixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.BitwiseOrExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.Block] = walkBlockChildren; - childrenWalkers[SyntaxKind.BooleanKeyword] = null; - childrenWalkers[SyntaxKind.BreakStatement] = null; - childrenWalkers[SyntaxKind.CallSignature] = walkCallSignatureChildren; - childrenWalkers[SyntaxKind.CaseSwitchClause] = walkCaseSwitchClauseChildren; - childrenWalkers[SyntaxKind.CastExpression] = walkCastExpressionChildren; - childrenWalkers[SyntaxKind.CatchClause] = walkCatchClauseChildren; - childrenWalkers[SyntaxKind.ClassDeclaration] = walkClassDeclChildren; - childrenWalkers[SyntaxKind.CommaExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.ConditionalExpression] = walkTrinaryExpressionChildren; - childrenWalkers[SyntaxKind.Constraint] = walkConstraintChildren; - childrenWalkers[SyntaxKind.ConstructorDeclaration] = walkConstructorDeclarationChildren; - childrenWalkers[SyntaxKind.ConstructSignature] = walkConstructSignatureChildren; - childrenWalkers[SyntaxKind.ContinueStatement] = null; - childrenWalkers[SyntaxKind.ConstructorType] = walkConstructorTypeChildren; - childrenWalkers[SyntaxKind.DebuggerStatement] = null; - childrenWalkers[SyntaxKind.DefaultSwitchClause] = walkDefaultSwitchClauseChildren; - childrenWalkers[SyntaxKind.DeleteExpression] = walkDeleteExpressionChildren; - childrenWalkers[SyntaxKind.DivideAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.DivideExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.DoStatement] = walkDoStatementChildren; - childrenWalkers[SyntaxKind.ElementAccessExpression] = walkElementAccessExpressionChildren; - childrenWalkers[SyntaxKind.ElseClause] = walkElseClauseChildren; - childrenWalkers[SyntaxKind.EmptyStatement] = null; - childrenWalkers[SyntaxKind.EnumDeclaration] = walkEnumDeclarationChildren; - childrenWalkers[SyntaxKind.EnumElement] = walkEnumElementChildren; - childrenWalkers[SyntaxKind.EqualsExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.EqualsValueClause] = walkEqualsValueClauseChildren; - childrenWalkers[SyntaxKind.EqualsWithTypeConversionExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.ExclusiveOrAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.ExportAssignment] = walkExportAssignmentChildren; - childrenWalkers[SyntaxKind.ExpressionStatement] = walkExpressionStatementChildren; - childrenWalkers[SyntaxKind.ExtendsHeritageClause] = walkHeritageClauseChildren; - childrenWalkers[SyntaxKind.ExternalModuleReference] = walkExternalModuleReferenceChildren; - childrenWalkers[SyntaxKind.FalseKeyword] = null; - childrenWalkers[SyntaxKind.FinallyClause] = walkFinallyClauseChildren; - childrenWalkers[SyntaxKind.ForInStatement] = walkForInStatementChildren; - childrenWalkers[SyntaxKind.ForStatement] = walkForStatementChildren; - childrenWalkers[SyntaxKind.FunctionDeclaration] = walkFuncDeclChildren; - childrenWalkers[SyntaxKind.FunctionExpression] = walkFunctionExpressionChildren; - childrenWalkers[SyntaxKind.FunctionPropertyAssignment] = walkFunctionPropertyAssignmentChildren; - childrenWalkers[SyntaxKind.FunctionType] = walkFunctionTypeChildren; - childrenWalkers[SyntaxKind.GenericType] = walkGenericTypeChildren; - childrenWalkers[SyntaxKind.GetAccessor] = walkGetAccessorChildren; - childrenWalkers[SyntaxKind.GreaterThanExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.GreaterThanOrEqualExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.IfStatement] = walkIfStatementChildren; - childrenWalkers[SyntaxKind.ImplementsHeritageClause] = walkHeritageClauseChildren; - childrenWalkers[SyntaxKind.ImportDeclaration] = walkImportDeclarationChildren; - childrenWalkers[SyntaxKind.IndexMemberDeclaration] = walkIndexMemberDeclarationChildren; - childrenWalkers[SyntaxKind.IndexSignature] = walkIndexSignatureChildren; - childrenWalkers[SyntaxKind.InExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.InstanceOfExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.InterfaceDeclaration] = walkInterfaceDeclerationChildren; - childrenWalkers[SyntaxKind.InvocationExpression] = walkInvocationExpressionChildren; - childrenWalkers[SyntaxKind.LabeledStatement] = walkLabeledStatementChildren; - childrenWalkers[SyntaxKind.LeftShiftAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.LeftShiftExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.LessThanExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.LessThanOrEqualExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.List] = walkListChildren; - childrenWalkers[SyntaxKind.LogicalAndExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.LogicalNotExpression] = walkPrefixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.LogicalOrExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.MemberAccessExpression] = walkMemberAccessExpressionChildren; - childrenWalkers[SyntaxKind.MemberFunctionDeclaration] = walkMemberFunctionDeclarationChildren; - childrenWalkers[SyntaxKind.MemberVariableDeclaration] = walkMemberVariableDeclarationChildren; - childrenWalkers[SyntaxKind.MethodSignature] = walkMethodSignatureChildren; - childrenWalkers[SyntaxKind.ModuleDeclaration] = walkModuleDeclarationChildren; - childrenWalkers[SyntaxKind.ModuleNameModuleReference] = walkModuleNameModuleReferenceChildren; - childrenWalkers[SyntaxKind.ModuloAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.ModuloExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.MultiplyAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.MultiplyExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.IdentifierName] = null; - childrenWalkers[SyntaxKind.NegateExpression] = walkPrefixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.None] = null; - childrenWalkers[SyntaxKind.NotEqualsExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.NotEqualsWithTypeConversionExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.NullKeyword] = null; - childrenWalkers[SyntaxKind.NumberKeyword] = null; - childrenWalkers[SyntaxKind.NumericLiteral] = null; - childrenWalkers[SyntaxKind.ObjectCreationExpression] = walkObjectCreationExpressionChildren; - childrenWalkers[SyntaxKind.ObjectLiteralExpression] = walkObjectLiteralExpressionChildren; - childrenWalkers[SyntaxKind.ObjectType] = walkObjectTypeChildren; - childrenWalkers[SyntaxKind.OmittedExpression] = null; - childrenWalkers[SyntaxKind.OrAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.Parameter] = walkParameterChildren; - childrenWalkers[SyntaxKind.ParameterList] = walkParameterListChildren; - childrenWalkers[SyntaxKind.ParenthesizedExpression] = walkParenthesizedExpressionChildren; - childrenWalkers[SyntaxKind.PlusExpression] = walkPrefixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.PostDecrementExpression] = walkPostfixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.PostIncrementExpression] = walkPostfixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.PreDecrementExpression] = walkPrefixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.PreIncrementExpression] = walkPrefixUnaryExpressionChildren; - childrenWalkers[SyntaxKind.PropertySignature] = walkPropertySignatureChildren; - childrenWalkers[SyntaxKind.QualifiedName] = walkQualifiedNameChildren; - childrenWalkers[SyntaxKind.RegularExpressionLiteral] = null; - childrenWalkers[SyntaxKind.ReturnStatement] = walkReturnStatementChildren; - childrenWalkers[SyntaxKind.SourceUnit] = walkScriptChildren; - childrenWalkers[SyntaxKind.SeparatedList] = walkSeparatedListChildren; - childrenWalkers[SyntaxKind.SetAccessor] = walkSetAccessorChildren; - childrenWalkers[SyntaxKind.SignedRightShiftAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.SignedRightShiftExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.SimplePropertyAssignment] = walkSimplePropertyAssignmentChildren; - childrenWalkers[SyntaxKind.StringLiteral] = null; - childrenWalkers[SyntaxKind.StringKeyword] = null; - childrenWalkers[SyntaxKind.SubtractAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.SubtractExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.SuperKeyword] = null; - childrenWalkers[SyntaxKind.SwitchStatement] = walkSwitchStatementChildren; - childrenWalkers[SyntaxKind.ThisKeyword] = null; - childrenWalkers[SyntaxKind.ThrowStatement] = walkThrowStatementChildren; - childrenWalkers[SyntaxKind.TriviaList] = null; - childrenWalkers[SyntaxKind.TrueKeyword] = null; - childrenWalkers[SyntaxKind.TryStatement] = walkTryStatementChildren; - childrenWalkers[SyntaxKind.TupleType] = walkTupleTypeChildren; - childrenWalkers[SyntaxKind.TypeAnnotation] = walkTypeAnnotationChildren; - childrenWalkers[SyntaxKind.TypeArgumentList] = walkTypeArgumentListChildren; - childrenWalkers[SyntaxKind.TypeOfExpression] = walkTypeOfExpressionChildren; - childrenWalkers[SyntaxKind.TypeParameter] = walkTypeParameterChildren; - childrenWalkers[SyntaxKind.TypeParameterList] = walkTypeParameterListChildren; - childrenWalkers[SyntaxKind.TypeQuery] = walkTypeQueryChildren; - childrenWalkers[SyntaxKind.UnsignedRightShiftAssignmentExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.UnsignedRightShiftExpression] = walkBinaryExpressionChildren; - childrenWalkers[SyntaxKind.VariableDeclaration] = walkVariableDeclarationChildren; - childrenWalkers[SyntaxKind.VariableDeclarator] = walkVariableDeclaratorChildren; - childrenWalkers[SyntaxKind.VariableStatement] = walkVariableStatementChildren; - childrenWalkers[SyntaxKind.VoidExpression] = walkVoidExpressionChildren; - childrenWalkers[SyntaxKind.VoidKeyword] = null; - childrenWalkers[SyntaxKind.WhileStatement] = walkWhileStatementChildren; - childrenWalkers[SyntaxKind.WithStatement] = walkWithStatementChildren; - - // Verify the code is up to date with the enum - for (var e in SyntaxKind) { - if (SyntaxKind.hasOwnProperty(e) && StringUtilities.isString(SyntaxKind[e])) { - TypeScript.Debug.assert(childrenWalkers[e] !== undefined, "Fix initWalkers: " + SyntaxKind[e]); - } - } - - export class AstWalkOptions { - public goChildren = true; - public stopWalking = false; - } - - interface IAstWalkChildren { - (preAst: ISyntaxElement, walker: AstWalker): void; - } - - export interface IAstWalker { - options: AstWalkOptions; - state: any - } - - interface AstWalker { - walk(ast: ISyntaxElement): void; - } - - class SimplePreAstWalker implements AstWalker { - public options: AstWalkOptions = new AstWalkOptions(); - - constructor( - private pre: (ast: ISyntaxElement, state: any) => void, - public state: any) { - } - - public walk(ast: ISyntaxElement): void { - if (!ast) { - return; - } - - this.pre(ast, this.state); - - var walker = childrenWalkers[ast.kind()]; - if (walker) { - walker(ast, this); - } - } - } - - class SimplePrePostAstWalker implements AstWalker { - public options: AstWalkOptions = new AstWalkOptions(); - - constructor( - private pre: (ast: ISyntaxElement, state: any) => void, - private post: (ast: ISyntaxElement, state: any) => void, - public state: any) { - } - - public walk(ast: ISyntaxElement): void { - if (!ast) { - return; - } - - this.pre(ast, this.state); - - var walker = childrenWalkers[ast.kind()]; - if (walker) { - walker(ast, this); - } - - this.post(ast, this.state); - } - } - - class NormalAstWalker implements AstWalker { - public options: AstWalkOptions = new AstWalkOptions(); - - constructor( - private pre: (ast: ISyntaxElement, walker: IAstWalker) => void, - private post: (ast: ISyntaxElement, walker: IAstWalker) => void, - public state: any) { - } - - public walk(ast: ISyntaxElement): void { - if (!ast) { - return; - } - - // If we're stopping, then bail out immediately. - if (this.options.stopWalking) { - return; - } - - this.pre(ast, this); - - // If we were asked to stop, then stop. - if (this.options.stopWalking) { - return; - } - - if (this.options.goChildren) { - // Call the "walkChildren" function corresponding to "nodeType". - var walker = childrenWalkers[ast.kind()]; - if (walker) { - walker(ast, this); - } - } - else { - // no go only applies to children of node issuing it - this.options.goChildren = true; - } - - if (this.post) { - this.post(ast, this); - } - } - } - - export class AstWalkerFactory { - public walk(ast: ISyntaxElement, pre: (ast: ISyntaxElement, walker: IAstWalker) => void, post?: (ast: ISyntaxElement, walker: IAstWalker) => void, state?: any): void { - new NormalAstWalker(pre, post, state).walk(ast); - } - - public simpleWalk(ast: ISyntaxElement, pre: (ast: ISyntaxElement, state: any) => void, post?: (ast: ISyntaxElement, state: any) => void, state?: any): void { - if (post) { - new SimplePrePostAstWalker(pre, post, state).walk(ast); - } - else { - new SimplePreAstWalker(pre, state).walk(ast); - } - } - } - - var globalAstWalkerFactory = new AstWalkerFactory(); - - export function getAstWalkerFactory(): AstWalkerFactory { - return globalAstWalkerFactory; - } -} \ No newline at end of file diff --git a/src/services/syntax/defaultSyntaxVisitor.generated.ts b/src/services/syntax/defaultSyntaxVisitor.generated.ts index 32a0cfad4a5..a4a42db309d 100644 --- a/src/services/syntax/defaultSyntaxVisitor.generated.ts +++ b/src/services/syntax/defaultSyntaxVisitor.generated.ts @@ -46,6 +46,14 @@ module TypeScript { return this.defaultVisit(node); } + public visitUnionType(node: UnionTypeSyntax): any { + return this.defaultVisit(node); + } + + public visitParenthesizedType(node: ParenthesizedTypeSyntax): any { + return this.defaultVisit(node); + } + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): any { return this.defaultVisit(node); } diff --git a/src/services/syntax/parser.ts b/src/services/syntax/parser.ts index a35ddc5737b..96de60aa17d 100644 --- a/src/services/syntax/parser.ts +++ b/src/services/syntax/parser.ts @@ -3532,6 +3532,38 @@ module TypeScript.Parser { } function tryParseType(): ITypeSyntax { + if (isFunctionType()) { + return parseFunctionType(); + } + + if (currentToken().kind() === SyntaxKind.NewKeyword) { + return parseConstructorType(); + } + + return tryParseUnionTypeOrHigher(); + } + + function tryParseUnionTypeOrHigher(): ITypeSyntax { + var type = tryParsePrimaryType(); + + if (type) { + var barToken: ISyntaxToken; + while ((barToken = currentToken()).kind() === SyntaxKind.BarToken) { + consumeToken(barToken); + var right = parsePrimaryType(); + + type = new syntaxFactory.UnionTypeSyntax(parseNodeData, type, barToken, right); + } + } + + return type; + } + + function parsePrimaryType(): ITypeSyntax { + return tryParsePrimaryType() || eatIdentifierToken(DiagnosticCode.Type_expected); + } + + function tryParsePrimaryType(): ITypeSyntax { // First consume any underlying element type. var type = tryParseNonArrayType(); @@ -3572,11 +3604,9 @@ module TypeScript.Parser { } return consumeToken(_currentToken); - case SyntaxKind.OpenParenToken: - case SyntaxKind.LessThanToken: return tryParseFunctionType(); case SyntaxKind.VoidKeyword: return consumeToken(_currentToken); + case SyntaxKind.OpenParenToken: return parseParenthesizedType(_currentToken); case SyntaxKind.OpenBraceToken: return parseObjectType(); - case SyntaxKind.NewKeyword: return parseConstructorType(); case SyntaxKind.TypeOfKeyword: return parseTypeQuery(_currentToken); case SyntaxKind.OpenBracketToken: return parseTupleType(_currentToken); } @@ -3584,6 +3614,10 @@ module TypeScript.Parser { return tryParseNameOrGenericType(); } + function parseParenthesizedType(openParenToken: ISyntaxToken): ParenthesizedTypeSyntax { + return new syntaxFactory.ParenthesizedTypeSyntax(parseNodeData, consumeToken(openParenToken), parseType(), eatToken(SyntaxKind.CloseParenToken)); + } + function tryParseNameOrGenericType(): ITypeSyntax { var name = tryParseName(/*allowIdentifierNames*/ false); if (name === null) { @@ -3604,18 +3638,71 @@ module TypeScript.Parser { : new syntaxFactory.GenericTypeSyntax(parseNodeData, name, typeArgumentList); } - function tryParseFunctionType(): FunctionTypeSyntax { - var typeParameterList = tryParseTypeParameterList(/*requireCompleteTypeParameterList:*/ false); - var parameterList: ParameterListSyntax = null; - if (typeParameterList === null) { - parameterList = tryParseParameterList(); - if (parameterList === null) { - return null; + function isFunctionType(): boolean { + var token0 = currentToken(); + var token0Kind = token0.kind(); + + // If we see a < then we consider ourselves to be definitely in a (generic) function type. + if (token0Kind === SyntaxKind.LessThanToken) { + return true; + } + + // If we don't see a < then we have to see an open paren for this to be a function + // type. However, an open paren may also start a parenthesized type. So we need to + // do some lookahead to see what we've actually got. If we don't see enough to be + // sure that it's a function type, then we go ahead with the assumption that it's a + // parenthesized type. + if (token0Kind === SyntaxKind.OpenParenToken) { + var token1 = peekToken(1); + var token1Kind = token1.kind(); + + if (token1Kind === SyntaxKind.CloseParenToken || token1Kind === SyntaxKind.DotDotDotToken) { + // () + // (... + // + // Both are definitely function types, and could not be paren types. + return true; + } + + if (isModifierKind(token1Kind) || isIdentifier(token1)) { + // (id + // could be a function type or a parenthesized type. + + var token2 = peekToken(2); + var token2Kind = token2.kind(); + + if (token2Kind === SyntaxKind.ColonToken || + token2Kind === SyntaxKind.CommaToken || + token2Kind === SyntaxKind.QuestionToken || + token2Kind === SyntaxKind.EqualsToken || + isIdentifier(token2) || + isModifierKind(token2Kind)) { + // ( id : + // ( id , + // ( id ? + // ( id = + // ( modifier id + // + // All of these are definitely a function type and not a parenthesized type. + return true; + } + + if (token2Kind === SyntaxKind.CloseParenToken) { + // ( id ) + // + // Only a function type if we see an arrow following it. + return peekToken(3).kind() === SyntaxKind.EqualsGreaterThanToken; + } } } - else { - parameterList = parseParameterList(); - } + + // Anything else is a parenthesized type. + return false; + } + + function parseFunctionType(): FunctionTypeSyntax { + var typeParameterList = tryParseTypeParameterList(/*requireCompleteTypeParameterList:*/ false); + var parameterList = parseParameterList(); return new syntaxFactory.FunctionTypeSyntax(parseNodeData, typeParameterList, parameterList, eatToken(SyntaxKind.EqualsGreaterThanToken), parseType()); diff --git a/src/services/syntax/prettyPrinter.ts b/src/services/syntax/prettyPrinter.ts index df22bcab559..ec354a9a44b 100644 --- a/src/services/syntax/prettyPrinter.ts +++ b/src/services/syntax/prettyPrinter.ts @@ -427,6 +427,20 @@ module TypeScript.PrettyPrinter { this.appendToken(node.closeBracketToken); } + public visitParenthesizedType(node: ParenthesizedTypeSyntax): void { + this.appendToken(node.openParenToken); + this.appendElement(node.type); + this.appendToken(node.closeParenToken); + } + + public visitUnionType(node: UnionTypeSyntax): void { + this.appendElement(node.left); + this.ensureSpace(); + this.appendToken(node.barToken); + this.ensureSpace(); + this.appendElement(node.right); + } + public visitConstructorType(node: ConstructorTypeSyntax): void { this.appendToken(node.newKeyword); this.ensureSpace(); diff --git a/src/services/syntax/syntaxGenerator.ts b/src/services/syntax/syntaxGenerator.ts index ebc2673b98c..788b8f91930 100644 --- a/src/services/syntax/syntaxGenerator.ts +++ b/src/services/syntax/syntaxGenerator.ts @@ -2,6 +2,7 @@ /// /// /// +/// // Adds argument checking to the generated nodes. Argument checking appears to slow things down // parsing about 7%. If we want to get that perf back, we can always remove this. @@ -365,6 +366,28 @@ var definitions:ITypeDefinition[] = [ ], isTypeScriptSpecific: true }, + { + name: 'UnionTypeSyntax', + baseType: 'ISyntaxNode', + interfaces: ['ITypeSyntax'], + children: [ + { name: 'left', type: 'ITypeSyntax' }, + { name: 'barToken', isToken: true, excludeFromAST: true }, + { name: 'right', type: 'ITypeSyntax' } + ], + isTypeScriptSpecific: true + }, + { + name: 'ParenthesizedTypeSyntax', + baseType: 'ISyntaxNode', + interfaces: ['ITypeSyntax'], + children: [ + { name: 'openParenToken', isToken: true, excludeFromAST: true }, + { name: 'type', type: 'ITypeSyntax' }, + { name: 'closeParenToken', isToken: true, excludeFromAST: true } + ], + isTypeScriptSpecific: true + }, { name: 'TypeAnnotationSyntax', baseType: 'ISyntaxNode', diff --git a/src/services/syntax/syntaxKind.ts b/src/services/syntax/syntaxKind.ts index 1021c2fcfd7..8c617a23f3e 100644 --- a/src/services/syntax/syntaxKind.ts +++ b/src/services/syntax/syntaxKind.ts @@ -159,6 +159,8 @@ module TypeScript { GenericType, TypeQuery, TupleType, + UnionType, + ParenthesizedType, // Module elements. InterfaceDeclaration, diff --git a/src/services/syntax/syntaxNodes.abstract.generated.ts b/src/services/syntax/syntaxNodes.abstract.generated.ts index 9cba7f66d00..d9affc6e623 100644 --- a/src/services/syntax/syntaxNodes.abstract.generated.ts +++ b/src/services/syntax/syntaxNodes.abstract.generated.ts @@ -119,6 +119,30 @@ module TypeScript.Syntax.Abstract { !isShared(types) && (types.parent = this); } } + export class UnionTypeSyntax extends SyntaxNode implements ITypeSyntax { + public left: ITypeSyntax; + public barToken: ISyntaxToken; + public right: ITypeSyntax; + public _typeBrand: any; + constructor(data: number, left: ITypeSyntax, barToken: ISyntaxToken, right: ITypeSyntax) { + super(data); + this.left = left, + this.right = right, + left.parent = this, + right.parent = this; + } + } + export class ParenthesizedTypeSyntax extends SyntaxNode implements ITypeSyntax { + public openParenToken: ISyntaxToken; + public type: ITypeSyntax; + public closeParenToken: ISyntaxToken; + public _typeBrand: any; + constructor(data: number, openParenToken: ISyntaxToken, type: ITypeSyntax, closeParenToken: ISyntaxToken) { + super(data); + this.type = type, + type.parent = this; + } + } export class InterfaceDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { public modifiers: ISyntaxToken[]; public interfaceKeyword: ISyntaxToken; @@ -1201,5 +1225,5 @@ module TypeScript.Syntax.Abstract { } } - (SourceUnitSyntax).prototype.__kind = SyntaxKind.SourceUnit, (QualifiedNameSyntax).prototype.__kind = SyntaxKind.QualifiedName, (ObjectTypeSyntax).prototype.__kind = SyntaxKind.ObjectType, (FunctionTypeSyntax).prototype.__kind = SyntaxKind.FunctionType, (ArrayTypeSyntax).prototype.__kind = SyntaxKind.ArrayType, (ConstructorTypeSyntax).prototype.__kind = SyntaxKind.ConstructorType, (GenericTypeSyntax).prototype.__kind = SyntaxKind.GenericType, (TypeQuerySyntax).prototype.__kind = SyntaxKind.TypeQuery, (TupleTypeSyntax).prototype.__kind = SyntaxKind.TupleType, (InterfaceDeclarationSyntax).prototype.__kind = SyntaxKind.InterfaceDeclaration, (FunctionDeclarationSyntax).prototype.__kind = SyntaxKind.FunctionDeclaration, (ModuleDeclarationSyntax).prototype.__kind = SyntaxKind.ModuleDeclaration, (ClassDeclarationSyntax).prototype.__kind = SyntaxKind.ClassDeclaration, (EnumDeclarationSyntax).prototype.__kind = SyntaxKind.EnumDeclaration, (ImportDeclarationSyntax).prototype.__kind = SyntaxKind.ImportDeclaration, (ExportAssignmentSyntax).prototype.__kind = SyntaxKind.ExportAssignment, (MemberFunctionDeclarationSyntax).prototype.__kind = SyntaxKind.MemberFunctionDeclaration, (MemberVariableDeclarationSyntax).prototype.__kind = SyntaxKind.MemberVariableDeclaration, (ConstructorDeclarationSyntax).prototype.__kind = SyntaxKind.ConstructorDeclaration, (IndexMemberDeclarationSyntax).prototype.__kind = SyntaxKind.IndexMemberDeclaration, (GetAccessorSyntax).prototype.__kind = SyntaxKind.GetAccessor, (SetAccessorSyntax).prototype.__kind = SyntaxKind.SetAccessor, (PropertySignatureSyntax).prototype.__kind = SyntaxKind.PropertySignature, (CallSignatureSyntax).prototype.__kind = SyntaxKind.CallSignature, (ConstructSignatureSyntax).prototype.__kind = SyntaxKind.ConstructSignature, (IndexSignatureSyntax).prototype.__kind = SyntaxKind.IndexSignature, (MethodSignatureSyntax).prototype.__kind = SyntaxKind.MethodSignature, (BlockSyntax).prototype.__kind = SyntaxKind.Block, (IfStatementSyntax).prototype.__kind = SyntaxKind.IfStatement, (VariableStatementSyntax).prototype.__kind = SyntaxKind.VariableStatement, (ExpressionStatementSyntax).prototype.__kind = SyntaxKind.ExpressionStatement, (ReturnStatementSyntax).prototype.__kind = SyntaxKind.ReturnStatement, (SwitchStatementSyntax).prototype.__kind = SyntaxKind.SwitchStatement, (BreakStatementSyntax).prototype.__kind = SyntaxKind.BreakStatement, (ContinueStatementSyntax).prototype.__kind = SyntaxKind.ContinueStatement, (ForStatementSyntax).prototype.__kind = SyntaxKind.ForStatement, (ForInStatementSyntax).prototype.__kind = SyntaxKind.ForInStatement, (EmptyStatementSyntax).prototype.__kind = SyntaxKind.EmptyStatement, (ThrowStatementSyntax).prototype.__kind = SyntaxKind.ThrowStatement, (WhileStatementSyntax).prototype.__kind = SyntaxKind.WhileStatement, (TryStatementSyntax).prototype.__kind = SyntaxKind.TryStatement, (LabeledStatementSyntax).prototype.__kind = SyntaxKind.LabeledStatement, (DoStatementSyntax).prototype.__kind = SyntaxKind.DoStatement, (DebuggerStatementSyntax).prototype.__kind = SyntaxKind.DebuggerStatement, (WithStatementSyntax).prototype.__kind = SyntaxKind.WithStatement, (DeleteExpressionSyntax).prototype.__kind = SyntaxKind.DeleteExpression, (TypeOfExpressionSyntax).prototype.__kind = SyntaxKind.TypeOfExpression, (VoidExpressionSyntax).prototype.__kind = SyntaxKind.VoidExpression, (ConditionalExpressionSyntax).prototype.__kind = SyntaxKind.ConditionalExpression, (MemberAccessExpressionSyntax).prototype.__kind = SyntaxKind.MemberAccessExpression, (InvocationExpressionSyntax).prototype.__kind = SyntaxKind.InvocationExpression, (ArrayLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ArrayLiteralExpression, (ObjectLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ObjectLiteralExpression, (ObjectCreationExpressionSyntax).prototype.__kind = SyntaxKind.ObjectCreationExpression, (ParenthesizedExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedExpression, (ParenthesizedArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedArrowFunctionExpression, (SimpleArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.SimpleArrowFunctionExpression, (CastExpressionSyntax).prototype.__kind = SyntaxKind.CastExpression, (ElementAccessExpressionSyntax).prototype.__kind = SyntaxKind.ElementAccessExpression, (FunctionExpressionSyntax).prototype.__kind = SyntaxKind.FunctionExpression, (OmittedExpressionSyntax).prototype.__kind = SyntaxKind.OmittedExpression, (VariableDeclarationSyntax).prototype.__kind = SyntaxKind.VariableDeclaration, (VariableDeclaratorSyntax).prototype.__kind = SyntaxKind.VariableDeclarator, (ArgumentListSyntax).prototype.__kind = SyntaxKind.ArgumentList, (ParameterListSyntax).prototype.__kind = SyntaxKind.ParameterList, (TypeArgumentListSyntax).prototype.__kind = SyntaxKind.TypeArgumentList, (TypeParameterListSyntax).prototype.__kind = SyntaxKind.TypeParameterList, (EqualsValueClauseSyntax).prototype.__kind = SyntaxKind.EqualsValueClause, (CaseSwitchClauseSyntax).prototype.__kind = SyntaxKind.CaseSwitchClause, (DefaultSwitchClauseSyntax).prototype.__kind = SyntaxKind.DefaultSwitchClause, (ElseClauseSyntax).prototype.__kind = SyntaxKind.ElseClause, (CatchClauseSyntax).prototype.__kind = SyntaxKind.CatchClause, (FinallyClauseSyntax).prototype.__kind = SyntaxKind.FinallyClause, (TypeParameterSyntax).prototype.__kind = SyntaxKind.TypeParameter, (ConstraintSyntax).prototype.__kind = SyntaxKind.Constraint, (SimplePropertyAssignmentSyntax).prototype.__kind = SyntaxKind.SimplePropertyAssignment, (FunctionPropertyAssignmentSyntax).prototype.__kind = SyntaxKind.FunctionPropertyAssignment, (ParameterSyntax).prototype.__kind = SyntaxKind.Parameter, (EnumElementSyntax).prototype.__kind = SyntaxKind.EnumElement, (TypeAnnotationSyntax).prototype.__kind = SyntaxKind.TypeAnnotation, (ExternalModuleReferenceSyntax).prototype.__kind = SyntaxKind.ExternalModuleReference, (ModuleNameModuleReferenceSyntax).prototype.__kind = SyntaxKind.ModuleNameModuleReference; + (SourceUnitSyntax).prototype.__kind = SyntaxKind.SourceUnit, (QualifiedNameSyntax).prototype.__kind = SyntaxKind.QualifiedName, (ObjectTypeSyntax).prototype.__kind = SyntaxKind.ObjectType, (FunctionTypeSyntax).prototype.__kind = SyntaxKind.FunctionType, (ArrayTypeSyntax).prototype.__kind = SyntaxKind.ArrayType, (ConstructorTypeSyntax).prototype.__kind = SyntaxKind.ConstructorType, (GenericTypeSyntax).prototype.__kind = SyntaxKind.GenericType, (TypeQuerySyntax).prototype.__kind = SyntaxKind.TypeQuery, (TupleTypeSyntax).prototype.__kind = SyntaxKind.TupleType, (UnionTypeSyntax).prototype.__kind = SyntaxKind.UnionType, (ParenthesizedTypeSyntax).prototype.__kind = SyntaxKind.ParenthesizedType, (InterfaceDeclarationSyntax).prototype.__kind = SyntaxKind.InterfaceDeclaration, (FunctionDeclarationSyntax).prototype.__kind = SyntaxKind.FunctionDeclaration, (ModuleDeclarationSyntax).prototype.__kind = SyntaxKind.ModuleDeclaration, (ClassDeclarationSyntax).prototype.__kind = SyntaxKind.ClassDeclaration, (EnumDeclarationSyntax).prototype.__kind = SyntaxKind.EnumDeclaration, (ImportDeclarationSyntax).prototype.__kind = SyntaxKind.ImportDeclaration, (ExportAssignmentSyntax).prototype.__kind = SyntaxKind.ExportAssignment, (MemberFunctionDeclarationSyntax).prototype.__kind = SyntaxKind.MemberFunctionDeclaration, (MemberVariableDeclarationSyntax).prototype.__kind = SyntaxKind.MemberVariableDeclaration, (ConstructorDeclarationSyntax).prototype.__kind = SyntaxKind.ConstructorDeclaration, (IndexMemberDeclarationSyntax).prototype.__kind = SyntaxKind.IndexMemberDeclaration, (GetAccessorSyntax).prototype.__kind = SyntaxKind.GetAccessor, (SetAccessorSyntax).prototype.__kind = SyntaxKind.SetAccessor, (PropertySignatureSyntax).prototype.__kind = SyntaxKind.PropertySignature, (CallSignatureSyntax).prototype.__kind = SyntaxKind.CallSignature, (ConstructSignatureSyntax).prototype.__kind = SyntaxKind.ConstructSignature, (IndexSignatureSyntax).prototype.__kind = SyntaxKind.IndexSignature, (MethodSignatureSyntax).prototype.__kind = SyntaxKind.MethodSignature, (BlockSyntax).prototype.__kind = SyntaxKind.Block, (IfStatementSyntax).prototype.__kind = SyntaxKind.IfStatement, (VariableStatementSyntax).prototype.__kind = SyntaxKind.VariableStatement, (ExpressionStatementSyntax).prototype.__kind = SyntaxKind.ExpressionStatement, (ReturnStatementSyntax).prototype.__kind = SyntaxKind.ReturnStatement, (SwitchStatementSyntax).prototype.__kind = SyntaxKind.SwitchStatement, (BreakStatementSyntax).prototype.__kind = SyntaxKind.BreakStatement, (ContinueStatementSyntax).prototype.__kind = SyntaxKind.ContinueStatement, (ForStatementSyntax).prototype.__kind = SyntaxKind.ForStatement, (ForInStatementSyntax).prototype.__kind = SyntaxKind.ForInStatement, (EmptyStatementSyntax).prototype.__kind = SyntaxKind.EmptyStatement, (ThrowStatementSyntax).prototype.__kind = SyntaxKind.ThrowStatement, (WhileStatementSyntax).prototype.__kind = SyntaxKind.WhileStatement, (TryStatementSyntax).prototype.__kind = SyntaxKind.TryStatement, (LabeledStatementSyntax).prototype.__kind = SyntaxKind.LabeledStatement, (DoStatementSyntax).prototype.__kind = SyntaxKind.DoStatement, (DebuggerStatementSyntax).prototype.__kind = SyntaxKind.DebuggerStatement, (WithStatementSyntax).prototype.__kind = SyntaxKind.WithStatement, (DeleteExpressionSyntax).prototype.__kind = SyntaxKind.DeleteExpression, (TypeOfExpressionSyntax).prototype.__kind = SyntaxKind.TypeOfExpression, (VoidExpressionSyntax).prototype.__kind = SyntaxKind.VoidExpression, (ConditionalExpressionSyntax).prototype.__kind = SyntaxKind.ConditionalExpression, (MemberAccessExpressionSyntax).prototype.__kind = SyntaxKind.MemberAccessExpression, (InvocationExpressionSyntax).prototype.__kind = SyntaxKind.InvocationExpression, (ArrayLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ArrayLiteralExpression, (ObjectLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ObjectLiteralExpression, (ObjectCreationExpressionSyntax).prototype.__kind = SyntaxKind.ObjectCreationExpression, (ParenthesizedExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedExpression, (ParenthesizedArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedArrowFunctionExpression, (SimpleArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.SimpleArrowFunctionExpression, (CastExpressionSyntax).prototype.__kind = SyntaxKind.CastExpression, (ElementAccessExpressionSyntax).prototype.__kind = SyntaxKind.ElementAccessExpression, (FunctionExpressionSyntax).prototype.__kind = SyntaxKind.FunctionExpression, (OmittedExpressionSyntax).prototype.__kind = SyntaxKind.OmittedExpression, (VariableDeclarationSyntax).prototype.__kind = SyntaxKind.VariableDeclaration, (VariableDeclaratorSyntax).prototype.__kind = SyntaxKind.VariableDeclarator, (ArgumentListSyntax).prototype.__kind = SyntaxKind.ArgumentList, (ParameterListSyntax).prototype.__kind = SyntaxKind.ParameterList, (TypeArgumentListSyntax).prototype.__kind = SyntaxKind.TypeArgumentList, (TypeParameterListSyntax).prototype.__kind = SyntaxKind.TypeParameterList, (EqualsValueClauseSyntax).prototype.__kind = SyntaxKind.EqualsValueClause, (CaseSwitchClauseSyntax).prototype.__kind = SyntaxKind.CaseSwitchClause, (DefaultSwitchClauseSyntax).prototype.__kind = SyntaxKind.DefaultSwitchClause, (ElseClauseSyntax).prototype.__kind = SyntaxKind.ElseClause, (CatchClauseSyntax).prototype.__kind = SyntaxKind.CatchClause, (FinallyClauseSyntax).prototype.__kind = SyntaxKind.FinallyClause, (TypeParameterSyntax).prototype.__kind = SyntaxKind.TypeParameter, (ConstraintSyntax).prototype.__kind = SyntaxKind.Constraint, (SimplePropertyAssignmentSyntax).prototype.__kind = SyntaxKind.SimplePropertyAssignment, (FunctionPropertyAssignmentSyntax).prototype.__kind = SyntaxKind.FunctionPropertyAssignment, (ParameterSyntax).prototype.__kind = SyntaxKind.Parameter, (EnumElementSyntax).prototype.__kind = SyntaxKind.EnumElement, (TypeAnnotationSyntax).prototype.__kind = SyntaxKind.TypeAnnotation, (ExternalModuleReferenceSyntax).prototype.__kind = SyntaxKind.ExternalModuleReference, (ModuleNameModuleReferenceSyntax).prototype.__kind = SyntaxKind.ModuleNameModuleReference; } \ No newline at end of file diff --git a/src/services/syntax/syntaxNodes.concrete.generated.ts b/src/services/syntax/syntaxNodes.concrete.generated.ts index fa593fd1976..15b3ef47160 100644 --- a/src/services/syntax/syntaxNodes.concrete.generated.ts +++ b/src/services/syntax/syntaxNodes.concrete.generated.ts @@ -141,6 +141,36 @@ module TypeScript.Syntax.Concrete { closeBracketToken.parent = this; } } + export class UnionTypeSyntax extends SyntaxNode implements ITypeSyntax { + public left: ITypeSyntax; + public barToken: ISyntaxToken; + public right: ITypeSyntax; + public _typeBrand: any; + constructor(data: number, left: ITypeSyntax, barToken: ISyntaxToken, right: ITypeSyntax) { + super(data); + this.left = left, + this.barToken = barToken, + this.right = right, + left.parent = this, + barToken.parent = this, + right.parent = this; + } + } + export class ParenthesizedTypeSyntax extends SyntaxNode implements ITypeSyntax { + public openParenToken: ISyntaxToken; + public type: ITypeSyntax; + public closeParenToken: ISyntaxToken; + public _typeBrand: any; + constructor(data: number, openParenToken: ISyntaxToken, type: ITypeSyntax, closeParenToken: ISyntaxToken) { + super(data); + this.openParenToken = openParenToken, + this.type = type, + this.closeParenToken = closeParenToken, + openParenToken.parent = this, + type.parent = this, + closeParenToken.parent = this; + } + } export class InterfaceDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { public modifiers: ISyntaxToken[]; public interfaceKeyword: ISyntaxToken; @@ -1435,5 +1465,5 @@ module TypeScript.Syntax.Concrete { } } - (SourceUnitSyntax).prototype.__kind = SyntaxKind.SourceUnit, (QualifiedNameSyntax).prototype.__kind = SyntaxKind.QualifiedName, (ObjectTypeSyntax).prototype.__kind = SyntaxKind.ObjectType, (FunctionTypeSyntax).prototype.__kind = SyntaxKind.FunctionType, (ArrayTypeSyntax).prototype.__kind = SyntaxKind.ArrayType, (ConstructorTypeSyntax).prototype.__kind = SyntaxKind.ConstructorType, (GenericTypeSyntax).prototype.__kind = SyntaxKind.GenericType, (TypeQuerySyntax).prototype.__kind = SyntaxKind.TypeQuery, (TupleTypeSyntax).prototype.__kind = SyntaxKind.TupleType, (InterfaceDeclarationSyntax).prototype.__kind = SyntaxKind.InterfaceDeclaration, (FunctionDeclarationSyntax).prototype.__kind = SyntaxKind.FunctionDeclaration, (ModuleDeclarationSyntax).prototype.__kind = SyntaxKind.ModuleDeclaration, (ClassDeclarationSyntax).prototype.__kind = SyntaxKind.ClassDeclaration, (EnumDeclarationSyntax).prototype.__kind = SyntaxKind.EnumDeclaration, (ImportDeclarationSyntax).prototype.__kind = SyntaxKind.ImportDeclaration, (ExportAssignmentSyntax).prototype.__kind = SyntaxKind.ExportAssignment, (MemberFunctionDeclarationSyntax).prototype.__kind = SyntaxKind.MemberFunctionDeclaration, (MemberVariableDeclarationSyntax).prototype.__kind = SyntaxKind.MemberVariableDeclaration, (ConstructorDeclarationSyntax).prototype.__kind = SyntaxKind.ConstructorDeclaration, (IndexMemberDeclarationSyntax).prototype.__kind = SyntaxKind.IndexMemberDeclaration, (GetAccessorSyntax).prototype.__kind = SyntaxKind.GetAccessor, (SetAccessorSyntax).prototype.__kind = SyntaxKind.SetAccessor, (PropertySignatureSyntax).prototype.__kind = SyntaxKind.PropertySignature, (CallSignatureSyntax).prototype.__kind = SyntaxKind.CallSignature, (ConstructSignatureSyntax).prototype.__kind = SyntaxKind.ConstructSignature, (IndexSignatureSyntax).prototype.__kind = SyntaxKind.IndexSignature, (MethodSignatureSyntax).prototype.__kind = SyntaxKind.MethodSignature, (BlockSyntax).prototype.__kind = SyntaxKind.Block, (IfStatementSyntax).prototype.__kind = SyntaxKind.IfStatement, (VariableStatementSyntax).prototype.__kind = SyntaxKind.VariableStatement, (ExpressionStatementSyntax).prototype.__kind = SyntaxKind.ExpressionStatement, (ReturnStatementSyntax).prototype.__kind = SyntaxKind.ReturnStatement, (SwitchStatementSyntax).prototype.__kind = SyntaxKind.SwitchStatement, (BreakStatementSyntax).prototype.__kind = SyntaxKind.BreakStatement, (ContinueStatementSyntax).prototype.__kind = SyntaxKind.ContinueStatement, (ForStatementSyntax).prototype.__kind = SyntaxKind.ForStatement, (ForInStatementSyntax).prototype.__kind = SyntaxKind.ForInStatement, (EmptyStatementSyntax).prototype.__kind = SyntaxKind.EmptyStatement, (ThrowStatementSyntax).prototype.__kind = SyntaxKind.ThrowStatement, (WhileStatementSyntax).prototype.__kind = SyntaxKind.WhileStatement, (TryStatementSyntax).prototype.__kind = SyntaxKind.TryStatement, (LabeledStatementSyntax).prototype.__kind = SyntaxKind.LabeledStatement, (DoStatementSyntax).prototype.__kind = SyntaxKind.DoStatement, (DebuggerStatementSyntax).prototype.__kind = SyntaxKind.DebuggerStatement, (WithStatementSyntax).prototype.__kind = SyntaxKind.WithStatement, (DeleteExpressionSyntax).prototype.__kind = SyntaxKind.DeleteExpression, (TypeOfExpressionSyntax).prototype.__kind = SyntaxKind.TypeOfExpression, (VoidExpressionSyntax).prototype.__kind = SyntaxKind.VoidExpression, (ConditionalExpressionSyntax).prototype.__kind = SyntaxKind.ConditionalExpression, (MemberAccessExpressionSyntax).prototype.__kind = SyntaxKind.MemberAccessExpression, (InvocationExpressionSyntax).prototype.__kind = SyntaxKind.InvocationExpression, (ArrayLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ArrayLiteralExpression, (ObjectLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ObjectLiteralExpression, (ObjectCreationExpressionSyntax).prototype.__kind = SyntaxKind.ObjectCreationExpression, (ParenthesizedExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedExpression, (ParenthesizedArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedArrowFunctionExpression, (SimpleArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.SimpleArrowFunctionExpression, (CastExpressionSyntax).prototype.__kind = SyntaxKind.CastExpression, (ElementAccessExpressionSyntax).prototype.__kind = SyntaxKind.ElementAccessExpression, (FunctionExpressionSyntax).prototype.__kind = SyntaxKind.FunctionExpression, (OmittedExpressionSyntax).prototype.__kind = SyntaxKind.OmittedExpression, (VariableDeclarationSyntax).prototype.__kind = SyntaxKind.VariableDeclaration, (VariableDeclaratorSyntax).prototype.__kind = SyntaxKind.VariableDeclarator, (ArgumentListSyntax).prototype.__kind = SyntaxKind.ArgumentList, (ParameterListSyntax).prototype.__kind = SyntaxKind.ParameterList, (TypeArgumentListSyntax).prototype.__kind = SyntaxKind.TypeArgumentList, (TypeParameterListSyntax).prototype.__kind = SyntaxKind.TypeParameterList, (EqualsValueClauseSyntax).prototype.__kind = SyntaxKind.EqualsValueClause, (CaseSwitchClauseSyntax).prototype.__kind = SyntaxKind.CaseSwitchClause, (DefaultSwitchClauseSyntax).prototype.__kind = SyntaxKind.DefaultSwitchClause, (ElseClauseSyntax).prototype.__kind = SyntaxKind.ElseClause, (CatchClauseSyntax).prototype.__kind = SyntaxKind.CatchClause, (FinallyClauseSyntax).prototype.__kind = SyntaxKind.FinallyClause, (TypeParameterSyntax).prototype.__kind = SyntaxKind.TypeParameter, (ConstraintSyntax).prototype.__kind = SyntaxKind.Constraint, (SimplePropertyAssignmentSyntax).prototype.__kind = SyntaxKind.SimplePropertyAssignment, (FunctionPropertyAssignmentSyntax).prototype.__kind = SyntaxKind.FunctionPropertyAssignment, (ParameterSyntax).prototype.__kind = SyntaxKind.Parameter, (EnumElementSyntax).prototype.__kind = SyntaxKind.EnumElement, (TypeAnnotationSyntax).prototype.__kind = SyntaxKind.TypeAnnotation, (ExternalModuleReferenceSyntax).prototype.__kind = SyntaxKind.ExternalModuleReference, (ModuleNameModuleReferenceSyntax).prototype.__kind = SyntaxKind.ModuleNameModuleReference; + (SourceUnitSyntax).prototype.__kind = SyntaxKind.SourceUnit, (QualifiedNameSyntax).prototype.__kind = SyntaxKind.QualifiedName, (ObjectTypeSyntax).prototype.__kind = SyntaxKind.ObjectType, (FunctionTypeSyntax).prototype.__kind = SyntaxKind.FunctionType, (ArrayTypeSyntax).prototype.__kind = SyntaxKind.ArrayType, (ConstructorTypeSyntax).prototype.__kind = SyntaxKind.ConstructorType, (GenericTypeSyntax).prototype.__kind = SyntaxKind.GenericType, (TypeQuerySyntax).prototype.__kind = SyntaxKind.TypeQuery, (TupleTypeSyntax).prototype.__kind = SyntaxKind.TupleType, (UnionTypeSyntax).prototype.__kind = SyntaxKind.UnionType, (ParenthesizedTypeSyntax).prototype.__kind = SyntaxKind.ParenthesizedType, (InterfaceDeclarationSyntax).prototype.__kind = SyntaxKind.InterfaceDeclaration, (FunctionDeclarationSyntax).prototype.__kind = SyntaxKind.FunctionDeclaration, (ModuleDeclarationSyntax).prototype.__kind = SyntaxKind.ModuleDeclaration, (ClassDeclarationSyntax).prototype.__kind = SyntaxKind.ClassDeclaration, (EnumDeclarationSyntax).prototype.__kind = SyntaxKind.EnumDeclaration, (ImportDeclarationSyntax).prototype.__kind = SyntaxKind.ImportDeclaration, (ExportAssignmentSyntax).prototype.__kind = SyntaxKind.ExportAssignment, (MemberFunctionDeclarationSyntax).prototype.__kind = SyntaxKind.MemberFunctionDeclaration, (MemberVariableDeclarationSyntax).prototype.__kind = SyntaxKind.MemberVariableDeclaration, (ConstructorDeclarationSyntax).prototype.__kind = SyntaxKind.ConstructorDeclaration, (IndexMemberDeclarationSyntax).prototype.__kind = SyntaxKind.IndexMemberDeclaration, (GetAccessorSyntax).prototype.__kind = SyntaxKind.GetAccessor, (SetAccessorSyntax).prototype.__kind = SyntaxKind.SetAccessor, (PropertySignatureSyntax).prototype.__kind = SyntaxKind.PropertySignature, (CallSignatureSyntax).prototype.__kind = SyntaxKind.CallSignature, (ConstructSignatureSyntax).prototype.__kind = SyntaxKind.ConstructSignature, (IndexSignatureSyntax).prototype.__kind = SyntaxKind.IndexSignature, (MethodSignatureSyntax).prototype.__kind = SyntaxKind.MethodSignature, (BlockSyntax).prototype.__kind = SyntaxKind.Block, (IfStatementSyntax).prototype.__kind = SyntaxKind.IfStatement, (VariableStatementSyntax).prototype.__kind = SyntaxKind.VariableStatement, (ExpressionStatementSyntax).prototype.__kind = SyntaxKind.ExpressionStatement, (ReturnStatementSyntax).prototype.__kind = SyntaxKind.ReturnStatement, (SwitchStatementSyntax).prototype.__kind = SyntaxKind.SwitchStatement, (BreakStatementSyntax).prototype.__kind = SyntaxKind.BreakStatement, (ContinueStatementSyntax).prototype.__kind = SyntaxKind.ContinueStatement, (ForStatementSyntax).prototype.__kind = SyntaxKind.ForStatement, (ForInStatementSyntax).prototype.__kind = SyntaxKind.ForInStatement, (EmptyStatementSyntax).prototype.__kind = SyntaxKind.EmptyStatement, (ThrowStatementSyntax).prototype.__kind = SyntaxKind.ThrowStatement, (WhileStatementSyntax).prototype.__kind = SyntaxKind.WhileStatement, (TryStatementSyntax).prototype.__kind = SyntaxKind.TryStatement, (LabeledStatementSyntax).prototype.__kind = SyntaxKind.LabeledStatement, (DoStatementSyntax).prototype.__kind = SyntaxKind.DoStatement, (DebuggerStatementSyntax).prototype.__kind = SyntaxKind.DebuggerStatement, (WithStatementSyntax).prototype.__kind = SyntaxKind.WithStatement, (DeleteExpressionSyntax).prototype.__kind = SyntaxKind.DeleteExpression, (TypeOfExpressionSyntax).prototype.__kind = SyntaxKind.TypeOfExpression, (VoidExpressionSyntax).prototype.__kind = SyntaxKind.VoidExpression, (ConditionalExpressionSyntax).prototype.__kind = SyntaxKind.ConditionalExpression, (MemberAccessExpressionSyntax).prototype.__kind = SyntaxKind.MemberAccessExpression, (InvocationExpressionSyntax).prototype.__kind = SyntaxKind.InvocationExpression, (ArrayLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ArrayLiteralExpression, (ObjectLiteralExpressionSyntax).prototype.__kind = SyntaxKind.ObjectLiteralExpression, (ObjectCreationExpressionSyntax).prototype.__kind = SyntaxKind.ObjectCreationExpression, (ParenthesizedExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedExpression, (ParenthesizedArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.ParenthesizedArrowFunctionExpression, (SimpleArrowFunctionExpressionSyntax).prototype.__kind = SyntaxKind.SimpleArrowFunctionExpression, (CastExpressionSyntax).prototype.__kind = SyntaxKind.CastExpression, (ElementAccessExpressionSyntax).prototype.__kind = SyntaxKind.ElementAccessExpression, (FunctionExpressionSyntax).prototype.__kind = SyntaxKind.FunctionExpression, (OmittedExpressionSyntax).prototype.__kind = SyntaxKind.OmittedExpression, (VariableDeclarationSyntax).prototype.__kind = SyntaxKind.VariableDeclaration, (VariableDeclaratorSyntax).prototype.__kind = SyntaxKind.VariableDeclarator, (ArgumentListSyntax).prototype.__kind = SyntaxKind.ArgumentList, (ParameterListSyntax).prototype.__kind = SyntaxKind.ParameterList, (TypeArgumentListSyntax).prototype.__kind = SyntaxKind.TypeArgumentList, (TypeParameterListSyntax).prototype.__kind = SyntaxKind.TypeParameterList, (EqualsValueClauseSyntax).prototype.__kind = SyntaxKind.EqualsValueClause, (CaseSwitchClauseSyntax).prototype.__kind = SyntaxKind.CaseSwitchClause, (DefaultSwitchClauseSyntax).prototype.__kind = SyntaxKind.DefaultSwitchClause, (ElseClauseSyntax).prototype.__kind = SyntaxKind.ElseClause, (CatchClauseSyntax).prototype.__kind = SyntaxKind.CatchClause, (FinallyClauseSyntax).prototype.__kind = SyntaxKind.FinallyClause, (TypeParameterSyntax).prototype.__kind = SyntaxKind.TypeParameter, (ConstraintSyntax).prototype.__kind = SyntaxKind.Constraint, (SimplePropertyAssignmentSyntax).prototype.__kind = SyntaxKind.SimplePropertyAssignment, (FunctionPropertyAssignmentSyntax).prototype.__kind = SyntaxKind.FunctionPropertyAssignment, (ParameterSyntax).prototype.__kind = SyntaxKind.Parameter, (EnumElementSyntax).prototype.__kind = SyntaxKind.EnumElement, (TypeAnnotationSyntax).prototype.__kind = SyntaxKind.TypeAnnotation, (ExternalModuleReferenceSyntax).prototype.__kind = SyntaxKind.ExternalModuleReference, (ModuleNameModuleReferenceSyntax).prototype.__kind = SyntaxKind.ModuleNameModuleReference; } \ No newline at end of file diff --git a/src/services/syntax/syntaxNodes.interfaces.generated.ts b/src/services/syntax/syntaxNodes.interfaces.generated.ts index 949141ba229..db9b94b421f 100644 --- a/src/services/syntax/syntaxNodes.interfaces.generated.ts +++ b/src/services/syntax/syntaxNodes.interfaces.generated.ts @@ -47,6 +47,16 @@ module TypeScript { types: ITypeSyntax[]; closeBracketToken: ISyntaxToken; } + export interface UnionTypeSyntax extends ISyntaxNode, ITypeSyntax { + left: ITypeSyntax; + barToken: ISyntaxToken; + right: ITypeSyntax; + } + export interface ParenthesizedTypeSyntax extends ISyntaxNode, ITypeSyntax { + openParenToken: ISyntaxToken; + type: ITypeSyntax; + closeParenToken: ISyntaxToken; + } export interface InterfaceDeclarationSyntax extends ISyntaxNode, IModuleElementSyntax { modifiers: ISyntaxToken[]; interfaceKeyword: ISyntaxToken; @@ -483,7 +493,7 @@ module TypeScript { moduleName: INameSyntax; } - export var nodeMetadata: string[][] = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],["moduleElements","endOfFileToken"],["left","dotToken","right"],["openBraceToken","typeMembers","closeBraceToken"],["typeParameterList","parameterList","equalsGreaterThanToken","type"],["type","openBracketToken","closeBracketToken"],["newKeyword","typeParameterList","parameterList","equalsGreaterThanToken","type"],["name","typeArgumentList"],["typeOfKeyword","name"],["openBracketToken","types","closeBracketToken"],["modifiers","interfaceKeyword","identifier","typeParameterList","heritageClauses","body"],["modifiers","functionKeyword","identifier","callSignature","block","semicolonToken"],["modifiers","moduleKeyword","name","stringLiteral","openBraceToken","moduleElements","closeBraceToken"],["modifiers","classKeyword","identifier","typeParameterList","heritageClauses","openBraceToken","classElements","closeBraceToken"],["modifiers","enumKeyword","identifier","openBraceToken","enumElements","closeBraceToken"],["modifiers","importKeyword","identifier","equalsToken","moduleReference","semicolonToken"],["exportKeyword","equalsToken","identifier","semicolonToken"],["modifiers","propertyName","callSignature","block","semicolonToken"],["modifiers","variableDeclarator","semicolonToken"],["modifiers","constructorKeyword","callSignature","block","semicolonToken"],["modifiers","indexSignature","semicolonToken"],["modifiers","getKeyword","propertyName","callSignature","block"],["modifiers","setKeyword","propertyName","callSignature","block"],["propertyName","questionToken","typeAnnotation"],["typeParameterList","parameterList","typeAnnotation"],["newKeyword","callSignature"],["openBracketToken","parameters","closeBracketToken","typeAnnotation"],["propertyName","questionToken","callSignature"],["openBraceToken","statements","closeBraceToken"],["ifKeyword","openParenToken","condition","closeParenToken","statement","elseClause"],["modifiers","variableDeclaration","semicolonToken"],["expression","semicolonToken"],["returnKeyword","expression","semicolonToken"],["switchKeyword","openParenToken","expression","closeParenToken","openBraceToken","switchClauses","closeBraceToken"],["breakKeyword","identifier","semicolonToken"],["continueKeyword","identifier","semicolonToken"],["forKeyword","openParenToken","variableDeclaration","initializer","firstSemicolonToken","condition","secondSemicolonToken","incrementor","closeParenToken","statement"],["forKeyword","openParenToken","variableDeclaration","left","inKeyword","expression","closeParenToken","statement"],["semicolonToken"],["throwKeyword","expression","semicolonToken"],["whileKeyword","openParenToken","condition","closeParenToken","statement"],["tryKeyword","block","catchClause","finallyClause"],["identifier","colonToken","statement"],["doKeyword","statement","whileKeyword","openParenToken","condition","closeParenToken","semicolonToken"],["debuggerKeyword","semicolonToken"],["withKeyword","openParenToken","condition","closeParenToken","statement"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["deleteKeyword","expression"],["typeOfKeyword","expression"],["voidKeyword","expression"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["condition","questionToken","whenTrue","colonToken","whenFalse"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["operand","operatorToken"],["operand","operatorToken"],["expression","dotToken","name"],["expression","argumentList"],["openBracketToken","expressions","closeBracketToken"],["openBraceToken","propertyAssignments","closeBraceToken"],["newKeyword","expression","argumentList"],["openParenToken","expression","closeParenToken"],["callSignature","equalsGreaterThanToken","block","expression"],["parameter","equalsGreaterThanToken","block","expression"],["lessThanToken","type","greaterThanToken","expression"],["expression","openBracketToken","argumentExpression","closeBracketToken"],["functionKeyword","identifier","callSignature","block"],[],["varKeyword","variableDeclarators"],["propertyName","typeAnnotation","equalsValueClause"],["typeArgumentList","openParenToken","arguments","closeParenToken"],["openParenToken","parameters","closeParenToken"],["lessThanToken","typeArguments","greaterThanToken"],["lessThanToken","typeParameters","greaterThanToken"],["extendsOrImplementsKeyword","typeNames"],["extendsOrImplementsKeyword","typeNames"],["equalsToken","value"],["caseKeyword","expression","colonToken","statements"],["defaultKeyword","colonToken","statements"],["elseKeyword","statement"],["catchKeyword","openParenToken","identifier","typeAnnotation","closeParenToken","block"],["finallyKeyword","block"],["identifier","constraint"],["extendsKeyword","typeOrExpression"],["propertyName","colonToken","expression"],["propertyName","callSignature","block"],["dotDotDotToken","modifiers","identifier","questionToken","typeAnnotation","equalsValueClause"],["propertyName","equalsValueClause"],["colonToken","type"],["requireKeyword","openParenToken","stringLiteral","closeParenToken"],["moduleName"],]; + export var nodeMetadata: string[][] = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],["moduleElements","endOfFileToken"],["left","dotToken","right"],["openBraceToken","typeMembers","closeBraceToken"],["typeParameterList","parameterList","equalsGreaterThanToken","type"],["type","openBracketToken","closeBracketToken"],["newKeyword","typeParameterList","parameterList","equalsGreaterThanToken","type"],["name","typeArgumentList"],["typeOfKeyword","name"],["openBracketToken","types","closeBracketToken"],["left","barToken","right"],["openParenToken","type","closeParenToken"],["modifiers","interfaceKeyword","identifier","typeParameterList","heritageClauses","body"],["modifiers","functionKeyword","identifier","callSignature","block","semicolonToken"],["modifiers","moduleKeyword","name","stringLiteral","openBraceToken","moduleElements","closeBraceToken"],["modifiers","classKeyword","identifier","typeParameterList","heritageClauses","openBraceToken","classElements","closeBraceToken"],["modifiers","enumKeyword","identifier","openBraceToken","enumElements","closeBraceToken"],["modifiers","importKeyword","identifier","equalsToken","moduleReference","semicolonToken"],["exportKeyword","equalsToken","identifier","semicolonToken"],["modifiers","propertyName","callSignature","block","semicolonToken"],["modifiers","variableDeclarator","semicolonToken"],["modifiers","constructorKeyword","callSignature","block","semicolonToken"],["modifiers","indexSignature","semicolonToken"],["modifiers","getKeyword","propertyName","callSignature","block"],["modifiers","setKeyword","propertyName","callSignature","block"],["propertyName","questionToken","typeAnnotation"],["typeParameterList","parameterList","typeAnnotation"],["newKeyword","callSignature"],["openBracketToken","parameters","closeBracketToken","typeAnnotation"],["propertyName","questionToken","callSignature"],["openBraceToken","statements","closeBraceToken"],["ifKeyword","openParenToken","condition","closeParenToken","statement","elseClause"],["modifiers","variableDeclaration","semicolonToken"],["expression","semicolonToken"],["returnKeyword","expression","semicolonToken"],["switchKeyword","openParenToken","expression","closeParenToken","openBraceToken","switchClauses","closeBraceToken"],["breakKeyword","identifier","semicolonToken"],["continueKeyword","identifier","semicolonToken"],["forKeyword","openParenToken","variableDeclaration","initializer","firstSemicolonToken","condition","secondSemicolonToken","incrementor","closeParenToken","statement"],["forKeyword","openParenToken","variableDeclaration","left","inKeyword","expression","closeParenToken","statement"],["semicolonToken"],["throwKeyword","expression","semicolonToken"],["whileKeyword","openParenToken","condition","closeParenToken","statement"],["tryKeyword","block","catchClause","finallyClause"],["identifier","colonToken","statement"],["doKeyword","statement","whileKeyword","openParenToken","condition","closeParenToken","semicolonToken"],["debuggerKeyword","semicolonToken"],["withKeyword","openParenToken","condition","closeParenToken","statement"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["operatorToken","operand"],["deleteKeyword","expression"],["typeOfKeyword","expression"],["voidKeyword","expression"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["condition","questionToken","whenTrue","colonToken","whenFalse"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["left","operatorToken","right"],["operand","operatorToken"],["operand","operatorToken"],["expression","dotToken","name"],["expression","argumentList"],["openBracketToken","expressions","closeBracketToken"],["openBraceToken","propertyAssignments","closeBraceToken"],["newKeyword","expression","argumentList"],["openParenToken","expression","closeParenToken"],["callSignature","equalsGreaterThanToken","block","expression"],["parameter","equalsGreaterThanToken","block","expression"],["lessThanToken","type","greaterThanToken","expression"],["expression","openBracketToken","argumentExpression","closeBracketToken"],["functionKeyword","identifier","callSignature","block"],[],["varKeyword","variableDeclarators"],["propertyName","typeAnnotation","equalsValueClause"],["typeArgumentList","openParenToken","arguments","closeParenToken"],["openParenToken","parameters","closeParenToken"],["lessThanToken","typeArguments","greaterThanToken"],["lessThanToken","typeParameters","greaterThanToken"],["extendsOrImplementsKeyword","typeNames"],["extendsOrImplementsKeyword","typeNames"],["equalsToken","value"],["caseKeyword","expression","colonToken","statements"],["defaultKeyword","colonToken","statements"],["elseKeyword","statement"],["catchKeyword","openParenToken","identifier","typeAnnotation","closeParenToken","block"],["finallyKeyword","block"],["identifier","constraint"],["extendsKeyword","typeOrExpression"],["propertyName","colonToken","expression"],["propertyName","callSignature","block"],["dotDotDotToken","modifiers","identifier","questionToken","typeAnnotation","equalsValueClause"],["propertyName","equalsValueClause"],["colonToken","type"],["requireKeyword","openParenToken","stringLiteral","closeParenToken"],["moduleName"],]; export module Syntax { export interface ISyntaxFactory { @@ -497,6 +507,8 @@ module TypeScript { GenericTypeSyntax: { new(data: number, name: INameSyntax, typeArgumentList: TypeArgumentListSyntax): GenericTypeSyntax }; TypeQuerySyntax: { new(data: number, typeOfKeyword: ISyntaxToken, name: INameSyntax): TypeQuerySyntax }; TupleTypeSyntax: { new(data: number, openBracketToken: ISyntaxToken, types: ITypeSyntax[], closeBracketToken: ISyntaxToken): TupleTypeSyntax }; + UnionTypeSyntax: { new(data: number, left: ITypeSyntax, barToken: ISyntaxToken, right: ITypeSyntax): UnionTypeSyntax }; + ParenthesizedTypeSyntax: { new(data: number, openParenToken: ISyntaxToken, type: ITypeSyntax, closeParenToken: ISyntaxToken): ParenthesizedTypeSyntax }; InterfaceDeclarationSyntax: { new(data: number, modifiers: ISyntaxToken[], interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: HeritageClauseSyntax[], body: ObjectTypeSyntax): InterfaceDeclarationSyntax }; FunctionDeclarationSyntax: { new(data: number, modifiers: ISyntaxToken[], functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): FunctionDeclarationSyntax }; ModuleDeclarationSyntax: { new(data: number, modifiers: ISyntaxToken[], moduleKeyword: ISyntaxToken, name: INameSyntax, stringLiteral: ISyntaxToken, openBraceToken: ISyntaxToken, moduleElements: IModuleElementSyntax[], closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax }; diff --git a/src/services/syntax/syntaxVisitor.generated.ts b/src/services/syntax/syntaxVisitor.generated.ts index 55aaef53255..c38f84693b9 100644 --- a/src/services/syntax/syntaxVisitor.generated.ts +++ b/src/services/syntax/syntaxVisitor.generated.ts @@ -14,6 +14,8 @@ module TypeScript { case SyntaxKind.GenericType: return visitor.visitGenericType(element); case SyntaxKind.TypeQuery: return visitor.visitTypeQuery(element); case SyntaxKind.TupleType: return visitor.visitTupleType(element); + case SyntaxKind.UnionType: return visitor.visitUnionType(element); + case SyntaxKind.ParenthesizedType: return visitor.visitParenthesizedType(element); case SyntaxKind.InterfaceDeclaration: return visitor.visitInterfaceDeclaration(element); case SyntaxKind.FunctionDeclaration: return visitor.visitFunctionDeclaration(element); case SyntaxKind.ModuleDeclaration: return visitor.visitModuleDeclaration(element); @@ -111,6 +113,8 @@ module TypeScript { visitGenericType(node: GenericTypeSyntax): any; visitTypeQuery(node: TypeQuerySyntax): any; visitTupleType(node: TupleTypeSyntax): any; + visitUnionType(node: UnionTypeSyntax): any; + visitParenthesizedType(node: ParenthesizedTypeSyntax): any; visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): any; visitFunctionDeclaration(node: FunctionDeclarationSyntax): any; visitModuleDeclaration(node: ModuleDeclarationSyntax): any; diff --git a/src/services/syntax/syntaxWalker.generated.ts b/src/services/syntax/syntaxWalker.generated.ts index 7b335709853..3e4131556aa 100644 --- a/src/services/syntax/syntaxWalker.generated.ts +++ b/src/services/syntax/syntaxWalker.generated.ts @@ -109,6 +109,18 @@ module TypeScript { this.visitToken(node.closeBracketToken); } + public visitUnionType(node: UnionTypeSyntax): void { + this.visitNodeOrToken(node.left); + this.visitToken(node.barToken); + this.visitNodeOrToken(node.right); + } + + public visitParenthesizedType(node: ParenthesizedTypeSyntax): void { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.closeParenToken); + } + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): void { this.visitList(node.modifiers); this.visitToken(node.interfaceKeyword); From f0ea98f5b2a00957ed8dfcbd00fb8dc756d4f12b Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Thu, 30 Oct 2014 13:57:40 -0700 Subject: [PATCH 8/9] Improve walking speed in Fidelity. --- src/services/formatting/formatter.ts | 2 +- .../formatting/indentationTrackingWalker.ts | 26 +- src/services/syntax/depthLimitedWalker.ts | 30 +- src/services/syntax/syntaxGenerator.ts | 86 +++--- src/services/syntax/syntaxWalker.generated.ts | 257 ++++++++---------- 5 files changed, 195 insertions(+), 206 deletions(-) diff --git a/src/services/formatting/formatter.ts b/src/services/formatting/formatter.ts index e4a1229abef..a98d969c059 100644 --- a/src/services/formatting/formatter.ts +++ b/src/services/formatting/formatter.ts @@ -52,7 +52,7 @@ module TypeScript.Services.Formatting { rulesProvider: RulesProvider, formattingRequestKind: FormattingRequestKind): TextEditInfo[] { var walker = new Formatter(textSpan, sourceUnit, indentFirstToken, options, snapshot, rulesProvider, formattingRequestKind); - visitNodeOrToken(walker, sourceUnit); + walker.walk(sourceUnit); return walker.edits(); } diff --git a/src/services/formatting/indentationTrackingWalker.ts b/src/services/formatting/indentationTrackingWalker.ts index b07b477623e..9e9c9e43a64 100644 --- a/src/services/formatting/indentationTrackingWalker.ts +++ b/src/services/formatting/indentationTrackingWalker.ts @@ -16,7 +16,7 @@ /// module TypeScript.Services.Formatting { - export class IndentationTrackingWalker extends SyntaxWalker { + export class IndentationTrackingWalker /*extends SyntaxWalker*/ { private _position: number = 0; private _parent: IndentationNodeContext = null; private _textSpan: TextSpan; @@ -26,7 +26,7 @@ module TypeScript.Services.Formatting { private _text: ISimpleText; constructor(textSpan: TextSpan, sourceUnit: SourceUnitSyntax, snapshot: ITextSnapshot, indentFirstToken: boolean, public options: FormattingOptions) { - super(); + // super(); // Create a pool object to manage context nodes while walking the tree this._indentationNodeContextPool = new IndentationNodeContextPool(); @@ -100,7 +100,23 @@ module TypeScript.Services.Formatting { this._position += token.fullWidth(); } - public visitNode(node: ISyntaxNode): void { + public walk(element: ISyntaxElement) { + if (element && !isShared(element)) { + if (isToken(element)) { + this.visitToken(element); + } + else if (element.kind() === SyntaxKind.List || element.kind() === SyntaxKind.SeparatedList) { + for (var i = 0, n = childCount(element); i < n; i++) { + this.walk(childAt(element, i)); + } + } + else { + this.visitNode(element); + } + } + } + + private visitNode(node: ISyntaxNode): void { var nodeSpan = new TextSpan(this._position, fullWidth(node)); if (nodeSpan.intersectsWithTextSpan(this._textSpan)) { @@ -112,7 +128,9 @@ module TypeScript.Services.Formatting { this._parent = this._indentationNodeContextPool.getNode(currentParent, node, this._position, indentation.indentationAmount, indentation.indentationAmountDelta); // Visit node - visitNodeOrToken(this, node); + for (var i = 0, n = childCount(node); i < n; i++) { + this.walk(childAt(node, i)); + } // Reset state this._indentationNodeContextPool.releaseNode(this._parent); diff --git a/src/services/syntax/depthLimitedWalker.ts b/src/services/syntax/depthLimitedWalker.ts index 79df1ebd836..c697ed42495 100644 --- a/src/services/syntax/depthLimitedWalker.ts +++ b/src/services/syntax/depthLimitedWalker.ts @@ -1,21 +1,21 @@ /// module TypeScript { - export class DepthLimitedWalker extends SyntaxWalker { - private _depth: number = 0; - private _maximumDepth: number = 0; + //export class DepthLimitedWalker extends SyntaxWalker { + // private _depth: number = 0; + // private _maximumDepth: number = 0; - constructor(maximumDepth: number) { - super(); - this._maximumDepth = maximumDepth; - } + // constructor(maximumDepth: number) { + // super(); + // this._maximumDepth = maximumDepth; + // } - public visitNode(node: ISyntaxNode): void { - if (this._depth < this._maximumDepth) { - this._depth++; - super.visitNode(node); - this._depth--; - } - } - } + // public visitNode(node: ISyntaxNode): void { + // if (this._depth < this._maximumDepth) { + // this._depth++; + // super.visitNode(node); + // this._depth--; + // } + // } + //} } \ No newline at end of file diff --git a/src/services/syntax/syntaxGenerator.ts b/src/services/syntax/syntaxGenerator.ts index b6b3e51ecff..5c28954a1c2 100644 --- a/src/services/syntax/syntaxGenerator.ts +++ b/src/services/syntax/syntaxGenerator.ts @@ -2311,19 +2311,19 @@ function generateWalker(): string { " export class SyntaxWalker implements ISyntaxVisitor {\r\n" + " public visitToken(token: ISyntaxToken): void {\r\n" + " }\r\n" + -"\r\n" + -" public visitNode(node: ISyntaxNode): void {\r\n" + -" visitNodeOrToken(this, node);\r\n" + -" }\r\n" + -"\r\n" + -" public visitNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + -" if (isToken(nodeOrToken)) { \r\n" + -" this.visitToken(nodeOrToken);\r\n" + -" }\r\n" + -" else {\r\n" + -" this.visitNode(nodeOrToken);\r\n" + -" }\r\n" + -" }\r\n" + +//"\r\n" + +//" public visitNode(node: ISyntaxNode): void {\r\n" + +//" visitNodeOrToken(this, node);\r\n" + +//" }\r\n" + +//"\r\n" + +//" public visitNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + +//" if (isToken(nodeOrToken)) { \r\n" + +//" this.visitToken(nodeOrToken);\r\n" + +//" }\r\n" + +//" else {\r\n" + +//" this.visitNode(nodeOrToken);\r\n" + +//" }\r\n" + +//" }\r\n" + "\r\n" + " private visitOptionalToken(token: ISyntaxToken): void {\r\n" + " if (token === undefined) {\r\n" + @@ -2332,33 +2332,33 @@ function generateWalker(): string { "\r\n" + " this.visitToken(token);\r\n" + " }\r\n" + -"\r\n" + -" public visitOptionalNode(node: ISyntaxNode): void {\r\n" + -" if (node === undefined) {\r\n" + -" return;\r\n" + -" }\r\n" + -"\r\n" + -" this.visitNode(node);\r\n" + -" }\r\n" + -"\r\n" + -" public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + -" if (nodeOrToken === undefined) {\r\n" + -" return;\r\n" + -" }\r\n" + -"\r\n" + -" this.visitNodeOrToken(nodeOrToken);\r\n" + -" }\r\n" + +//"\r\n" + +//" public visitOptionalNode(node: ISyntaxNode): void {\r\n" + +//" if (node === undefined) {\r\n" + +//" return;\r\n" + +//" }\r\n" + +//"\r\n" + +//" this.visitNode(node);\r\n" + +//" }\r\n" + +//"\r\n" + +//" public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + +//" if (nodeOrToken === undefined) {\r\n" + +//" return;\r\n" + +//" }\r\n" + +//"\r\n" + +//" this.visitNodeOrToken(nodeOrToken);\r\n" + +//" }\r\n" + "\r\n" + " public visitList(list: ISyntaxNodeOrToken[]): void {\r\n" + " for (var i = 0, n = list.length; i < n; i++) {\r\n" + -" this.visitNodeOrToken(list[i]);\r\n" + +" visitNodeOrToken(this, list[i]);\r\n" + " }\r\n" + " }\r\n" + "\r\n" + " public visitSeparatedList(list: ISyntaxNodeOrToken[]): void {\r\n" + " for (var i = 0, n = childCount(list); i < n; i++) {\r\n" + " var item = childAt(list, i);\r\n" + -" this.visitNodeOrToken(item);\r\n" + +" visitNodeOrToken(this, item);\r\n" + " }\r\n" + " }\r\n"; @@ -2386,20 +2386,20 @@ function generateWalker(): string { result += " this.visitSeparatedList(node." + child.name + ");\r\n"; } else if (isNodeOrToken(child)) { - if (child.isOptional) { - result += " this.visitOptionalNodeOrToken(node." + child.name + ");\r\n"; - } - else { - result += " this.visitNodeOrToken(node." + child.name + ");\r\n"; - } + //if (child.isOptional) { + result += " visitNodeOrToken(this, node." + child.name + ");\r\n"; + //} + //else { + // result += " this.visitNodeOrToken(node." + child.name + ");\r\n"; + //} } else if (child.type !== "SyntaxKind") { - if (child.isOptional) { - result += " this.visitOptionalNode(node." + child.name + ");\r\n"; - } - else { - result += " this.visitNode(node." + child.name + ");\r\n"; - } + //if (child.isOptional) { + result += " visitNodeOrToken(this, node." + child.name + ");\r\n"; + //} + //else { + // result += " this.visitNode(node." + child.name + ");\r\n"; + //} } } diff --git a/src/services/syntax/syntaxWalker.generated.ts b/src/services/syntax/syntaxWalker.generated.ts index fe43bd25b18..21c1acefc7f 100644 --- a/src/services/syntax/syntaxWalker.generated.ts +++ b/src/services/syntax/syntaxWalker.generated.ts @@ -5,19 +5,6 @@ module TypeScript { public visitToken(token: ISyntaxToken): void { } - public visitNode(node: ISyntaxNode): void { - visitNodeOrToken(this, node); - } - - public visitNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void { - if (isToken(nodeOrToken)) { - this.visitToken(nodeOrToken); - } - else { - this.visitNode(nodeOrToken); - } - } - private visitOptionalToken(token: ISyntaxToken): void { if (token === undefined) { return; @@ -26,32 +13,16 @@ module TypeScript { this.visitToken(token); } - public visitOptionalNode(node: ISyntaxNode): void { - if (node === undefined) { - return; - } - - this.visitNode(node); - } - - public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void { - if (nodeOrToken === undefined) { - return; - } - - this.visitNodeOrToken(nodeOrToken); - } - public visitList(list: ISyntaxNodeOrToken[]): void { for (var i = 0, n = list.length; i < n; i++) { - this.visitNodeOrToken(list[i]); + visitNodeOrToken(this, list[i]); } } public visitSeparatedList(list: ISyntaxNodeOrToken[]): void { for (var i = 0, n = childCount(list); i < n; i++) { var item = childAt(list, i); - this.visitNodeOrToken(item); + visitNodeOrToken(this, item); } } @@ -61,7 +32,7 @@ module TypeScript { } public visitQualifiedName(node: QualifiedNameSyntax): void { - this.visitNodeOrToken(node.left); + visitNodeOrToken(this, node.left); this.visitToken(node.dotToken); this.visitToken(node.right); } @@ -73,34 +44,34 @@ module TypeScript { } public visitFunctionType(node: FunctionTypeSyntax): void { - this.visitOptionalNode(node.typeParameterList); - this.visitNode(node.parameterList); + visitNodeOrToken(this, node.typeParameterList); + visitNodeOrToken(this, node.parameterList); this.visitToken(node.equalsGreaterThanToken); - this.visitNodeOrToken(node.type); + visitNodeOrToken(this, node.type); } public visitArrayType(node: ArrayTypeSyntax): void { - this.visitNodeOrToken(node.type); + visitNodeOrToken(this, node.type); this.visitToken(node.openBracketToken); this.visitToken(node.closeBracketToken); } public visitConstructorType(node: ConstructorTypeSyntax): void { this.visitToken(node.newKeyword); - this.visitOptionalNode(node.typeParameterList); - this.visitNode(node.parameterList); + visitNodeOrToken(this, node.typeParameterList); + visitNodeOrToken(this, node.parameterList); this.visitToken(node.equalsGreaterThanToken); - this.visitNodeOrToken(node.type); + visitNodeOrToken(this, node.type); } public visitGenericType(node: GenericTypeSyntax): void { - this.visitNodeOrToken(node.name); - this.visitNode(node.typeArgumentList); + visitNodeOrToken(this, node.name); + visitNodeOrToken(this, node.typeArgumentList); } public visitTypeQuery(node: TypeQuerySyntax): void { this.visitToken(node.typeOfKeyword); - this.visitNodeOrToken(node.name); + visitNodeOrToken(this, node.name); } public visitTupleType(node: TupleTypeSyntax): void { @@ -110,14 +81,14 @@ module TypeScript { } public visitUnionType(node: UnionTypeSyntax): void { - this.visitNodeOrToken(node.left); + visitNodeOrToken(this, node.left); this.visitToken(node.barToken); - this.visitNodeOrToken(node.right); + visitNodeOrToken(this, node.right); } public visitParenthesizedType(node: ParenthesizedTypeSyntax): void { this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.type); + visitNodeOrToken(this, node.type); this.visitToken(node.closeParenToken); } @@ -125,24 +96,24 @@ module TypeScript { this.visitList(node.modifiers); this.visitToken(node.interfaceKeyword); this.visitToken(node.identifier); - this.visitOptionalNode(node.typeParameterList); + visitNodeOrToken(this, node.typeParameterList); this.visitList(node.heritageClauses); - this.visitNode(node.body); + visitNodeOrToken(this, node.body); } public visitFunctionDeclaration(node: FunctionDeclarationSyntax): void { this.visitList(node.modifiers); this.visitToken(node.functionKeyword); this.visitToken(node.identifier); - this.visitNode(node.callSignature); - this.visitOptionalNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); this.visitOptionalToken(node.semicolonToken); } public visitModuleDeclaration(node: ModuleDeclarationSyntax): void { this.visitList(node.modifiers); this.visitToken(node.moduleKeyword); - this.visitOptionalNodeOrToken(node.name); + visitNodeOrToken(this, node.name); this.visitOptionalToken(node.stringLiteral); this.visitToken(node.openBraceToken); this.visitList(node.moduleElements); @@ -153,7 +124,7 @@ module TypeScript { this.visitList(node.modifiers); this.visitToken(node.classKeyword); this.visitToken(node.identifier); - this.visitOptionalNode(node.typeParameterList); + visitNodeOrToken(this, node.typeParameterList); this.visitList(node.heritageClauses); this.visitToken(node.openBraceToken); this.visitList(node.classElements); @@ -174,7 +145,7 @@ module TypeScript { this.visitToken(node.importKeyword); this.visitToken(node.identifier); this.visitToken(node.equalsToken); - this.visitNodeOrToken(node.moduleReference); + visitNodeOrToken(this, node.moduleReference); this.visitOptionalToken(node.semicolonToken); } @@ -188,28 +159,28 @@ module TypeScript { public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void { this.visitList(node.modifiers); this.visitToken(node.propertyName); - this.visitNode(node.callSignature); - this.visitOptionalNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); this.visitOptionalToken(node.semicolonToken); } public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): void { this.visitList(node.modifiers); - this.visitNode(node.variableDeclarator); + visitNodeOrToken(this, node.variableDeclarator); this.visitOptionalToken(node.semicolonToken); } public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): void { this.visitList(node.modifiers); this.visitToken(node.constructorKeyword); - this.visitNode(node.callSignature); - this.visitOptionalNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); this.visitOptionalToken(node.semicolonToken); } public visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): void { this.visitList(node.modifiers); - this.visitNode(node.indexSignature); + visitNodeOrToken(this, node.indexSignature); this.visitOptionalToken(node.semicolonToken); } @@ -217,46 +188,46 @@ module TypeScript { this.visitList(node.modifiers); this.visitToken(node.getKeyword); this.visitToken(node.propertyName); - this.visitNode(node.callSignature); - this.visitNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); } public visitSetAccessor(node: SetAccessorSyntax): void { this.visitList(node.modifiers); this.visitToken(node.setKeyword); this.visitToken(node.propertyName); - this.visitNode(node.callSignature); - this.visitNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); } public visitPropertySignature(node: PropertySignatureSyntax): void { this.visitToken(node.propertyName); this.visitOptionalToken(node.questionToken); - this.visitOptionalNode(node.typeAnnotation); + visitNodeOrToken(this, node.typeAnnotation); } public visitCallSignature(node: CallSignatureSyntax): void { - this.visitOptionalNode(node.typeParameterList); - this.visitNode(node.parameterList); - this.visitOptionalNode(node.typeAnnotation); + visitNodeOrToken(this, node.typeParameterList); + visitNodeOrToken(this, node.parameterList); + visitNodeOrToken(this, node.typeAnnotation); } public visitConstructSignature(node: ConstructSignatureSyntax): void { this.visitToken(node.newKeyword); - this.visitNode(node.callSignature); + visitNodeOrToken(this, node.callSignature); } public visitIndexSignature(node: IndexSignatureSyntax): void { this.visitToken(node.openBracketToken); this.visitSeparatedList(node.parameters); this.visitToken(node.closeBracketToken); - this.visitOptionalNode(node.typeAnnotation); + visitNodeOrToken(this, node.typeAnnotation); } public visitMethodSignature(node: MethodSignatureSyntax): void { this.visitToken(node.propertyName); this.visitOptionalToken(node.questionToken); - this.visitNode(node.callSignature); + visitNodeOrToken(this, node.callSignature); } public visitBlock(node: BlockSyntax): void { @@ -268,33 +239,33 @@ module TypeScript { public visitIfStatement(node: IfStatementSyntax): void { this.visitToken(node.ifKeyword); this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.condition); + visitNodeOrToken(this, node.condition); this.visitToken(node.closeParenToken); - this.visitNodeOrToken(node.statement); - this.visitOptionalNode(node.elseClause); + visitNodeOrToken(this, node.statement); + visitNodeOrToken(this, node.elseClause); } public visitVariableStatement(node: VariableStatementSyntax): void { this.visitList(node.modifiers); - this.visitNode(node.variableDeclaration); + visitNodeOrToken(this, node.variableDeclaration); this.visitOptionalToken(node.semicolonToken); } public visitExpressionStatement(node: ExpressionStatementSyntax): void { - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitOptionalToken(node.semicolonToken); } public visitReturnStatement(node: ReturnStatementSyntax): void { this.visitToken(node.returnKeyword); - this.visitOptionalNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitOptionalToken(node.semicolonToken); } public visitSwitchStatement(node: SwitchStatementSyntax): void { this.visitToken(node.switchKeyword); this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitToken(node.closeParenToken); this.visitToken(node.openBraceToken); this.visitList(node.switchClauses); @@ -316,25 +287,25 @@ module TypeScript { public visitForStatement(node: ForStatementSyntax): void { this.visitToken(node.forKeyword); this.visitToken(node.openParenToken); - this.visitOptionalNode(node.variableDeclaration); - this.visitOptionalNodeOrToken(node.initializer); + visitNodeOrToken(this, node.variableDeclaration); + visitNodeOrToken(this, node.initializer); this.visitToken(node.firstSemicolonToken); - this.visitOptionalNodeOrToken(node.condition); + visitNodeOrToken(this, node.condition); this.visitToken(node.secondSemicolonToken); - this.visitOptionalNodeOrToken(node.incrementor); + visitNodeOrToken(this, node.incrementor); this.visitToken(node.closeParenToken); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); } public visitForInStatement(node: ForInStatementSyntax): void { this.visitToken(node.forKeyword); this.visitToken(node.openParenToken); - this.visitOptionalNode(node.variableDeclaration); - this.visitOptionalNodeOrToken(node.left); + visitNodeOrToken(this, node.variableDeclaration); + visitNodeOrToken(this, node.left); this.visitToken(node.inKeyword); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitToken(node.closeParenToken); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); } public visitEmptyStatement(node: EmptyStatementSyntax): void { @@ -343,37 +314,37 @@ module TypeScript { public visitThrowStatement(node: ThrowStatementSyntax): void { this.visitToken(node.throwKeyword); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitOptionalToken(node.semicolonToken); } public visitWhileStatement(node: WhileStatementSyntax): void { this.visitToken(node.whileKeyword); this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.condition); + visitNodeOrToken(this, node.condition); this.visitToken(node.closeParenToken); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); } public visitTryStatement(node: TryStatementSyntax): void { this.visitToken(node.tryKeyword); - this.visitNode(node.block); - this.visitOptionalNode(node.catchClause); - this.visitOptionalNode(node.finallyClause); + visitNodeOrToken(this, node.block); + visitNodeOrToken(this, node.catchClause); + visitNodeOrToken(this, node.finallyClause); } public visitLabeledStatement(node: LabeledStatementSyntax): void { this.visitToken(node.identifier); this.visitToken(node.colonToken); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); } public visitDoStatement(node: DoStatementSyntax): void { this.visitToken(node.doKeyword); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); this.visitToken(node.whileKeyword); this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.condition); + visitNodeOrToken(this, node.condition); this.visitToken(node.closeParenToken); this.visitOptionalToken(node.semicolonToken); } @@ -386,59 +357,59 @@ module TypeScript { public visitWithStatement(node: WithStatementSyntax): void { this.visitToken(node.withKeyword); this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.condition); + visitNodeOrToken(this, node.condition); this.visitToken(node.closeParenToken); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); } public visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): void { this.visitToken(node.operatorToken); - this.visitNodeOrToken(node.operand); + visitNodeOrToken(this, node.operand); } public visitDeleteExpression(node: DeleteExpressionSyntax): void { this.visitToken(node.deleteKeyword); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); } public visitTypeOfExpression(node: TypeOfExpressionSyntax): void { this.visitToken(node.typeOfKeyword); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); } public visitVoidExpression(node: VoidExpressionSyntax): void { this.visitToken(node.voidKeyword); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); } public visitConditionalExpression(node: ConditionalExpressionSyntax): void { - this.visitNodeOrToken(node.condition); + visitNodeOrToken(this, node.condition); this.visitToken(node.questionToken); - this.visitNodeOrToken(node.whenTrue); + visitNodeOrToken(this, node.whenTrue); this.visitToken(node.colonToken); - this.visitNodeOrToken(node.whenFalse); + visitNodeOrToken(this, node.whenFalse); } public visitBinaryExpression(node: BinaryExpressionSyntax): void { - this.visitNodeOrToken(node.left); + visitNodeOrToken(this, node.left); this.visitToken(node.operatorToken); - this.visitNodeOrToken(node.right); + visitNodeOrToken(this, node.right); } public visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): void { - this.visitNodeOrToken(node.operand); + visitNodeOrToken(this, node.operand); this.visitToken(node.operatorToken); } public visitMemberAccessExpression(node: MemberAccessExpressionSyntax): void { - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitToken(node.dotToken); this.visitToken(node.name); } public visitInvocationExpression(node: InvocationExpressionSyntax): void { - this.visitNodeOrToken(node.expression); - this.visitNode(node.argumentList); + visitNodeOrToken(this, node.expression); + visitNodeOrToken(this, node.argumentList); } public visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): void { @@ -455,49 +426,49 @@ module TypeScript { public visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): void { this.visitToken(node.newKeyword); - this.visitNodeOrToken(node.expression); - this.visitOptionalNode(node.argumentList); + visitNodeOrToken(this, node.expression); + visitNodeOrToken(this, node.argumentList); } public visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): void { this.visitToken(node.openParenToken); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitToken(node.closeParenToken); } public visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): void { - this.visitNode(node.callSignature); + visitNodeOrToken(this, node.callSignature); this.visitToken(node.equalsGreaterThanToken); - this.visitOptionalNode(node.block); - this.visitOptionalNodeOrToken(node.expression); + visitNodeOrToken(this, node.block); + visitNodeOrToken(this, node.expression); } public visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): void { - this.visitNode(node.parameter); + visitNodeOrToken(this, node.parameter); this.visitToken(node.equalsGreaterThanToken); - this.visitOptionalNode(node.block); - this.visitOptionalNodeOrToken(node.expression); + visitNodeOrToken(this, node.block); + visitNodeOrToken(this, node.expression); } public visitCastExpression(node: CastExpressionSyntax): void { this.visitToken(node.lessThanToken); - this.visitNodeOrToken(node.type); + visitNodeOrToken(this, node.type); this.visitToken(node.greaterThanToken); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); } public visitElementAccessExpression(node: ElementAccessExpressionSyntax): void { - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitToken(node.openBracketToken); - this.visitNodeOrToken(node.argumentExpression); + visitNodeOrToken(this, node.argumentExpression); this.visitToken(node.closeBracketToken); } public visitFunctionExpression(node: FunctionExpressionSyntax): void { this.visitToken(node.functionKeyword); this.visitOptionalToken(node.identifier); - this.visitNode(node.callSignature); - this.visitNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); } public visitOmittedExpression(node: OmittedExpressionSyntax): void { @@ -510,12 +481,12 @@ module TypeScript { public visitVariableDeclarator(node: VariableDeclaratorSyntax): void { this.visitToken(node.propertyName); - this.visitOptionalNode(node.typeAnnotation); - this.visitOptionalNode(node.equalsValueClause); + visitNodeOrToken(this, node.typeAnnotation); + visitNodeOrToken(this, node.equalsValueClause); } public visitArgumentList(node: ArgumentListSyntax): void { - this.visitOptionalNode(node.typeArgumentList); + visitNodeOrToken(this, node.typeArgumentList); this.visitToken(node.openParenToken); this.visitSeparatedList(node.arguments); this.visitToken(node.closeParenToken); @@ -546,12 +517,12 @@ module TypeScript { public visitEqualsValueClause(node: EqualsValueClauseSyntax): void { this.visitToken(node.equalsToken); - this.visitNodeOrToken(node.value); + visitNodeOrToken(this, node.value); } public visitCaseSwitchClause(node: CaseSwitchClauseSyntax): void { this.visitToken(node.caseKeyword); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); this.visitToken(node.colonToken); this.visitList(node.statements); } @@ -564,43 +535,43 @@ module TypeScript { public visitElseClause(node: ElseClauseSyntax): void { this.visitToken(node.elseKeyword); - this.visitNodeOrToken(node.statement); + visitNodeOrToken(this, node.statement); } public visitCatchClause(node: CatchClauseSyntax): void { this.visitToken(node.catchKeyword); this.visitToken(node.openParenToken); this.visitToken(node.identifier); - this.visitOptionalNode(node.typeAnnotation); + visitNodeOrToken(this, node.typeAnnotation); this.visitToken(node.closeParenToken); - this.visitNode(node.block); + visitNodeOrToken(this, node.block); } public visitFinallyClause(node: FinallyClauseSyntax): void { this.visitToken(node.finallyKeyword); - this.visitNode(node.block); + visitNodeOrToken(this, node.block); } public visitTypeParameter(node: TypeParameterSyntax): void { this.visitToken(node.identifier); - this.visitOptionalNode(node.constraint); + visitNodeOrToken(this, node.constraint); } public visitConstraint(node: ConstraintSyntax): void { this.visitToken(node.extendsKeyword); - this.visitNodeOrToken(node.typeOrExpression); + visitNodeOrToken(this, node.typeOrExpression); } public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): void { this.visitToken(node.propertyName); this.visitToken(node.colonToken); - this.visitNodeOrToken(node.expression); + visitNodeOrToken(this, node.expression); } public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): void { this.visitToken(node.propertyName); - this.visitNode(node.callSignature); - this.visitNode(node.block); + visitNodeOrToken(this, node.callSignature); + visitNodeOrToken(this, node.block); } public visitParameter(node: ParameterSyntax): void { @@ -608,18 +579,18 @@ module TypeScript { this.visitList(node.modifiers); this.visitToken(node.identifier); this.visitOptionalToken(node.questionToken); - this.visitOptionalNode(node.typeAnnotation); - this.visitOptionalNode(node.equalsValueClause); + visitNodeOrToken(this, node.typeAnnotation); + visitNodeOrToken(this, node.equalsValueClause); } public visitEnumElement(node: EnumElementSyntax): void { this.visitToken(node.propertyName); - this.visitOptionalNode(node.equalsValueClause); + visitNodeOrToken(this, node.equalsValueClause); } public visitTypeAnnotation(node: TypeAnnotationSyntax): void { this.visitToken(node.colonToken); - this.visitNodeOrToken(node.type); + visitNodeOrToken(this, node.type); } public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): void { @@ -630,7 +601,7 @@ module TypeScript { } public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): void { - this.visitNodeOrToken(node.moduleName); + visitNodeOrToken(this, node.moduleName); } } } \ No newline at end of file From 84f0348420e11bf0b762cef0628a84edddb74602 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Thu, 30 Oct 2014 14:06:35 -0700 Subject: [PATCH 9/9] Removing commented out code. --- .../formatting/indentationTrackingWalker.ts | 4 +- src/services/syntax/depthLimitedWalker.ts | 21 ---------- src/services/syntax/syntaxGenerator.ts | 41 +------------------ 3 files changed, 2 insertions(+), 64 deletions(-) diff --git a/src/services/formatting/indentationTrackingWalker.ts b/src/services/formatting/indentationTrackingWalker.ts index 9e9c9e43a64..2863b2e4fcc 100644 --- a/src/services/formatting/indentationTrackingWalker.ts +++ b/src/services/formatting/indentationTrackingWalker.ts @@ -16,7 +16,7 @@ /// module TypeScript.Services.Formatting { - export class IndentationTrackingWalker /*extends SyntaxWalker*/ { + export class IndentationTrackingWalker { private _position: number = 0; private _parent: IndentationNodeContext = null; private _textSpan: TextSpan; @@ -26,8 +26,6 @@ module TypeScript.Services.Formatting { private _text: ISimpleText; constructor(textSpan: TextSpan, sourceUnit: SourceUnitSyntax, snapshot: ITextSnapshot, indentFirstToken: boolean, public options: FormattingOptions) { - // super(); - // Create a pool object to manage context nodes while walking the tree this._indentationNodeContextPool = new IndentationNodeContextPool(); diff --git a/src/services/syntax/depthLimitedWalker.ts b/src/services/syntax/depthLimitedWalker.ts index c697ed42495..e69de29bb2d 100644 --- a/src/services/syntax/depthLimitedWalker.ts +++ b/src/services/syntax/depthLimitedWalker.ts @@ -1,21 +0,0 @@ -/// - -module TypeScript { - //export class DepthLimitedWalker extends SyntaxWalker { - // private _depth: number = 0; - // private _maximumDepth: number = 0; - - // constructor(maximumDepth: number) { - // super(); - // this._maximumDepth = maximumDepth; - // } - - // public visitNode(node: ISyntaxNode): void { - // if (this._depth < this._maximumDepth) { - // this._depth++; - // super.visitNode(node); - // this._depth--; - // } - // } - //} -} \ No newline at end of file diff --git a/src/services/syntax/syntaxGenerator.ts b/src/services/syntax/syntaxGenerator.ts index 5c28954a1c2..c1839074167 100644 --- a/src/services/syntax/syntaxGenerator.ts +++ b/src/services/syntax/syntaxGenerator.ts @@ -2311,19 +2311,6 @@ function generateWalker(): string { " export class SyntaxWalker implements ISyntaxVisitor {\r\n" + " public visitToken(token: ISyntaxToken): void {\r\n" + " }\r\n" + -//"\r\n" + -//" public visitNode(node: ISyntaxNode): void {\r\n" + -//" visitNodeOrToken(this, node);\r\n" + -//" }\r\n" + -//"\r\n" + -//" public visitNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + -//" if (isToken(nodeOrToken)) { \r\n" + -//" this.visitToken(nodeOrToken);\r\n" + -//" }\r\n" + -//" else {\r\n" + -//" this.visitNode(nodeOrToken);\r\n" + -//" }\r\n" + -//" }\r\n" + "\r\n" + " private visitOptionalToken(token: ISyntaxToken): void {\r\n" + " if (token === undefined) {\r\n" + @@ -2332,22 +2319,6 @@ function generateWalker(): string { "\r\n" + " this.visitToken(token);\r\n" + " }\r\n" + -//"\r\n" + -//" public visitOptionalNode(node: ISyntaxNode): void {\r\n" + -//" if (node === undefined) {\r\n" + -//" return;\r\n" + -//" }\r\n" + -//"\r\n" + -//" this.visitNode(node);\r\n" + -//" }\r\n" + -//"\r\n" + -//" public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {\r\n" + -//" if (nodeOrToken === undefined) {\r\n" + -//" return;\r\n" + -//" }\r\n" + -//"\r\n" + -//" this.visitNodeOrToken(nodeOrToken);\r\n" + -//" }\r\n" + "\r\n" + " public visitList(list: ISyntaxNodeOrToken[]): void {\r\n" + " for (var i = 0, n = list.length; i < n; i++) {\r\n" + @@ -2386,20 +2357,10 @@ function generateWalker(): string { result += " this.visitSeparatedList(node." + child.name + ");\r\n"; } else if (isNodeOrToken(child)) { - //if (child.isOptional) { - result += " visitNodeOrToken(this, node." + child.name + ");\r\n"; - //} - //else { - // result += " this.visitNodeOrToken(node." + child.name + ");\r\n"; - //} + result += " visitNodeOrToken(this, node." + child.name + ");\r\n"; } else if (child.type !== "SyntaxKind") { - //if (child.isOptional) { result += " visitNodeOrToken(this, node." + child.name + ");\r\n"; - //} - //else { - // result += " this.visitNode(node." + child.name + ");\r\n"; - //} } }