Merge branch 'master' into templates

This commit is contained in:
Daniel Rosenwasser
2014-10-30 15:26:27 -07:00
38 changed files with 1532 additions and 1994 deletions
+281 -190
View File
@@ -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) {
+514 -401
View File
File diff suppressed because it is too large Load Diff
+18 -20
View File
@@ -5468,31 +5468,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;
}
}
}
-69
View File
@@ -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);
}
-721
View File
@@ -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.
//
///<reference path='references.ts' />
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<IAstWalkChildren>(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;
}
}
+3 -3
View File
@@ -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<T>(array: T[], func: (v: T, index: number) => boolean): T {
@@ -82,7 +82,7 @@ module TypeScript {
}
}
return null;
return undefined;
}
public static first<T>(array: T[], func?: (v: T, index: number) => boolean): T {
+2 -1
View File
@@ -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);
}
}
+3 -3
View File
@@ -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 {
+2 -2
View File
@@ -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();
}
+1 -1
View File
@@ -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();
}
@@ -16,7 +16,7 @@
///<reference path='formatting.ts' />
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();
@@ -100,7 +98,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(<ISyntaxToken>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(<ISyntaxNode>element);
}
}
}
private visitNode(node: ISyntaxNode): void {
var nodeSpan = new TextSpan(this._position, fullWidth(node));
if (nodeSpan.intersectsWithTextSpan(this._textSpan)) {
@@ -112,7 +126,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);
+29 -47
View File
@@ -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<string>;
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;
@@ -749,32 +737,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;
@@ -792,21 +759,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 = <SourceFileObject><any>createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), languageVersion, version, isOpen);
newSourceFile.scriptSnapshot = scriptSnapshot;
newSourceFile.syntaxTree = syntaxTree;
return newSourceFile;
}
}
@@ -1328,7 +1286,7 @@ module ts {
return "";
}
interface DisplayPartsSymbolWriter extends SymbolWriter {
export interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
}
@@ -1637,7 +1595,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;
@@ -1645,22 +1605,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) {
@@ -5093,10 +5068,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) {
@@ -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 {
@@ -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);
}
-21
View File
@@ -1,21 +0,0 @@
///<reference path='references.ts' />
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--;
}
}
}
}
+34 -34
View File
@@ -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 <ISyntaxNodeOrToken>result;
@@ -699,12 +699,12 @@ module TypeScript.IncrementalParser {
function currentNode(): ISyntaxNode {
var element = currentNodeOrToken();
return isNode(element) ? <ISyntaxNode>element : null;
return isNode(element) ? <ISyntaxNode>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 : <ISyntaxToken>element;
// Debug.assert(element === undefined || element.isToken());
return <ISyntaxToken>element;
}
return {
+235 -147
View File
@@ -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 <EnumElementSyntax>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<HeritageClauseSyntax>();
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<HeritageClauseSyntax>(ListParsingState.ClassOrInterfaceDeclaration_HeritageClauses, null);
heritageClauses = parseSyntaxList<HeritageClauseSyntax>(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 = <VariableDeclaratorSyntax>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<IStatementSyntax>(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 {
@@ -3532,6 +3533,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 +3605,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,10 +3615,14 @@ 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) {
return null;
if (name === undefined) {
return undefined;
}
// TypeReference:
@@ -3599,23 +3634,76 @@ 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) {
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());
@@ -3628,7 +3716,7 @@ module TypeScript.Parser {
}
function isParameter(): boolean {
if (currentNode() !== null && currentNode().kind() === SyntaxKind.Parameter) {
if (currentNode() && currentNode().kind() === SyntaxKind.Parameter) {
return true;
}
@@ -3644,13 +3732,13 @@ module TypeScript.Parser {
function eatSimpleParameter() {
return new syntaxFactory.ParameterSyntax(parseNodeData,
/*dotDotDotToken:*/ null, /*modifiers:*/ Syntax.emptyList<ISyntaxToken>(), eatIdentifierToken(),
/*questionToken:*/ null, /*typeAnnotation:*/ null, /*equalsValueClause:*/ null);
/*dotDotDotToken:*/ undefined, /*modifiers:*/ Syntax.emptyList<ISyntaxToken>(), 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 <ParameterSyntax>node;
}
@@ -3661,7 +3749,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 +3758,7 @@ module TypeScript.Parser {
modifiers = Syntax.list([consumeToken(_currentToken)]);
}
else {
return null;
return undefined;
}
}
@@ -3678,7 +3766,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 +3775,7 @@ module TypeScript.Parser {
}
function parseSyntaxList<T extends ISyntaxNodeOrToken>(
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 +3857,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 +3895,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 +3934,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 +4355,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();
}
}
+23 -9
View File
@@ -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);
@@ -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();
@@ -472,7 +486,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 +757,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];
+16 -17
View File
@@ -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);
}
@@ -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 {
+1 -1
View File
@@ -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;
}
}
+9 -9
View File
@@ -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;
}
+18 -18
View File
@@ -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 ? <ISyntaxToken>element : null;
return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? <ISyntaxToken>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 ? <ISyntaxToken>element : null;
return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? <ISyntaxToken>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;
}
+1 -1
View File
@@ -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 {
+59 -75
View File
@@ -2,6 +2,7 @@
///<reference path='..\core\environment.ts' />
///<reference path='syntaxFacts.ts' />
///<reference path='syntaxKind.ts' />
///<reference path='..\..\..\tests\fidelity\es5compat.ts' />
// 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
},
<any> {
name: 'UnionTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'left', type: 'ITypeSyntax' },
<any>{ name: 'barToken', isToken: true, excludeFromAST: true },
<any>{ name: 'right', type: 'ITypeSyntax' }
],
isTypeScriptSpecific: true
},
<any> {
name: 'ParenthesizedTypeSyntax',
baseType: 'ISyntaxNode',
interfaces: ['ITypeSyntax'],
children: [
<any>{ name: 'openParenToken', isToken: true, excludeFromAST: true },
<any>{ name: 'type', type: 'ITypeSyntax' },
<any>{ name: 'closeParenToken', isToken: true, excludeFromAST: true }
],
isTypeScriptSpecific: true
},
<any>{
name: 'TypeAnnotationSyntax',
baseType: 'ISyntaxNode',
@@ -1065,7 +1088,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 +1120,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 +1234,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 +1291,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 +1408,7 @@ function generateFactory1Method(definition: ITypeDefinition): string {
result += "Syntax.emptySeparatedList<" + child.elementType + ">()";
}
else {
result += "null";
result += "undefined";
}
result += ", ";
@@ -1412,7 +1435,7 @@ function isKeywordOrPunctuation(kind: string): boolean {
}
function isDefaultConstructable(definition: ITypeDefinition): boolean {
if (definition === null) {
if (!definition) {
return false;
}
@@ -1489,7 +1512,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 +1638,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 +1654,7 @@ function generateFirstTokenMethod(definition: ITypeDefinition): string {
result += " if (";
if (child.isOptional) {
result += getPropertyAccess(child) + " !== null && ";
result += getPropertyAccess(child) + " && ";
}
if (child.isToken) {
@@ -1639,7 +1662,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 +1671,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 +1691,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 +1707,7 @@ function generateLastTokenMethod(definition: ITypeDefinition): string {
result += " if (";
if (child.isOptional) {
result += getPropertyAccess(child) + " !== null && ";
result += getPropertyAccess(child) + " && ";
}
if (child.isToken) {
@@ -1692,12 +1715,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 +1739,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 +1932,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 +1953,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 +2196,13 @@ function generateRewriter(): string {
" }\r\n" +
"\r\n" +
" public visitList<T extends ISyntaxNodeOrToken>(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 = <T>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 +2214,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<T>(newItems);\r\n" +
" // Debug.assert(!newItems || newItems.length === childCount(list));\r\n" +
" return !newItems ? list : Syntax.list<T>(newItems);\r\n" +
" }\r\n" +
"\r\n" +
" public visitSeparatedList<T extends ISyntaxNodeOrToken>(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) ? <ISyntaxNodeOrToken>this.visitToken(<ISyntaxToken>item) : this.visitNode(<ISyntaxNode>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 +2237,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<T>(newItems);\r\n" +
" // Debug.assert(newItems === undefined || newItems.length === childCount(list));\r\n" +
" return !newItems ? list : Syntax.separatedList<T>(newItems);\r\n" +
" }\r\n";
for (var i = 0; i < definitions.length; i++) {
@@ -2242,7 +2265,7 @@ function generateRewriter(): string {
result += " ";
if (child.isOptional) {
result += "node." + child.name + " === null ? null : ";
result += "!node." + child.name + " ? undefined : ";
}
if (child.isToken) {
@@ -2289,53 +2312,24 @@ function generateWalker(): string {
" 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(<ISyntaxToken>nodeOrToken);\r\n" +
" }\r\n" +
" else {\r\n" +
" this.visitNode(<ISyntaxNode>nodeOrToken);\r\n" +
" }\r\n" +
" }\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" +
" this.visitToken(token);\r\n" +
" }\r\n" +
"\r\n" +
" public visitOptionalNode(node: ISyntaxNode): void {\r\n" +
" if (node === null) {\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 === null) {\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";
@@ -2363,20 +2357,10 @@ 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";
}
result += " visitNodeOrToken(this, 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";
}
result += " visitNodeOrToken(this, node." + child.name + ");\r\n";
}
}
@@ -2535,7 +2519,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(<ISyntaxToken>element); }\r\n";
result += " switch (element.kind()) {\r\n";
@@ -2584,7 +2568,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 +2722,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(<ISyntaxNodeOrToken[]>element); }\r\n";
result += " if (isSeparatedList(element)) { return isSeparatedListTypeScriptSpecific(<ISyntaxNodeOrToken[]>element); }\r\n\r\n";
@@ -2855,7 +2839,7 @@ function generateIsTypeScriptSpecificMethod(definition: ITypeDefinition): string
result += getPropertyAccess(child, "node") + ".childCount() > 0";
}
else {
result += getPropertyAccess(child, "node") + " !== null";
result += "!!" + getPropertyAccess(child, "node");
}
}
else {
+2
View File
@@ -159,6 +159,8 @@ module TypeScript {
GenericType,
TypeQuery,
TupleType,
UnionType,
ParenthesizedType,
// Module elements.
InterfaceDeclaration,
+2 -2
View File
@@ -51,7 +51,7 @@ module TypeScript.Syntax {
}
export function list<T extends ISyntaxNodeOrToken>(nodes: T[]): T[] {
if (nodes === undefined || nodes === null || nodes.length === 0) {
if (!nodes || nodes.length === 0) {
return emptyList<T>();
}
@@ -63,7 +63,7 @@ module TypeScript.Syntax {
}
export function separatedList<T extends ISyntaxNodeOrToken>(nodes: T[], separators: ISyntaxToken[]): T[] {
if (nodes === undefined || nodes === null || nodes.length === 0) {
if (!nodes || nodes.length === 0) {
return emptySeparatedList<T>();
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+11 -11
View File
@@ -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.
+17 -17
View File
@@ -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*<amd-dependency\s+path=('|")(.+?)\1/gim;
var match = amdDependencyRegEx.exec(comment);
return match ? match[2] : null;
return match ? match[2] : undefined;
}
public isExternalModule(): boolean {
@@ -144,7 +144,7 @@ module TypeScript {
this.text = syntaxTree.text;
}
private pushDiagnostic(element: ISyntaxElement, diagnosticKey: string, args: any[] = null): void {
private pushDiagnostic(element: ISyntaxElement, diagnosticKey: string, args?: any[]): void {
this.diagnostics.push(new Diagnostic(
this.syntaxTree.fileName(), this.syntaxTree.lineMap(), start(element, this.text), width(element), diagnosticKey, args));
}
@@ -303,7 +303,7 @@ module TypeScript {
}
public visitVariableDeclaration(node: VariableDeclarationSyntax): void {
if (this.checkForAtLeastOneElement(node, node.variableDeclarators, node.varKeyword, getLocalizedText(DiagnosticCode.variable_declaration, null)) ||
if (this.checkForAtLeastOneElement(node, node.variableDeclarators, node.varKeyword, getLocalizedText(DiagnosticCode.variable_declaration, undefined)) ||
this.checkForTrailingComma(node.variableDeclarators)) {
return;
}
@@ -313,7 +313,7 @@ module TypeScript {
public visitTypeArgumentList(node: TypeArgumentListSyntax): void {
if (this.checkForTrailingComma(node.typeArguments) ||
this.checkForAtLeastOneElement(node, node.typeArguments, node.lessThanToken, getLocalizedText(DiagnosticCode.type_argument, null))) {
this.checkForAtLeastOneElement(node, node.typeArguments, node.lessThanToken, getLocalizedText(DiagnosticCode.type_argument, undefined))) {
return;
}
@@ -322,7 +322,7 @@ module TypeScript {
public visitTupleType(node: TupleTypeSyntax): void {
if (this.checkForTrailingComma(node.types) ||
this.checkForAtLeastOneElement(node, node.types, node.openBracketToken, getLocalizedText(DiagnosticCode.type, null))) {
this.checkForAtLeastOneElement(node, node.types, node.openBracketToken, getLocalizedText(DiagnosticCode.type, undefined))) {
return
}
@@ -331,7 +331,7 @@ module TypeScript {
public visitTypeParameterList(node: TypeParameterListSyntax): void {
if (this.checkForTrailingComma(node.typeParameters) ||
this.checkForAtLeastOneElement(node, node.typeParameters, node.lessThanToken, getLocalizedText(DiagnosticCode.type_parameter, null))) {
this.checkForAtLeastOneElement(node, node.typeParameters, node.lessThanToken, getLocalizedText(DiagnosticCode.type_parameter, undefined))) {
return;
}
@@ -635,7 +635,7 @@ module TypeScript {
}
private checkForDisallowedAccessorTypeParameters(callSignature: CallSignatureSyntax): boolean {
if (callSignature.typeParameterList !== null) {
if (callSignature.typeParameterList) {
this.pushDiagnostic(callSignature.typeParameterList, DiagnosticCode.Type_parameters_cannot_appear_on_an_accessor);
return true;
}
@@ -745,7 +745,7 @@ module TypeScript {
public visitInvocationExpression(node: InvocationExpressionSyntax): void {
if (node.expression.kind() === SyntaxKind.SuperKeyword &&
node.argumentList.typeArgumentList !== null) {
node.argumentList.typeArgumentList) {
this.pushDiagnostic(node, DiagnosticCode.super_invocation_cannot_have_type_arguments);
}
@@ -1529,11 +1529,11 @@ module TypeScript {
}
}
return null;
return undefined;
}
private isEvalOrArguments(expr: IExpressionSyntax): boolean {
return this.getEvalOrArguments(expr) !== null;
return !!this.getEvalOrArguments(expr);
}
public visitConstraint(node: ConstraintSyntax): void {
@@ -1583,7 +1583,7 @@ module TypeScript {
}
}
return null;
return undefined;
}
function implicitImportSpanWorker(trivia: ISyntaxTrivia): TextSpan {
@@ -1594,7 +1594,7 @@ module TypeScript {
return new TextSpan(trivia.fullStart(), trivia.fullWidth());
}
return null;
return undefined;
}
function topLevelImportOrExportSpan(node: SourceUnitSyntax): TextSpan {
@@ -1602,7 +1602,7 @@ module TypeScript {
var moduleElement = node.moduleElements[i];
var _firstToken = firstToken(moduleElement);
if (_firstToken !== null && _firstToken.kind() === SyntaxKind.ExportKeyword) {
if (_firstToken && _firstToken.kind() === SyntaxKind.ExportKeyword) {
return new TextSpan(start(_firstToken), width(_firstToken));
}
@@ -1615,6 +1615,6 @@ module TypeScript {
}
}
return null;
return undefined;
}
}
+1 -1
View File
@@ -233,7 +233,7 @@ module TypeScript.Syntax {
}
export function triviaList(trivia: ISyntaxTrivia[]): ISyntaxTriviaList {
if (trivia === undefined || trivia === null || trivia.length === 0) {
if (!trivia || trivia.length === 0) {
return Syntax.emptyTriviaList;
}
+6 -6
View File
@@ -21,7 +21,7 @@ module TypeScript {
public static isLastTokenOnLine(token: ISyntaxToken, text: ISimpleText): boolean {
var _nextToken = nextToken(token, text);
if (_nextToken === null) {
if (_nextToken === undefined) {
return true;
}
@@ -252,7 +252,7 @@ module TypeScript {
public static isAngleBracket(positionedElement: ISyntaxElement): boolean {
var element = positionedElement;
var parent = positionedElement.parent;
if (parent !== null && (element.kind() === SyntaxKind.LessThanToken || element.kind() === SyntaxKind.GreaterThanToken)) {
if (parent && (element.kind() === SyntaxKind.LessThanToken || element.kind() === SyntaxKind.GreaterThanToken)) {
switch (parent.kind()) {
case SyntaxKind.TypeArgumentList:
case SyntaxKind.TypeParameterList:
@@ -272,15 +272,15 @@ module TypeScript {
}
}
return null;
return undefined;
}
public static containsToken(list: ISyntaxToken[], kind: SyntaxKind): boolean {
return SyntaxUtilities.getToken(list, kind) !== null;
return !!SyntaxUtilities.getToken(list, kind);
}
public static hasExportKeyword(moduleElement: IModuleElementSyntax): boolean {
return SyntaxUtilities.getExportKeyword(moduleElement) !== null;
return !!SyntaxUtilities.getExportKeyword(moduleElement);
}
public static getExportKeyword(moduleElement: IModuleElementSyntax): ISyntaxToken {
@@ -294,7 +294,7 @@ module TypeScript {
case SyntaxKind.ImportDeclaration:
return SyntaxUtilities.getToken((<any>moduleElement).modifiers, SyntaxKind.ExportKeyword);
default:
return null;
return undefined;
}
}
@@ -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(<ISyntaxToken>element); }
switch (element.kind()) {
case SyntaxKind.SourceUnit: return visitor.visitSourceUnit(<SourceUnitSyntax>element);
@@ -14,6 +14,8 @@ module TypeScript {
case SyntaxKind.GenericType: return visitor.visitGenericType(<GenericTypeSyntax>element);
case SyntaxKind.TypeQuery: return visitor.visitTypeQuery(<TypeQuerySyntax>element);
case SyntaxKind.TupleType: return visitor.visitTupleType(<TupleTypeSyntax>element);
case SyntaxKind.UnionType: return visitor.visitUnionType(<UnionTypeSyntax>element);
case SyntaxKind.ParenthesizedType: return visitor.visitParenthesizedType(<ParenthesizedTypeSyntax>element);
case SyntaxKind.InterfaceDeclaration: return visitor.visitInterfaceDeclaration(<InterfaceDeclarationSyntax>element);
case SyntaxKind.FunctionDeclaration: return visitor.visitFunctionDeclaration(<FunctionDeclarationSyntax>element);
case SyntaxKind.ModuleDeclaration: return visitor.visitModuleDeclaration(<ModuleDeclarationSyntax>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;
+124 -141
View File
@@ -5,53 +5,24 @@ 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(<ISyntaxToken>nodeOrToken);
}
else {
this.visitNode(<ISyntaxNode>nodeOrToken);
}
}
private visitOptionalToken(token: ISyntaxToken): void {
if (token === null) {
if (token === undefined) {
return;
}
this.visitToken(token);
}
public visitOptionalNode(node: ISyntaxNode): void {
if (node === null) {
return;
}
this.visitNode(node);
}
public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {
if (nodeOrToken === null) {
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 {
@@ -109,28 +80,40 @@ module TypeScript {
this.visitToken(node.closeBracketToken);
}
public visitUnionType(node: UnionTypeSyntax): void {
visitNodeOrToken(this, node.left);
this.visitToken(node.barToken);
visitNodeOrToken(this, node.right);
}
public visitParenthesizedType(node: ParenthesizedTypeSyntax): void {
this.visitToken(node.openParenToken);
visitNodeOrToken(this, node.type);
this.visitToken(node.closeParenToken);
}
public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): void {
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);
@@ -141,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);
@@ -162,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);
}
@@ -176,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);
}
@@ -205,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 {
@@ -256,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);
@@ -304,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 {
@@ -331,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);
}
@@ -374,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 {
@@ -443,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 {
@@ -498,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);
@@ -534,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);
}
@@ -552,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 {
@@ -596,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 {
@@ -618,7 +601,7 @@ module TypeScript {
}
public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): void {
this.visitNodeOrToken(node.moduleName);
visitNodeOrToken(this, node.moduleName);
}
}
}
+4 -4
View File
@@ -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;
}
+1 -1
View File
@@ -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) {
}
+3 -3
View File
@@ -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());
}
+4 -4
View File
@@ -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;
}
/**