From 8199b0b2363c15d22406040f20e22fe1c5040f12 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 29 Jul 2014 18:21:16 -0700 Subject: [PATCH 01/29] Pull model for contextual types. New baselines reflect a couple of unrelated bug fixes. --- src/compiler/checker.ts | 453 ++++++++++++------ src/compiler/types.ts | 19 +- .../functionImplementationErrors.errors.txt | 4 +- .../parserCastVersusArrowFunction1.errors.txt | 16 +- .../reference/parserRealSource8.errors.txt | 4 +- .../parserVariableDeclaration3.errors.txt | 4 +- 6 files changed, 342 insertions(+), 158 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5b4ada0ac86..fd89c889f9e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -41,6 +41,9 @@ module ts { var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = 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: SymbolTable = {}; var globalObjectType: ObjectType; @@ -1179,23 +1182,28 @@ module ts { var links = getSymbolLinks(symbol); if (!links.type) { if (symbol.flags & SymbolFlags.Prototype) { - links.type = getTypeOfPrototypeProperty(symbol); + return links.type = getTypeOfPrototypeProperty(symbol); } - else { - links.type = resolvingType; - var type = getTypeOfVariableDeclaration(symbol.valueDeclaration); - if (links.type === resolvingType) { - links.type = type; + var declaration = symbol.valueDeclaration; + if (declaration.kind === SyntaxKind.Parameter && !declaration.type) { + var parent = declaration.parent; + if (parent.kind === SyntaxKind.FunctionExpression || parent.kind === SyntaxKind.ArrowFunction) { + assignContextualTypes(parent); + if (links.type) { + return links.type; + } } } + links.type = resolvingType; + var type = getTypeOfVariableDeclaration(symbol.valueDeclaration); + if (links.type === resolvingType) { + links.type = type; + } } - else if (links.type === resolvingType) { links.type = anyType; } - return links.type; - } function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode { @@ -2269,15 +2277,17 @@ module ts { } function instantiateType(type: Type, mapper: TypeMapper): Type { - if (type.flags & TypeFlags.TypeParameter) { - return mapper(type); - } - if (type.flags & TypeFlags.Anonymous) { - return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) ? - instantiateAnonymousType(type, mapper) : type; - } - if (type.flags & TypeFlags.Reference) { - return createTypeReference((type).target, instantiateList((type).typeArguments, mapper, instantiateType)); + if (mapper !== identityMapper) { + if (type.flags & TypeFlags.TypeParameter) { + return mapper(type); + } + if (type.flags & TypeFlags.Anonymous) { + return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) ? + instantiateAnonymousType(type, mapper) : type; + } + if (type.flags & TypeFlags.Reference) { + return createTypeReference((type).target, instantiateList((type).typeArguments, mapper, instantiateType)); + } } return type; } @@ -3434,22 +3444,157 @@ module ts { return unknownType; } + function getTypeOfExpression(node: Expression): Type { + // TODO: Return type cached in NodeLinks + return checkExpression(node); + } + + function getContextualTypeForInitializerExpression(node: Expression): Type { + var declaration = node.parent; + if (node === declaration.initializer) { + if (declaration.type) { + return getTypeFromTypeNode(declaration.type); + } + if (declaration.kind === SyntaxKind.Parameter) { + var func = declaration.parent; + if (func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction) { + if (isContextSensitiveExpression(func)) { + var type = getContextualType(func); + if (type) { + var signature = getContextualSignature(type); + if (signature) { + return getTypeAtPosition(signature, indexOf(func.parameters, declaration)); + } + } + } + } + } + } + return undefined; + } + + function getContextualTypeForReturnExpression(node: Expression): Type { + var func = getContainingFunction(node); + if (func) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + if (func.type || func.kind === SyntaxKind.Constructor || func.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(func.symbol, SyntaxKind.SetAccessor))) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var type = getContextualType(func); + if (type) { + var signature = getContextualSignature(type); + if (signature) { + return getReturnTypeOfSignature(signature); + } + } + } + return undefined; + } + + function getContextualTypeForArgument(node: Expression): Type { + var callExpression = node.parent; + var argIndex = indexOf(callExpression.arguments, node); + if (argIndex >= 0) { + var signature = getResolvedSignature(callExpression); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + + function getContextualTypeForBinaryOperand(node: Expression): Type { + var binaryExpression = node.parent; + var operator = binaryExpression.operator; + if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { + if (node === binaryExpression.right) { + return getTypeOfExpression(binaryExpression.left); + } + } + else if (operator === SyntaxKind.BarBarToken) { + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = getTypeOfExpression(binaryExpression.left); + } + return type; + } + return undefined; + } + + function getContextualTypeForPropertyExpression(node: Expression): Type { + var declaration = node.parent; + var objectLiteral = declaration.parent; + var type = getContextualType(objectLiteral); + var name = declaration.name.text; + if (type && name) { + var prop = getPropertyOfType(type, name); + if (prop) { + return getTypeOfSymbol(prop); + } + return isNumericName(name) && getIndexTypeOfType(type, IndexKind.Number) || getIndexTypeOfType(type, IndexKind.String); + } + return undefined; + } + + function getContextualTypeForElementExpression(node: Expression): Type { + var arrayLiteral = node.parent; + var type = getContextualType(arrayLiteral); + return type ? getIndexTypeOfType(type, IndexKind.Number) : undefined; + } + + function getContextualTypeForConditionalOperand(node: Expression): Type { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + + function getContextualType(node: Expression): Type { + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case SyntaxKind.VariableDeclaration: + case SyntaxKind.Parameter: + case SyntaxKind.Property: + return getContextualTypeForInitializerExpression(node); + case SyntaxKind.ArrowFunction: + case SyntaxKind.ReturnStatement: + return getContextualTypeForReturnExpression(node); + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + return getContextualTypeForArgument(node); + case SyntaxKind.TypeAssertion: + return getTypeFromTypeNode((parent).type); + case SyntaxKind.BinaryExpression: + return getContextualTypeForBinaryOperand(node); + case SyntaxKind.PropertyAssignment: + return getContextualTypeForPropertyExpression(node); + case SyntaxKind.ArrayLiteral: + return getContextualTypeForElementExpression(node); + case SyntaxKind.ConditionalExpression: + return getContextualTypeForConditionalOperand(node); + } + return undefined; + } + // Presence of a contextual type mapper indicates inferential typing, except the identityMapper object is // used as a special marker for other purposes. function isInferentialContext(mapper: TypeMapper) { return mapper && mapper !== identityMapper; } - function checkArrayLiteral(node: ArrayLiteral, contextualType?: Type, contextualMapper?: TypeMapper): Type { - var contextualElementType = contextualType && getIndexTypeOfType(contextualType, IndexKind.Number); + function checkArrayLiteral(node: ArrayLiteral, contextualMapper?: TypeMapper): Type { var elementTypes: Type[] = []; forEach(node.elements, element => { if (element.kind !== SyntaxKind.OmittedExpression) { - var type = checkExpression(element, contextualElementType, contextualMapper); + var type = checkExpression(element, contextualMapper); if (!contains(elementTypes, type)) elementTypes.push(type); } }); - var elementType = getBestCommonType(elementTypes, isInferentialContext(contextualMapper) ? undefined : contextualElementType, true); + var contextualType = isInferentialContext(contextualMapper) ? undefined : getContextualType(node); + var contextualElementType = contextualType && getIndexTypeOfType(contextualType, IndexKind.Number); + var elementType = getBestCommonType(elementTypes, contextualElementType, true); if (!elementType) elementType = elementTypes.length ? emptyObjectType : undefinedType; return createArrayType(elementType); } @@ -3458,22 +3603,16 @@ module ts { return !isNaN(name); } - function getContextualTypeForProperty(type: Type, name: string) { - var prop = getPropertyOfType(type, name); - if (prop) return getTypeOfSymbol(prop); - return isNumericName(name) && getIndexTypeOfType(type, IndexKind.Number) || getIndexTypeOfType(type, IndexKind.String); - } - - function checkObjectLiteral(node: ObjectLiteral, contextualType?: Type, contextualMapper?: TypeMapper): Type { + function checkObjectLiteral(node: ObjectLiteral, contextualMapper?: TypeMapper): Type { var members = node.symbol.members; var properties: SymbolTable = {}; + var contextualType = getContextualType(node); for (var id in members) { if (hasProperty(members, id)) { var member = members[id]; if (member.flags & SymbolFlags.Property) { - var contextualPropType = contextualType && getContextualTypeForProperty(contextualType, member.name); - var type = checkExpression((member.declarations[0]).initializer, contextualPropType, contextualMapper); + var type = checkExpression((member.declarations[0]).initializer, contextualMapper); var prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, member.name); prop.declarations = member.declarations; prop.parent = member.parent; @@ -3500,11 +3639,11 @@ module ts { properties[member.name] = member; } } - var stringIndexType = getIndexType(properties, IndexKind.String); - var numberIndexType = getIndexType(properties, IndexKind.Number); + var stringIndexType = getIndexType(IndexKind.String); + var numberIndexType = getIndexType(IndexKind.Number); return createAnonymousType(node.symbol, properties, emptyArray, emptyArray, stringIndexType, numberIndexType); - function getIndexType(properties: SymbolTable, kind: IndexKind) { + function getIndexType(kind: IndexKind) { if (contextualType) { var indexType = getIndexTypeOfType(contextualType, kind); if (indexType) { @@ -3517,7 +3656,6 @@ module ts { } } } - return getBestCommonType(propTypes, isInferentialContext(contextualMapper) ? undefined : indexType); } } @@ -3632,14 +3770,16 @@ module ts { return unknownType; } - function checkUntypedCall(node: CallExpression): Type { - forEach(node.arguments, argument => { checkExpression(argument); }); - return anyType; + function resolveUntypedCall(node: CallExpression): Signature { + forEach(node.arguments, argument => { + checkExpression(argument); + }); + return anySignature; } - function checkErrorCall(node: CallExpression): Type { - checkUntypedCall(node); - return unknownType; + function resolveErrorCall(node: CallExpression): Signature { + resolveUntypedCall(node); + return unknownSignature; } function isCandidateSignature(node: CallExpression, signature: Signature) { @@ -3698,7 +3838,7 @@ module ts { // Inferentially type an expression by a contextual parameter type (section 4.12.2 in TypeScript spec) function inferentiallyTypeExpession(expr: Expression, contextualType: Type, contextualMapper: TypeMapper): Type { - var type = checkExpression(expr, contextualType, contextualMapper); + var type = checkExpressionWithContextualType(expr, contextualType, contextualMapper); var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { var contextualSignature = getSingleCallSignature(contextualType); @@ -3755,7 +3895,7 @@ module ts { // String literals get string literal types unless we're reporting errors var argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors ? getStringLiteralType(arg) : - checkExpression(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); // Use argument expression as error location when reporting errors var isValidArgument = checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, @@ -3768,12 +3908,12 @@ module ts { return true; } - function checkCall(node: CallExpression, signatures: Signature[]): Type { + function resolveCall(node: CallExpression, signatures: Signature[]): Signature { forEach(node.typeArguments, checkSourceElement); var candidates = collectCandidates(node, signatures); if (!candidates.length) { error(node, Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); - return checkErrorCall(node); + return resolveErrorCall(node); } var args = node.arguments || emptyArray; var excludeArgument: boolean[]; @@ -3799,7 +3939,7 @@ module ts { } var index = excludeArgument ? indexOf(excludeArgument, true) : -1; if (index < 0) { - return getReturnTypeOfSignature(candidate); + return candidate; } excludeArgument[index] = false; } @@ -3812,35 +3952,29 @@ module ts { // No signatures were applicable. Now report errors based on the last applicable signature with // no arguments excluded from assignability checks. checkApplicableSignature(node, candidate, relation, undefined, /*reportErrors*/ true); - return checkErrorCall(node); + return resolveErrorCall(node); } - function checkCallExpression(node: CallExpression): Type { + function resolveCallExpression(node: CallExpression): Signature { if (node.func.kind === SyntaxKind.SuperKeyword) { var superType = checkSuperExpression(node.func, true); if (superType !== unknownType) { - checkCall(node, getSignaturesOfType(superType, SignatureKind.Construct)); + return resolveCall(node, getSignaturesOfType(superType, SignatureKind.Construct)); } - else { - checkUntypedCall(node); - } - - // TS 1.0 spec: 4.8.1 - // The type of a super call expression is Void. - return voidType; + return resolveUntypedCall(node); } var funcType = checkExpression(node.func); if (funcType === unknownType) { // Another error has already been reported - return checkErrorCall(node); + return resolveErrorCall(node); } var apparentType = getApparentType(funcType) if (apparentType === unknownType) { // handler cases when funcType is type parameter with invalid constraint // Another error was already reported - return checkErrorCall(node); + return resolveErrorCall(node); } // Technically, this signatures list may be incomplete. We are taking the apparent type, @@ -3859,7 +3993,7 @@ module ts { if (node.typeArguments) { error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } - return checkUntypedCall(node); + return resolveUntypedCall(node); } // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. // TypeScript employs overload resolution in typed function calls in order to support functions @@ -3871,16 +4005,16 @@ module ts { else { error(node, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); } - return checkErrorCall(node); + return resolveErrorCall(node); } - return checkCall(node, callSignatures); + return resolveCall(node, callSignatures); } - function checkNewExpression(node: NewExpression): Type { + function resolveNewExpression(node: NewExpression): Signature { var expressionType = checkExpression(node.func); if (expressionType === unknownType) { // Another error has already been reported - return checkErrorCall(node); + return resolveErrorCall(node); } // TS 1.0 spec: 4.11 // If ConstructExpr is of type Any, Args can be any argument @@ -3890,7 +4024,7 @@ module ts { error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } - return checkUntypedCall(node); + return resolveUntypedCall(node); } // If ConstructExpr's apparent type(section 3.8.1) is an object type with one or @@ -3902,7 +4036,7 @@ module ts { if (expressionType === unknownType) { // handler cases when original expressionType is a type parameter with invalid constraint // another error has already been reported - return checkErrorCall(node); + return resolveErrorCall(node); } // Technically, this signatures list may be incomplete. We are taking the apparent type, @@ -3911,7 +4045,7 @@ module ts { // that the user will not add any. var constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); if (constructSignatures.length) { - return checkCall(node, constructSignatures); + return resolveCall(node, constructSignatures); } // If ConstructExpr's apparent type is an object type with no construct signatures but @@ -3920,31 +4054,52 @@ module ts { // operation is Any. var callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); if (callSignatures.length) { - var type = checkCall(node, callSignatures); - - if (type !== voidType) { + var signature = resolveCall(node, callSignatures); + if (getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } - - // Since we found no constructor signature, we (implicitly) return any. - if (program.getCompilerOptions().noImplicitAny) { - error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); - } - - return anyType; + return signature; } error(node, Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); - return checkErrorCall(node); + return resolveErrorCall(node); + } + + function getResolvedSignature(node: CallExpression): Signature { + var links = getNodeLinks(node); + if (!links.resolvedSignature) { + links.resolvedSignature = anySignature; + links.resolvedSignature = node.kind === SyntaxKind.CallExpression ? resolveCallExpression(node) : resolveNewExpression(node); + } + return links.resolvedSignature; + } + + function checkCallExpression(node: CallExpression): Type { + var signature = getResolvedSignature(node); + if (node.func.kind === SyntaxKind.SuperKeyword) { + return voidType; + } + if (node.kind === SyntaxKind.NewExpression) { + var declaration = signature.declaration; + if (declaration && (declaration.kind !== SyntaxKind.Constructor && declaration.kind !== SyntaxKind.ConstructSignature)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any + if (program.getCompilerOptions().noImplicitAny) { + error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + return getReturnTypeOfSignature(signature); } function checkTypeAssertion(node: TypeAssertion): Type { + var exprType = checkExpression(node.operand); var targetType = getTypeFromTypeNode(node.type); - if (targetType === unknownType) return unknownType; - var exprType = checkExpression(node.operand, targetType); - var widenedType = getWidenedType(exprType); - if (!(isTypeAssignableTo(exprType, targetType) || isTypeAssignableTo(targetType, widenedType))) { - checkTypeAssignableTo(targetType, widenedType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); + if (targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!(isTypeAssignableTo(exprType, targetType) || isTypeAssignableTo(targetType, widenedType))) { + checkTypeAssignableTo(targetType, widenedType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other_Colon, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); + } } return targetType; } @@ -3967,6 +4122,29 @@ module ts { pos < signature.parameters.length ? getTypeOfSymbol(signature.parameters[pos]) : anyType; } + function assignContextualTypes(node: FunctionExpression, contextualMapper?: TypeMapper) { + var links = getNodeLinks(node); + if (!(links.flags & NodeCheckFlags.ContextAssigned)) { + var contextualSignature = getContextualSignature(getContextualType(node)); + if (!(links.flags & NodeCheckFlags.ContextAssigned)) { + links.flags |= NodeCheckFlags.ContextAssigned; + if (contextualSignature) { + var signature = getSignaturesOfType(getTypeOfSymbol(node.symbol), SignatureKind.Call)[0]; + if (!node.typeParameters && !forEach(node.parameters, p => p.type)) { + assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); + } + if (!node.type) { + signature.resolvedReturnType = resolvingType; + var returnType = getReturnTypeFromBody(node, contextualMapper); + if (signature.resolvedReturnType === resolvingType) { + signature.resolvedReturnType = returnType; + } + } + } + } + } + } + function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); for (var i = 0; i < len; i++) { @@ -3985,9 +4163,9 @@ module ts { } } - function getReturnTypeFromBody(func: FunctionDeclaration, contextualType?: Type, contextualMapper?: TypeMapper): Type { + function getReturnTypeFromBody(func: FunctionDeclaration, contextualMapper?: TypeMapper): Type { if (func.body.kind !== SyntaxKind.FunctionBlock) { - var unwidenedType = checkAndMarkExpression(func.body, contextualType, contextualMapper); + var unwidenedType = checkAndMarkExpression(func.body, contextualMapper); var widenedType = getWidenedType(unwidenedType); if (program.getCompilerOptions().noImplicitAny && widenedType !== unwidenedType && getInnermostTypeOfNestedArrayTypes(widenedType) === anyType) { @@ -3998,7 +4176,7 @@ module ts { } // Aggregate the types of expressions within all the return statements. - var types = checkAndAggregateReturnExpressionTypes(func.body, contextualType, contextualMapper); + var types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); // Try to return the best common type if we have any return expressions. if (types.length > 0) { @@ -4061,13 +4239,13 @@ module ts { } /// Returns a set of types relating to every return expression relating to a function block. - function checkAndAggregateReturnExpressionTypes(body: Block, contextualType?: Type, contextualMapper?: TypeMapper): Type[] { + function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper?: TypeMapper): Type[] { var aggregatedTypes: Type[] = []; forEachReturnStatement(body, returnStatement => { var expr = returnStatement.expression; if (expr) { - var type = checkAndMarkExpression(expr, contextualType, contextualMapper); + var type = checkAndMarkExpression(expr, contextualMapper); if (!contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } @@ -4120,42 +4298,26 @@ module ts { error(func.type, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } - function checkFunctionExpression(node: FunctionExpression, contextualType?: Type, contextualMapper?: TypeMapper): Type { + function checkFunctionExpression(node: FunctionExpression, contextualMapper?: TypeMapper): Type { // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper) { return anyFunctionType; } - var type = getTypeOfSymbol(node.symbol); var links = getNodeLinks(node); - if (!(links.flags & NodeCheckFlags.TypeChecked)) { - var signature = getSignaturesOfType(type, SignatureKind.Call)[0]; - var contextualSignature = getContextualSignature(contextualType); - if (contextualSignature) { - if (!node.typeParameters && !forEach(node.parameters, p => p.type)) { - assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); - } - if (!node.type) { - signature.resolvedReturnType = resolvingType; - var returnType = getReturnTypeFromBody(node, getReturnTypeOfSignature(contextualSignature), contextualMapper); - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = returnType; - } - } - else { - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); - } - } + assignContextualTypes(node, contextualMapper); checkSignatureDeclaration(node); + if (node.type) { + checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); + } if (node.body.kind === SyntaxKind.FunctionBlock) { checkSourceElement(node.body); } else { - var returnType = getReturnTypeOfSignature(signature); + var exprType = checkExpression(node.body); if (node.type) { - // Use default error messages for this check - checkTypeAssignableTo(checkExpression(node.body, returnType), returnType, node.body, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined); + checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined, undefined); } } links.flags |= NodeCheckFlags.TypeChecked; @@ -4285,13 +4447,10 @@ module ts { return booleanType; } - function checkBinaryExpression(node: BinaryExpression, contextualType?: Type, contextualMapper?: TypeMapper) { + function checkBinaryExpression(node: BinaryExpression, contextualMapper?: TypeMapper) { var operator = node.operator; - var leftContextualType = operator === SyntaxKind.BarBarToken ? contextualType : undefined - var leftType = checkExpression(node.left, leftContextualType, contextualMapper); - var rightContextualType = operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment ? leftType : - operator === SyntaxKind.BarBarToken ? contextualType || leftType : undefined; - var rightType = checkExpression(node.right, rightContextualType, contextualMapper); + var leftType = checkExpression(node.left, contextualMapper); + var rightType = checkExpression(node.right, contextualMapper); switch (operator) { case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: @@ -4383,7 +4542,7 @@ module ts { case SyntaxKind.AmpersandAmpersandToken: return rightType; case SyntaxKind.BarBarToken: - return getBestCommonType([leftType, rightType], isInferentialContext(contextualMapper) ? undefined : contextualType); + return getBestCommonType([leftType, rightType], isInferentialContext(contextualMapper) ? undefined : getContextualType(node)); case SyntaxKind.EqualsToken: checkAssignmentOperator(rightType); return rightType; @@ -4413,40 +4572,45 @@ module ts { } } - function checkConditionalExpression(node: ConditionalExpression, contextualType?: Type, contextualMapper?: TypeMapper): Type { + function checkConditionalExpression(node: ConditionalExpression, contextualMapper?: TypeMapper): Type { checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, contextualType, contextualMapper); - var type2 = checkExpression(node.whenFalse, contextualType, contextualMapper); - var resultType = getBestCommonType([type1, type2], isInferentialContext(contextualMapper) ? undefined : contextualType, true); + var type1 = checkExpression(node.whenTrue, contextualMapper); + var type2 = checkExpression(node.whenFalse, contextualMapper); + var contextualType = isInferentialContext(contextualMapper) ? undefined : getContextualType(node); + var resultType = getBestCommonType([type1, type2], contextualType, true); if (!resultType) { - - if (contextualType && !isInferentialContext(contextualMapper)) { + if (contextualType) { error(node, Diagnostics.No_best_common_type_exists_between_0_1_and_2, typeToString(contextualType), typeToString(type1), typeToString(type2)); } else { error(node, Diagnostics.No_best_common_type_exists_between_0_and_1, typeToString(type1), typeToString(type2)); } - resultType = emptyObjectType; } return resultType; } - function checkAndMarkExpression(node: Expression, contextualType?: Type, contextualMapper?: TypeMapper): Type { - var result = checkExpression(node, contextualType, contextualMapper); + function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper?: TypeMapper): Type { + node.contextualType = contextualType; + var result = checkExpression(node, contextualMapper); + node.contextualType = undefined; + return result; + } + + function checkAndMarkExpression(node: Expression, contextualMapper?: TypeMapper): Type { + var result = checkExpression(node, contextualMapper); getNodeLinks(node).flags |= NodeCheckFlags.TypeChecked; return result; } - // Checks an expression and returns its type. The contextualType parameter provides a contextual type for - // the check or is undefined if there is no contextual type. The contextualMapper parameter serves two - // purposes: When contextualMapper is not undefined and not equal to the identityMapper function object - // it provides a type mapper to use during inferential typing (the contextual type is then a generic type). - // When contextualMapper is equal to the identityMapper function object, it serves as an indicator that all - // contained function and arrow expressions should be considered to have the wildcard function type; this - // form of type check is used during overload resolution to exclude contextually typed function and arrow - // expressions in the initial phase. - function checkExpression(node: Expression, contextualType?: Type, contextualMapper?: TypeMapper): Type { + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.12.2 in spec) and provides the type mapper to use in + // conjuction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node: Expression, contextualMapper?: TypeMapper): Type { switch (node.kind) { case SyntaxKind.Identifier: return checkIdentifier(node); @@ -4468,32 +4632,31 @@ module ts { case SyntaxKind.QualifiedName: return checkPropertyAccess(node); case SyntaxKind.ArrayLiteral: - return checkArrayLiteral(node, contextualType, contextualMapper); + return checkArrayLiteral(node, contextualMapper); case SyntaxKind.ObjectLiteral: - return checkObjectLiteral(node, contextualType, contextualMapper); + return checkObjectLiteral(node, contextualMapper); case SyntaxKind.PropertyAccess: return checkPropertyAccess(node); case SyntaxKind.IndexedAccess: return checkIndexedAccess(node); case SyntaxKind.CallExpression: - return checkCallExpression(node); case SyntaxKind.NewExpression: - return checkNewExpression(node); + return checkCallExpression(node); case SyntaxKind.TypeAssertion: return checkTypeAssertion(node); case SyntaxKind.ParenExpression: return checkExpression((node).expression); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return checkFunctionExpression(node, contextualType, contextualMapper); + return checkFunctionExpression(node, contextualMapper); case SyntaxKind.PrefixOperator: return checkPrefixExpression(node); case SyntaxKind.PostfixOperator: return checkPostfixExpression(node); case SyntaxKind.BinaryExpression: - return checkBinaryExpression(node, contextualType, contextualMapper); + return checkBinaryExpression(node, contextualMapper); case SyntaxKind.ConditionalExpression: - return checkConditionalExpression(node, contextualType, contextualMapper); + return checkConditionalExpression(node, contextualMapper); } return unknownType; } @@ -5170,7 +5333,7 @@ module ts { if (node.initializer) { if (!(getNodeLinks(node.initializer).flags & NodeCheckFlags.TypeChecked)) { // Use default messages - checkTypeAssignableTo(checkAndMarkExpression(node.initializer, type), type, node, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined); + checkTypeAssignableTo(checkAndMarkExpression(node.initializer), type, node, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined); } } @@ -5291,12 +5454,12 @@ module ts { func.type || (func.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(func.symbol, SyntaxKind.SetAccessor))); if (checkAssignability) { - checkTypeAssignableTo(checkExpression(node.expression, returnType), returnType, node.expression, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined); + checkTypeAssignableTo(checkExpression(node.expression), returnType, node.expression, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined); } else if (func.kind == SyntaxKind.Constructor) { // constructor doesn't have explicit return type annontation and yet its return type is known - declaring type // handle constructors and issue specialized error message for them. - if (!isTypeAssignableTo(checkExpression(node.expression, returnType), returnType)) { + if (!isTypeAssignableTo(checkExpression(node.expression), returnType)) { error(node.expression, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 9d15e453334..5f9f02e5475 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -319,7 +319,9 @@ module ts { text: string; } - export interface Expression extends Node { } + export interface Expression extends Node { + contextualType?: Type; + } export interface UnaryExpression extends Expression { operator: SyntaxKind; @@ -730,17 +732,18 @@ module ts { } export enum NodeCheckFlags { - TypeChecked = 0x00000001, // Node has been type checked - LexicalThis = 0x00000002, // Lexical 'this' reference - CaptureThis = 0x00000004, // Lexical 'this' used in body - EmitExtends = 0x00000008, // Emit __extends - SuperInstance = 0x00000010, // Instance 'super' reference - SuperStatic = 0x00000020, // Static 'super' reference + TypeChecked = 0x00000001, // Node has been type checked + LexicalThis = 0x00000002, // Lexical 'this' reference + CaptureThis = 0x00000004, // Lexical 'this' used in body + EmitExtends = 0x00000008, // Emit __extends + SuperInstance = 0x00000010, // Instance 'super' reference + SuperStatic = 0x00000020, // Static 'super' reference + ContextAssigned = 0x00000040, // Contextual types have been assigned } export interface NodeLinks { resolvedType?: Type; // Cached type of type node - resolvedSignature?: Signature; // Cached signature of signature node + resolvedSignature?: Signature; // Cached signature of signature node or call expression resolvedSymbol?: Symbol; // Cached name resolution result flags?: NodeCheckFlags; // Set of flags specific to Node enumMemberValue?: number; // Constant value of enum member diff --git a/tests/baselines/reference/functionImplementationErrors.errors.txt b/tests/baselines/reference/functionImplementationErrors.errors.txt index 3da56bd6818..5c2d678840e 100644 --- a/tests/baselines/reference/functionImplementationErrors.errors.txt +++ b/tests/baselines/reference/functionImplementationErrors.errors.txt @@ -1,4 +1,4 @@ -==== tests/cases/conformance/functions/functionImplementationErrors.ts (7 errors) ==== +==== tests/cases/conformance/functions/functionImplementationErrors.ts (8 errors) ==== // FunctionExpression with no return type annotation with multiple return statements with unrelated types var f1 = function () { ~~~~~~~~~~~~~ @@ -68,6 +68,8 @@ // FunctionExpression with non -void return type annotation with a throw, no return, and other code // Should be error but isn't undefined === function (): number { + ~~~~~~ +!!! A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement. throw undefined; var x = 4; }; diff --git a/tests/baselines/reference/parserCastVersusArrowFunction1.errors.txt b/tests/baselines/reference/parserCastVersusArrowFunction1.errors.txt index b9ae061ed69..2686c59da36 100644 --- a/tests/baselines/reference/parserCastVersusArrowFunction1.errors.txt +++ b/tests/baselines/reference/parserCastVersusArrowFunction1.errors.txt @@ -1,8 +1,10 @@ -==== tests/cases/conformance/parser/ecmascript5/Generics/parserCastVersusArrowFunction1.ts (7 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Generics/parserCastVersusArrowFunction1.ts (13 errors) ==== var v = () => 1; var v = a; ~ !!! Cannot find name 'T'. + ~ +!!! Cannot find name 'a'. var v = (a) => 1; ~ @@ -17,9 +19,19 @@ var v = (a); ~ !!! Cannot find name 'T'. + ~ +!!! Cannot find name 'a'. var v = (a, b); ~ !!! Cannot find name 'T'. + ~ +!!! Cannot find name 'a'. + ~ +!!! Cannot find name 'b'. var v = (a = 1, b = 2); ~ -!!! Cannot find name 'T'. \ No newline at end of file +!!! Cannot find name 'T'. + ~ +!!! Cannot find name 'a'. + ~ +!!! Cannot find name 'b'. \ No newline at end of file diff --git a/tests/baselines/reference/parserRealSource8.errors.txt b/tests/baselines/reference/parserRealSource8.errors.txt index 42dca350919..d4f6467fc10 100644 --- a/tests/baselines/reference/parserRealSource8.errors.txt +++ b/tests/baselines/reference/parserRealSource8.errors.txt @@ -1,4 +1,4 @@ -==== tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts (133 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/parserRealSource8.ts (134 errors) ==== // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. @@ -383,6 +383,8 @@ outerFnc.type.members = ((container).type.memberScope).valueMembers; ~~~~~~~~~~~~~~~~~~ !!! Cannot find name 'SymbolScopeBuilder'. + ~~~~~~~~~~ +!!! Cannot find name 'TypeSymbol'. } funcScope = context.scopeChain.fnc.type.memberScope; outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; diff --git a/tests/baselines/reference/parserVariableDeclaration3.errors.txt b/tests/baselines/reference/parserVariableDeclaration3.errors.txt index b2dfcb1c4e9..8d10b4ba5de 100644 --- a/tests/baselines/reference/parserVariableDeclaration3.errors.txt +++ b/tests/baselines/reference/parserVariableDeclaration3.errors.txt @@ -1,4 +1,4 @@ -==== tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts (3 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts (4 errors) ==== function runTests() { var outfile = new Harness.Compiler.WriterAggregator() ~~~~~~~ @@ -8,6 +8,8 @@ !!! Cannot find name 'Harness'. , compiler = new TypeScript.TypeScriptCompiler(outerr) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! Cannot find name 'TypeScript'. + ~~~~~~~~~~ !!! Cannot find name 'TypeScript'. , code; } \ No newline at end of file From 617910b3d4b44e42432705e868e4d7060e882e9d Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 31 Jul 2014 13:27:12 -0700 Subject: [PATCH 02/29] Support the '--watch' compiler flag. --- src/compiler/commandLineParser.ts | 16 +- src/compiler/core.ts | 6 +- .../diagnosticInformationMap.generated.ts | 3 + src/compiler/diagnosticMessages.json | 16 +- src/compiler/parser.ts | 16 +- src/compiler/sys.ts | 18 ++- src/compiler/tc.ts | 137 +++++++++++++++--- src/compiler/types.ts | 1 + 8 files changed, 177 insertions(+), 36 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 8abd3c00d9e..7a3e27b8a02 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -11,9 +11,10 @@ module ts { "o": "out", "t": "target", "v": "version", + "w": "watch", }; - var options: CommandLineOption[] = [ + var optionDeclarations: CommandLineOption[] = [ { name: "charset", type: "string" }, { name: "codepage", type: "number" }, { name: "declaration", type: "boolean" }, @@ -32,14 +33,15 @@ module ts { { name: "sourceMap", type: "boolean" }, { name: "sourceRoot", type: "string" }, { name: "target", type: { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5 }, error: Diagnostics.Argument_for_target_option_must_be_es3_or_es5 }, - { name: "version", type: "boolean" } + { name: "version", type: "boolean" }, + { name: "watch", type: "boolean" }, ]; // Map command line switches to compiler options' property descriptors. Keys must be lower case spellings of command line switches. // The 'name' property specifies the property name in the CompilerOptions type. The 'type' property specifies the type of the option. - var optionDeclarations: Map = {}; - forEach(options, option => { - optionDeclarations[option.name.toLowerCase()] = option; + var optionMap: Map = {}; + forEach(optionDeclarations, option => { + optionMap[option.name.toLowerCase()] = option; }); export function parseCommandLine(commandLine: string[]): ParsedCommandLine { @@ -73,8 +75,8 @@ module ts { s = shortOptionNames[s]; } - if (hasProperty(optionDeclarations, s)) { - var opt = optionDeclarations[s]; + if (hasProperty(optionMap, s)) { + var opt = optionMap[s]; // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 8e59408f151..1171191f8dc 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -114,7 +114,11 @@ module ts { } export function isEmpty(map: Map) { - for (var id in map) return false; + for (var id in map) { + if (hasProperty(map, id)) { + return false; + } + } return true; } diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 11342e81eeb..a3b85cfb013 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -209,6 +209,7 @@ module ts { Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 4019, category: DiagnosticCategory.NoPrefix, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 4024, category: DiagnosticCategory.Error, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, Named_properties_0_of_types_1_and_2_are_not_identical: { code: 4032, category: DiagnosticCategory.NoPrefix, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." }, + The_current_host_does_not_support_the_0_option: { code: 5001, category: DiagnosticCategory.Error, key: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: DiagnosticCategory.Error, key: "Cannot find the common subdirectory path for the input files." }, Cannot_read_file_0_Colon_1: { code: 5012, category: DiagnosticCategory.Error, key: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: DiagnosticCategory.NoPrefix, key: "Unsupported file encoding." }, @@ -216,6 +217,8 @@ module ts { Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: DiagnosticCategory.Error, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: DiagnosticCategory.Error, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, Version_0: { code: 6029, category: DiagnosticCategory.Message, key: "Version {0}" }, + File_Changed_Compiling: { code: 6032, category: DiagnosticCategory.Message, key: "File Changed. Compiling." }, + Compile_complete_Listening_for_changed_files: { code: 6042, category: DiagnosticCategory.Message, key: "Compile complete. Listening for changed files." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 69b06cbcdf0..9ace46f4202 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -830,6 +830,10 @@ "category": "NoPrefix", "code": 4032 }, + "The current host does not support the '{0}' option.": { + "category": "Error", + "code": 5001 + }, "Cannot find the common subdirectory path for the input files.": { "category": "Error", "code": 5009 @@ -854,12 +858,18 @@ "category": "Error", "code": 5039 }, - "Version {0}": { "category": "Message", "code": 6029 - }, - + }, + "File Changed. Compiling.": { + "category": "Message", + "code": 6032 + }, + "Compile complete. Listening for changed files.": { + "category": "Message", + "code": 6042 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", "code": 7005 diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index d3e40a21780..c0ddd75883c 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -3514,7 +3514,6 @@ module ts { } export function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program { - var program: Program; var files: SourceFile[] = []; var filesByName: Map = {}; @@ -3523,7 +3522,9 @@ module ts { var commonSourceDirectory: string; forEach(rootNames, name => processRootFile(name, false)); - if (!seenNoDefaultLib) processRootFile(host.getDefaultLibFilename(), true); + if (!seenNoDefaultLib) { + processRootFile(host.getDefaultLibFilename(), true); + } verifyCompilerOptions(); errors.sort(compareDiagnostics); program = { @@ -3614,7 +3615,7 @@ module ts { function processReferencedFiles(file: SourceFile, basePath: string) { forEach(file.referencedFiles, ref => { - processSourceFile(normalizePath(combinePaths(basePath, ref.filename)), false, file, ref.pos, ref.end); + processSourceFile(normalizePath(combinePaths(basePath, ref.filename)), /* isDefaultLib */ false, file, ref.pos, ref.end); }); } @@ -3627,9 +3628,14 @@ module ts { var searchPath = basePath; while (true) { var searchName = normalizePath(combinePaths(searchPath, moduleName)); - if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) break; + if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { + break; + } + var parentPath = getDirectoryPath(searchPath); - if (parentPath === searchPath) break; + if (parentPath === searchPath) { + break; + } searchPath = parentPath; } } diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 51fe9214e71..ce31988b504 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -5,9 +5,9 @@ interface System { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; - writeErr(s: string): void; readFile(fileName: string, encoding?: string): string; writeFile(fileName: string, data: string): void; + watchFile?(fileName: string, callback: (fileName: string) => void): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; @@ -18,6 +18,10 @@ interface System { exit(exitCode?: number): void; } +interface FileWatcher { + close(): void; +} + declare var require: any; declare var module: any; declare var process: any; @@ -187,6 +191,18 @@ var sys: System = (function () { }, readFile: readFile, writeFile: writeFile, + watchFile: (fileName, callback) => { + // watchFile polls a file every 250ms, picking up file notifications. + _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged); + + return { + close() { _fs.unwatchFile(fileName, fileChanged); } + }; + + function fileChanged() { + callback(fileName); + }; + }, resolvePath: function (path: string): string { return _path.resolve(path); }, diff --git a/src/compiler/tc.ts b/src/compiler/tc.ts index b363ab4d39f..fa922138d17 100644 --- a/src/compiler/tc.ts +++ b/src/compiler/tc.ts @@ -81,10 +81,10 @@ module ts { function reportDiagnostic(error: Diagnostic) { if (error.file) { var loc = error.file.getLineAndCharacterFromPosition(error.start); - sys.writeErr(error.file.filename + "(" + loc.line + "," + loc.character + "): " + error.messageText + sys.newLine); + sys.write(error.file.filename + "(" + loc.line + "," + loc.character + "): " + error.messageText + sys.newLine); } else { - sys.writeErr(error.messageText + sys.newLine); + sys.write(error.messageText + sys.newLine); } } @@ -110,7 +110,7 @@ module ts { } function reportStatisticalValue(name: string, value: string) { - sys.writeErr(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine); + sys.write(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine); } function reportCountStatistic(name: string, count: number) { @@ -178,33 +178,130 @@ module ts { }; } - export function executeCommandLine(args: string[]): number { - var cmds = parseCommandLine(args); + export function executeCommandLine(args: string[]): void { + var commandLine = parseCommandLine(args); - if (cmds.options.locale) { - validateLocaleAndSetLanguage(cmds.options.locale, cmds.errors); + if (commandLine.options.locale) { + validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors); } - if (cmds.filenames.length === 0 && !(cmds.options.help || cmds.options.version)) { - cmds.errors.push(createCompilerDiagnostic(Diagnostics.No_input_files_specified)); + if (commandLine.filenames.length === 0 && !(commandLine.options.help || commandLine.options.version)) { + commandLine.errors.push(createCompilerDiagnostic(Diagnostics.No_input_files_specified)); } - if (cmds.options.version) { + if (commandLine.options.version) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.Version_0, version)); - return 0; + sys.exit(0); } - if (cmds.filenames.length === 0 || cmds.options.help) { + if (commandLine.filenames.length === 0 || commandLine.options.help) { // TODO (drosen): Usage. } - if (cmds.errors.length) { - reportDiagnostics(cmds.errors); - return 1; + if (commandLine.errors.length) { + reportDiagnostics(commandLine.errors); + sys.exit(1); } + var defaultCompilerHost = createCompilerHost(commandLine.options); + + if (commandLine.options.watch) { + if (!sys.watchFile) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); + sys.exit(1); + } + + watchProgram(commandLine, defaultCompilerHost); + } + else { + sys.exit(compile(commandLine, defaultCompilerHost).errors.length > 0 ? 1 : 0); + } + } + + /** + * Compiles the program once, and then watches all given and referenced files for changes. + * Upon detecting a file change, watchProgram will queue up file modification events for the next + * 250ms and then perform a recompilation. The reasoning is that in some cases, an editor can + * save all files at once, and we'd like to just perform a single recompilation. + */ + function watchProgram(commandLine: ParsedCommandLine, compilerHost: CompilerHost): void { + var watchers: Map = {}; + var updatedFiles: Map = {}; + + // Compile the program the first time and watch all given/referenced files. + var program = compile(commandLine, compilerHost).program; + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compile_complete_Listening_for_changed_files)); + addWatchers(program); + return; + + function addWatchers(program: Program) { + forEach(program.getSourceFiles(), f => { + var filename = f.filename; + watchers[filename] = sys.watchFile(filename, fileUpdated); + }); + } + + function removeWatchers(program: Program) { + forEach(program.getSourceFiles(), f => { + var filename = f.filename; + if (hasProperty(watchers, filename)) { + watchers[filename].close(); + } + }); + + watchers = {}; + } + + // Fired off whenever a file is changed. + function fileUpdated(filename: string) { + var firstNotification = isEmpty(updatedFiles); + + updatedFiles[filename] = true; + + // Only start this off when the first file change comes in, + // so that we can batch up all further changes. + if (firstNotification) { + setTimeout(() => { + var changedFiles = updatedFiles; + updatedFiles = {}; + + recompile(changedFiles); + }, 250); + } + } + + function recompile(changedFiles: Map) { + var oldProgram = program; + reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_Changed_Compiling)); + // Remove all the watchers, since we may not be watching every file + // specified since the last recompilation cycle. + removeWatchers(oldProgram); + + // We create a new compiler host for this compilation cycle. + // This new host is effectively the same except that 'getSourceFile' + // will try to reuse the SourceFiles from the last compilation cycle + // so long as they were not modified. + var newCompilerHost = clone(compilerHost); + newCompilerHost.getSourceFile = (fileName, languageVersion, onError) => { + if (!hasProperty(changedFiles, fileName)) { + var sourceFile = oldProgram.getSourceFile(fileName); + if (sourceFile) { + return sourceFile; + } + } + + return compilerHost.getSourceFile(fileName, languageVersion, onError); + }; + + program = compile(commandLine, newCompilerHost).program; + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compile_complete_Listening_for_changed_files)); + addWatchers(program); + } + } + + function compile(commandLine: ParsedCommandLine, compilerHost: CompilerHost) { var parseStart = new Date().getTime(); - var program = createProgram(cmds.filenames, cmds.options, createCompilerHost(cmds.options)); + var program = createProgram(commandLine.filenames, commandLine.options, compilerHost); var bindStart = new Date().getTime(); var errors = program.getDiagnostics(); if (errors.length) { @@ -223,7 +320,7 @@ module ts { } reportDiagnostics(errors); - if (cmds.options.diagnostics) { + if (commandLine.options.diagnostics) { reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); reportCountStatistic("Nodes", checker ? checker.getNodeCount() : 0); @@ -236,8 +333,10 @@ module ts { reportTimeStatistic("Emit time", reportStart - emitStart); reportTimeStatistic("Total time", reportStart - parseStart); } - return errors.length ? 1 : 0; + + return { program: program, errors: errors }; + } } -sys.exit(ts.executeCommandLine(sys.args)); +ts.executeCommandLine(sys.args); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 6b846768c15..316ae5410c0 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -928,6 +928,7 @@ module ts { sourceRoot?: string; target?: ScriptTarget; version?: boolean; + watch?: boolean; [option: string]: any; } From bd97ba443af70f23bf7238eac26e55b3eb168b6f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 31 Jul 2014 15:48:03 -0700 Subject: [PATCH 03/29] Restructuring and cleanup. Changed binder to record catch clause instead of catch variable as symbol declaration. Restructuring of getTypeOfVariableDeclaration and getTypeOfVariableOrParameterOrProperty methods. Restructuring of checkFunctionExpression method. --- src/compiler/binder.ts | 2 +- src/compiler/checker.ts | 247 +++++++++++++++++----------------------- src/compiler/types.ts | 14 +-- 3 files changed, 115 insertions(+), 148 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index ec67b496db6..e0164514de0 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -250,7 +250,7 @@ module ts { function bindCatchVariableDeclaration(node: CatchBlock) { var symbol = createSymbol(SymbolFlags.Variable, node.variable.text || "__missing"); - addDeclarationToSymbol(symbol, node.variable, SymbolFlags.Variable); + addDeclarationToSymbol(symbol, node, SymbolFlags.Variable); var saveParent = parent; parent = node; forEachChild(node, bind); diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fd89c889f9e..ef6dff1414e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -305,7 +305,7 @@ module ts { case SyntaxKind.CatchBlock: var id = (location).variable; if (name === id.text) { - return returnResolvedSymbol((location).variable.symbol); + return returnResolvedSymbol(location.symbol); } break; } @@ -1080,122 +1080,87 @@ module ts { } function getTypeOfVariableDeclaration(declaration: VariableDeclaration): Type { - var type: Type; - - if (declaration.parent.kind === SyntaxKind.CatchBlock || declaration.parent.kind === SyntaxKind.ForInStatement) { - type = anyType; + // A variable declared in a for..in statement is always of type any + if (declaration.parent.kind === SyntaxKind.ForInStatement) { + return anyType; } - else if (declaration.type) { - type = getTypeFromTypeNode(declaration.type); + // Use type from type annotation if one is present + if (declaration.type) { + return getTypeFromTypeNode(declaration.type); } - else { - // TypeScript 1.0 spec (April 2014): - // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - // If neither accessor includes a type annotation, the inferred return type of the get accessor becomes the parameter type of the set accessor. - if (declaration.kind === SyntaxKind.Parameter && declaration.parent.kind === SyntaxKind.SetAccessor) { + if (declaration.kind === SyntaxKind.Parameter) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === SyntaxKind.SetAccessor) { var getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { - //getReturnTypeOfSignature will check both type annotation and return type inferred from body - type = getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); + return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } } - - var unwidenedType: Type; - - if (!type) { - if (declaration.initializer) { - unwidenedType = checkAndMarkExpression(declaration.initializer); - type = getWidenedType(unwidenedType); - } - else if (declaration.flags & NodeFlags.Rest) { - type = createArrayType(anyType); - } - else { - type = anyType; - } - } - - if (program.getCompilerOptions().noImplicitAny && shouldReportNoImplicitAnyOnVariableOrParameterOrProperty(declaration, type, unwidenedType)) { - reportNoImplicitAnyOnVariableOrParameterOrProperty(declaration, type); + // Use contextual parameter type if one is available + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; } } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var unwidenedType = checkAndMarkExpression(declaration.initializer); + var type = getWidenedType(unwidenedType); + return type !== unwidenedType ? checkImplicitAny(type) : type; + } + // Rest parameter defaults to type any[] + if (declaration.flags & NodeFlags.Rest) { + return checkImplicitAny(createArrayType(anyType)); + } + // Other parameters default to type any + return checkImplicitAny(anyType); - return type; - - function shouldReportNoImplicitAnyOnVariableOrParameterOrProperty(declaration: VariableDeclaration, type: Type, unwidenedType: Type): boolean { - // If we attempted to widen, the resulting type has to be a different. - if (type === unwidenedType) { - return false; + function checkImplicitAny(type: Type): Type { + if (!program.getCompilerOptions().noImplicitAny) { + return type; } - // We need to have ended up with 'any', 'any[]', 'any[][]', etc. if (getInnermostTypeOfNestedArrayTypes(type) !== anyType) { - return false; + return type; } - // Ignore privates within ambient contexts; they exist purely for documentative purposes to avoid name clashing. // (e.g. privates within .d.ts files do not expose type information) if (isPrivateWithinAmbient(declaration) || (declaration.kind === SyntaxKind.Parameter && isPrivateWithinAmbient(declaration.parent))) { - return false; + return type; } - - return true; - } - - function reportNoImplicitAnyOnVariableOrParameterOrProperty(declaration: VariableDeclaration, type: Type): void { - var varName = identifierToString(declaration.name); - var typeName = typeToString(type); - switch (declaration.kind) { - case SyntaxKind.VariableDeclaration: - error(declaration, Diagnostics.Variable_0_implicitly_has_an_1_type, varName, typeName) - break; - case SyntaxKind.Property: - error(declaration, Diagnostics.Member_0_implicitly_has_an_1_type, varName, typeName) + var diagnostic = Diagnostics.Member_0_implicitly_has_an_1_type; break; - case SyntaxKind.Parameter: - var funcDeclaration = declaration.parent; - - // If this is a rest parameter, we should have widened specifically to 'any[]'. - if (declaration.flags & NodeFlags.Rest) { - error(declaration, Diagnostics.Rest_parameter_0_implicitly_has_an_any_type, varName) - } - else { - error(declaration, Diagnostics.Parameter_0_implicitly_has_an_1_type, varName, typeName) - } - + var diagnostic = declaration.flags & NodeFlags.Rest ? + Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - default: - Debug.fail("Received a '" + SyntaxKind[declaration.kind] + "', but expected '" + - SyntaxKind[SyntaxKind.VariableDeclaration] + "', '" + - SyntaxKind[SyntaxKind.Property] + "', or '" + - SyntaxKind[SyntaxKind.Parameter] + "'.\r\n"); + var diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } + error(declaration, diagnostic, identifierToString(declaration.name), typeToString(type)); + return type; } - } function getTypeOfVariableOrParameterOrProperty(symbol: Symbol): Type { var links = getSymbolLinks(symbol); if (!links.type) { + // Handle prototype property if (symbol.flags & SymbolFlags.Prototype) { return links.type = getTypeOfPrototypeProperty(symbol); } - var declaration = symbol.valueDeclaration; - if (declaration.kind === SyntaxKind.Parameter && !declaration.type) { - var parent = declaration.parent; - if (parent.kind === SyntaxKind.FunctionExpression || parent.kind === SyntaxKind.ArrowFunction) { - assignContextualTypes(parent); - if (links.type) { - return links.type; - } - } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (declaration.kind === SyntaxKind.CatchBlock) { + return links.type = anyType; } + // Handle variable, parameter or property links.type = resolvingType; - var type = getTypeOfVariableDeclaration(symbol.valueDeclaration); + var type = getTypeOfVariableDeclaration(declaration); if (links.type === resolvingType) { links.type = type; } @@ -1207,7 +1172,7 @@ module ts { } function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode { - return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; + return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } function getAnnotatedAccessorType(accessor: AccessorDeclaration): Type { @@ -3445,10 +3410,24 @@ module ts { } function getTypeOfExpression(node: Expression): Type { - // TODO: Return type cached in NodeLinks + // TODO: Optimize by caching type in NodeLinks? return checkExpression(node); } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter: VariableDeclaration): Type { + var func = parameter.parent; + if (func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction) { + if (isContextSensitiveExpression(func)) { + var signature = getContextualSignature(func); + if (signature) { + return getTypeAtPosition(signature, indexOf(func.parameters, parameter)); + } + } + } + return undefined; + } + function getContextualTypeForInitializerExpression(node: Expression): Type { var declaration = node.parent; if (node === declaration.initializer) { @@ -3456,18 +3435,7 @@ module ts { return getTypeFromTypeNode(declaration.type); } if (declaration.kind === SyntaxKind.Parameter) { - var func = declaration.parent; - if (func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction) { - if (isContextSensitiveExpression(func)) { - var type = getContextualType(func); - if (type) { - var signature = getContextualSignature(type); - if (signature) { - return getTypeAtPosition(signature, indexOf(func.parameters, declaration)); - } - } - } - } + return getContextuallyTypedParameterType(declaration); } } return undefined; @@ -3483,12 +3451,9 @@ module ts { } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature - var type = getContextualType(func); - if (type) { - var signature = getContextualSignature(type); - if (signature) { - return getReturnTypeOfSignature(signature); - } + var signature = getContextualSignature(func); + if (signature) { + return getReturnTypeOfSignature(signature); } } return undefined; @@ -3578,6 +3543,20 @@ module ts { return undefined; } + function getContextualSignature(node: Expression): Signature { + var type = getContextualType(node); + if (type) { + var signatures = getSignaturesOfType(type, SignatureKind.Call); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!signature.typeParameters) { + return signature; + } + } + } + return undefined; + } + // Presence of a contextual type mapper indicates inferential typing, except the identityMapper object is // used as a special marker for other purposes. function isInferentialContext(mapper: TypeMapper) { @@ -4104,47 +4083,12 @@ module ts { return targetType; } - function getContextualSignature(contextualType: Type) { - if (contextualType) { - var signatures = getSignaturesOfType(contextualType, SignatureKind.Call); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!signature.typeParameters) { - return signature; - } - } - } - } - function getTypeAtPosition(signature: Signature, pos: number): Type { return signature.hasRestParameter ? pos < signature.parameters.length - 1 ? getTypeOfSymbol(signature.parameters[pos]) : getRestTypeOfSignature(signature) : pos < signature.parameters.length ? getTypeOfSymbol(signature.parameters[pos]) : anyType; } - function assignContextualTypes(node: FunctionExpression, contextualMapper?: TypeMapper) { - var links = getNodeLinks(node); - if (!(links.flags & NodeCheckFlags.ContextAssigned)) { - var contextualSignature = getContextualSignature(getContextualType(node)); - if (!(links.flags & NodeCheckFlags.ContextAssigned)) { - links.flags |= NodeCheckFlags.ContextAssigned; - if (contextualSignature) { - var signature = getSignaturesOfType(getTypeOfSymbol(node.symbol), SignatureKind.Call)[0]; - if (!node.typeParameters && !forEach(node.parameters, p => p.type)) { - assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); - } - if (!node.type) { - signature.resolvedReturnType = resolvingType; - var returnType = getReturnTypeFromBody(node, contextualMapper); - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = returnType; - } - } - } - } - } - } - function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); for (var i = 0; i < len; i++) { @@ -4303,10 +4247,32 @@ module ts { if (contextualMapper === identityMapper) { return anyFunctionType; } - var type = getTypeOfSymbol(node.symbol); var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + // Check if function expression is contextually typed and assign parameter types if so + if (!(links.flags & NodeCheckFlags.ContextChecked)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & NodeCheckFlags.ContextChecked)) { + links.flags |= NodeCheckFlags.ContextChecked; + if (contextualSignature) { + var signature = getSignaturesOfType(type, SignatureKind.Call)[0]; + if (isContextSensitiveExpression(node)) { + assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); + } + if (!node.type) { + signature.resolvedReturnType = resolvingType; + var returnType = getReturnTypeFromBody(node, contextualMapper); + if (signature.resolvedReturnType === resolvingType) { + signature.resolvedReturnType = returnType; + } + } + } + } + } if (!(links.flags & NodeCheckFlags.TypeChecked)) { - assignContextualTypes(node, contextualMapper); checkSignatureDeclaration(node); if (node.type) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); @@ -4591,9 +4557,10 @@ module ts { } function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper?: TypeMapper): Type { + var saveContextualType = node.contextualType; node.contextualType = contextualType; var result = checkExpression(node, contextualMapper); - node.contextualType = undefined; + node.contextualType = saveContextualType; return result; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 5f9f02e5475..78f462230f3 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -732,13 +732,13 @@ module ts { } export enum NodeCheckFlags { - TypeChecked = 0x00000001, // Node has been type checked - LexicalThis = 0x00000002, // Lexical 'this' reference - CaptureThis = 0x00000004, // Lexical 'this' used in body - EmitExtends = 0x00000008, // Emit __extends - SuperInstance = 0x00000010, // Instance 'super' reference - SuperStatic = 0x00000020, // Static 'super' reference - ContextAssigned = 0x00000040, // Contextual types have been assigned + TypeChecked = 0x00000001, // Node has been type checked + LexicalThis = 0x00000002, // Lexical 'this' reference + CaptureThis = 0x00000004, // Lexical 'this' used in body + EmitExtends = 0x00000008, // Emit __extends + SuperInstance = 0x00000010, // Instance 'super' reference + SuperStatic = 0x00000020, // Static 'super' reference + ContextChecked = 0x00000040, // Contextual types have been assigned } export interface NodeLinks { From 352a44df3fde32e86a7e76dd07039c822bdb8b86 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 31 Jul 2014 15:56:00 -0700 Subject: [PATCH 04/29] Accepting new baselines. Previous commit fixes overly aggressive -noImplictAny reporting. In the test case the source of the error is the 'getAndSet' property that implicitly gets type any. The fact that the setter then gets type any isn't actually an error. --- .../implicitAnyGetAndSetAccessorWithAnyReturnType.errors.txt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.errors.txt b/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.errors.txt index d6439688597..c3484202590 100644 --- a/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.errors.txt +++ b/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.errors.txt @@ -1,4 +1,4 @@ -==== tests/cases/compiler/implicitAnyGetAndSetAccessorWithAnyReturnType.ts (9 errors) ==== +==== tests/cases/compiler/implicitAnyGetAndSetAccessorWithAnyReturnType.ts (8 errors) ==== // these should be errors class GetAndSet { getAndSet = null; // error at "getAndSet" @@ -14,8 +14,6 @@ public set haveGetAndSet(value) { // error at "value" ~~~~~~~~~~~~~ !!! Accessors are only available when targeting ECMAScript 5 and higher. - ~~~~~ -!!! Parameter 'value' implicitly has an 'any' type. this.getAndSet = value; } } From f2a8842215de65d7042b4bb6d483728fb19c051d Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 31 Jul 2014 21:43:08 -0700 Subject: [PATCH 05/29] Addressed code review feedback. --- src/compiler/tc.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/compiler/tc.ts b/src/compiler/tc.ts index fa922138d17..fc508ed459c 100644 --- a/src/compiler/tc.ts +++ b/src/compiler/tc.ts @@ -185,17 +185,18 @@ module ts { validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors); } - if (commandLine.filenames.length === 0 && !(commandLine.options.help || commandLine.options.version)) { - commandLine.errors.push(createCompilerDiagnostic(Diagnostics.No_input_files_specified)); - } - if (commandLine.options.version) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.Version_0, version)); sys.exit(0); } - if (commandLine.filenames.length === 0 || commandLine.options.help) { + if (commandLine.options.help) { // TODO (drosen): Usage. + sys.exit(0); + } + + if (commandLine.filenames.length === 0) { + commandLine.errors.push(createCompilerDiagnostic(Diagnostics.No_input_files_specified)); } if (commandLine.errors.length) { From 91023227e49c6757522c826f6a4fbaeb61693252 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 31 Jul 2014 21:58:05 -0700 Subject: [PATCH 06/29] Changed watchFile callback behavior. We no longer recompile unless the new last-modified time is more recent. --- src/compiler/sys.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index ce31988b504..03d517476cd 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -199,7 +199,11 @@ var sys: System = (function () { close() { _fs.unwatchFile(fileName, fileChanged); } }; - function fileChanged() { + function fileChanged(curr:any, prev:any) { + if (+curr.mtime <= +prev.mtime) { + return; + } + callback(fileName); }; }, From 95badebee3361aad580a1e5a6e83b2414672793e Mon Sep 17 00:00:00 2001 From: milkisevil Date: Fri, 1 Aug 2014 12:18:42 +0100 Subject: [PATCH 07/29] Added ArrayBuffer.slice() to extensions.d.ts --- src/lib/extensions.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lib/extensions.d.ts b/src/lib/extensions.d.ts index 62f3bc88c80..87b78018c7e 100644 --- a/src/lib/extensions.d.ts +++ b/src/lib/extensions.d.ts @@ -14,6 +14,11 @@ interface ArrayBuffer { * Read-only. The length of the ArrayBuffer (in bytes). */ byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; } declare var ArrayBuffer: { From 5d25821cff34f65e001ab5579fd4f4fbaf33c6eb Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 Aug 2014 08:13:38 -0700 Subject: [PATCH 08/29] Introduced fullTypeCheck flag. checkFunctionExpression only type checks function body if fullTypeCheck is true. --- src/compiler/checker.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ef6dff1414e..99b4d776b43 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -56,6 +56,7 @@ module ts { var stringLiteralTypes: Map = {}; + var fullTypeCheck = false; var emitExtends = false; var mergedSymbols: Symbol[] = []; @@ -4272,7 +4273,7 @@ module ts { } } } - if (!(links.flags & NodeCheckFlags.TypeChecked)) { + if (fullTypeCheck && !(links.flags & NodeCheckFlags.TypeChecked)) { checkSignatureDeclaration(node); if (node.type) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); @@ -6019,9 +6020,12 @@ module ts { } } + // Fully type check a source file and collect the relevant diagnostics. The fullTypeCheck flag is true during this + // operation, but otherwise is false when the compiler is used by the language service. function checkSourceFile(node: SourceFile) { var links = getNodeLinks(node); if (!(links.flags & NodeCheckFlags.TypeChecked)) { + fullTypeCheck = true; emitExtends = false; potentialThisCollisions.length = 0; forEach(node.statements, checkSourceElement); @@ -6038,6 +6042,7 @@ module ts { } if (emitExtends) links.flags |= NodeCheckFlags.EmitExtends; links.flags |= NodeCheckFlags.TypeChecked; + fullTypeCheck = false; } } From c0b3efbbb4709cc074c34862b506140248a3ec76 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Fri, 1 Aug 2014 11:16:09 -0700 Subject: [PATCH 09/29] emit this capturing as a first action in the constructor --- src/compiler/emitter.ts | 4 +-- .../reference/arrowFunctionContexts.js | 4 +-- .../reference/captureThisInSuperCall.js | 32 +++++++++++++++++++ .../classMemberInitializerWithLamdaScoping.js | 2 +- ...ionAndPropertyNameAsConstuctorParameter.js | 4 +-- .../derivedClassSuperCallsWithThisArg.js | 2 +- tests/baselines/reference/lambdaPropSelf.js | 2 +- tests/baselines/reference/statics.js | 2 +- .../reference/validUseOfThisInSuper.js | 2 +- .../cases/compiler/captureThisInSuperCall.ts | 8 +++++ 10 files changed, 51 insertions(+), 11 deletions(-) create mode 100644 tests/baselines/reference/captureThisInSuperCall.js create mode 100644 tests/cases/compiler/captureThisInSuperCall.ts diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index a80845d852b..b867a555ef0 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1371,6 +1371,7 @@ module ts { write(" {"); scopeEmitStart(node, "constructor"); increaseIndent(); + emitCaptureThisForNodeIfNecessary(node); if (ctor) { emitDefaultValueAssignments(ctor); emitRestParameter(ctor); @@ -1390,8 +1391,7 @@ module ts { write("_super.apply(this, arguments);"); emitEnd(node.baseType); } - } - emitCaptureThisForNodeIfNecessary(node); + } emitMemberAssignments(node, /*nonstatic*/0); if (ctor) { var statements: Node[] = (ctor.body).statements; diff --git a/tests/baselines/reference/arrowFunctionContexts.js b/tests/baselines/reference/arrowFunctionContexts.js index 24b928c7842..d0b43e61c84 100644 --- a/tests/baselines/reference/arrowFunctionContexts.js +++ b/tests/baselines/reference/arrowFunctionContexts.js @@ -114,8 +114,8 @@ var Base = (function () { var Derived = (function (_super) { __extends(Derived, _super); function Derived() { - _super.call(this, function () { return _this; }); var _this = this; + _super.call(this, function () { return _this; }); } return Derived; })(Base); @@ -147,8 +147,8 @@ var M2; var Derived = (function (_super) { __extends(Derived, _super); function Derived() { - _super.call(this, function () { return _this; }); var _this = this; + _super.call(this, function () { return _this; }); } return Derived; })(Base); diff --git a/tests/baselines/reference/captureThisInSuperCall.js b/tests/baselines/reference/captureThisInSuperCall.js new file mode 100644 index 00000000000..3f60fcd3cb1 --- /dev/null +++ b/tests/baselines/reference/captureThisInSuperCall.js @@ -0,0 +1,32 @@ +//// [captureThisInSuperCall.ts] +class A { + constructor(p:any) {} +} + +class B extends A { + constructor() { super({ test: () => this.someMethod()}); } + someMethod() {} +} + +//// [captureThisInSuperCall.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var A = (function () { + function A(p) { + } + return A; +})(); +var B = (function (_super) { + __extends(B, _super); + function B() { + var _this = this; + _super.call(this, { test: function () { return _this.someMethod(); } }); + } + B.prototype.someMethod = function () { + }; + return B; +})(A); diff --git a/tests/baselines/reference/classMemberInitializerWithLamdaScoping.js b/tests/baselines/reference/classMemberInitializerWithLamdaScoping.js index f246ea38709..9eb0eb83074 100644 --- a/tests/baselines/reference/classMemberInitializerWithLamdaScoping.js +++ b/tests/baselines/reference/classMemberInitializerWithLamdaScoping.js @@ -33,8 +33,8 @@ class Test1 { //// [classMemberInitializerWithLamdaScoping.js] var Test = (function () { function Test(field) { - this.field = field; var _this = this; + this.field = field; this.messageHandler = function () { var field = _this.field; console.log(field); diff --git a/tests/baselines/reference/collisionThisExpressionAndPropertyNameAsConstuctorParameter.js b/tests/baselines/reference/collisionThisExpressionAndPropertyNameAsConstuctorParameter.js index 813295bb889..566bb552a70 100644 --- a/tests/baselines/reference/collisionThisExpressionAndPropertyNameAsConstuctorParameter.js +++ b/tests/baselines/reference/collisionThisExpressionAndPropertyNameAsConstuctorParameter.js @@ -47,8 +47,8 @@ var Foo2 = (function () { })(); var Foo3 = (function () { function Foo3(_this) { - this._this = _this; var _this = this; + this._this = _this; var lambda = function () { return function (x) { return _this; }; }; @@ -66,8 +66,8 @@ var Foo4 = (function () { })(); var Foo5 = (function () { function Foo5(_this) { - this._this = _this; var _this = this; + this._this = _this; var lambda = function () { return function (x) { return _this; }; }; diff --git a/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js b/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js index 163337ae12e..0616d94cdff 100644 --- a/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js +++ b/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js @@ -58,9 +58,9 @@ var Derived2 = (function (_super) { var Derived3 = (function (_super) { __extends(Derived3, _super); function Derived3(a) { + var _this = this; _super.call(this, function () { return _this; }); this.a = a; - var _this = this; } return Derived3; })(Base); diff --git a/tests/baselines/reference/lambdaPropSelf.js b/tests/baselines/reference/lambdaPropSelf.js index 1630bd0c5d7..8d1b16e1431 100644 --- a/tests/baselines/reference/lambdaPropSelf.js +++ b/tests/baselines/reference/lambdaPropSelf.js @@ -26,8 +26,8 @@ module M { //// [lambdaPropSelf.js] var Person = (function () { function Person(name, children) { - this.name = name; var _this = this; + this.name = name; this.addChild = function () { return _this.children.push("New child"); }; this.children = ko.observableArray(children); } diff --git a/tests/baselines/reference/statics.js b/tests/baselines/reference/statics.js index 4266725bec6..c69fa0aabd7 100644 --- a/tests/baselines/reference/statics.js +++ b/tests/baselines/reference/statics.js @@ -36,9 +36,9 @@ var M; (function (M) { var C = (function () { function C(c1, c2, c3) { + var _this = this; this.c1 = c1; this.c2 = c2; - var _this = this; this.x = C.y + this.c1 + this.c2 + c3; this.g = function (v) { return C.f(_this.x + C.y + v + _this.c1 + _this.c2 + C.pub); }; } diff --git a/tests/baselines/reference/validUseOfThisInSuper.js b/tests/baselines/reference/validUseOfThisInSuper.js index 9ff9bb08425..a57f2934439 100644 --- a/tests/baselines/reference/validUseOfThisInSuper.js +++ b/tests/baselines/reference/validUseOfThisInSuper.js @@ -25,8 +25,8 @@ var Base = (function () { var Super = (function (_super) { __extends(Super, _super); function Super() { - _super.call(this, (function () { return _this; })()); var _this = this; + _super.call(this, (function () { return _this; })()); } return Super; })(Base); diff --git a/tests/cases/compiler/captureThisInSuperCall.ts b/tests/cases/compiler/captureThisInSuperCall.ts new file mode 100644 index 00000000000..8037aa50b44 --- /dev/null +++ b/tests/cases/compiler/captureThisInSuperCall.ts @@ -0,0 +1,8 @@ +class A { + constructor(p:any) {} +} + +class B extends A { + constructor() { super({ test: () => this.someMethod()}); } + someMethod() {} +} \ No newline at end of file From e6ea85d31b2a40ca2531791eb33dcde9d4b4e4f4 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 Aug 2014 12:36:09 -0700 Subject: [PATCH 10/29] Properly build container list in binder. Containers are added to container list only if they aren't already on the list. Fixes #325. --- src/compiler/binder.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index faf8d96e2be..7b16c785833 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -171,8 +171,13 @@ module ts { parent = node; if (symbolKind & SymbolFlags.IsContainer) { container = node; - if (lastContainer) lastContainer.nextContainer = container; - lastContainer = container; + // If container is not on container list, add it to the list + if (lastContainer !== container && !container.nextContainer) { + if (lastContainer) { + lastContainer.nextContainer = container; + } + lastContainer = container; + } } forEachChild(node, bind); container = saveContainer; From acd3ba35ccd577ab9b77adce528bd078e4d5d392 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Fri, 1 Aug 2014 13:05:23 -0700 Subject: [PATCH 11/29] Remove debugger statements from fourslash tests --- tests/cases/fourslash/genericParameterHelp.ts | 1 - tests/cases/fourslash/navbar_contains-no-duplicates.ts | 2 +- tests/cases/fourslash/signatureHelpNegativeTests.ts | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/cases/fourslash/genericParameterHelp.ts b/tests/cases/fourslash/genericParameterHelp.ts index 7cf81f685f7..b5601c1eb5b 100644 --- a/tests/cases/fourslash/genericParameterHelp.ts +++ b/tests/cases/fourslash/genericParameterHelp.ts @@ -27,7 +27,6 @@ ////class Bar extends testClass; -debugger; // goTo.marker("1"); // verify.currentSignatureParamterCountIs(3); // verify.currentSignatureHelpIs("testFunction(a: T, b: U, c: M): M"); diff --git a/tests/cases/fourslash/navbar_contains-no-duplicates.ts b/tests/cases/fourslash/navbar_contains-no-duplicates.ts index 6dd06d9d4ba..4334d30229f 100644 --- a/tests/cases/fourslash/navbar_contains-no-duplicates.ts +++ b/tests/cases/fourslash/navbar_contains-no-duplicates.ts @@ -26,7 +26,7 @@ //// {| "itemName": "ABC", "kind": "module", "parentName": "" |}module ABC { //// export var {| "itemName": "x", "kind": "var" |}x = 3; //// } -debugger; + verify.getScriptLexicalStructureListCount(12); test.markers().forEach(marker => { if (marker.data) { diff --git a/tests/cases/fourslash/signatureHelpNegativeTests.ts b/tests/cases/fourslash/signatureHelpNegativeTests.ts index 2e8703ad340..32d76d158a6 100644 --- a/tests/cases/fourslash/signatureHelpNegativeTests.ts +++ b/tests/cases/fourslash/signatureHelpNegativeTests.ts @@ -5,7 +5,7 @@ //////inside a comment foo(/*insideComment*/ ////cl/*invalidContext*/ass InvalidSignatureHelpLocation { } ////InvalidSignatureHelpLocation(/*validContext*/); -debugger; + goTo.marker('insideComment'); verify.not.signatureHelpPresent(); From b43d694ec1327fb4cfa3d7d72a04447f7c3a9fb2 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Fri, 1 Aug 2014 13:09:06 -0700 Subject: [PATCH 12/29] move exportAssignSymbol to symbolLinks --- src/compiler/checker.ts | 10 ++++++---- src/compiler/types.ts | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6097e3337dd..9b014e744a7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -443,13 +443,15 @@ module ts { return moduleSymbol; } - function getExportAssignmentSymbol(symbol: Symbol): Symbol { + function getExportAssignmentSymbol(symbol: Symbol): Symbol { checkTypeOfExportAssignmentSymbol(symbol); - return symbol.exportAssignSymbol === unknownSymbol ? undefined : symbol.exportAssignSymbol; + var symbolLinks = getSymbolLinks(symbol); + return symbolLinks.exportAssignSymbol === unknownSymbol ? undefined : symbolLinks.exportAssignSymbol; } function checkTypeOfExportAssignmentSymbol(containerSymbol: Symbol): void { - if (!containerSymbol.exportAssignSymbol) { + var symbolLinks = getSymbolLinks(containerSymbol); + if (!symbolLinks.exportAssignSymbol) { var exportInformation = collectExportInformationForSourceFileOrModule(containerSymbol); if (exportInformation.exportAssignments.length) { if (exportInformation.exportAssignments.length > 1) { @@ -470,7 +472,7 @@ module ts { var exportSymbol = resolveName(node, node.exportName.text, meaning, Diagnostics.Cannot_find_name_0, identifierToString(node.exportName)); } } - containerSymbol.exportAssignSymbol = exportSymbol || unknownSymbol; + symbolLinks.exportAssignSymbol = exportSymbol || unknownSymbol; } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 6ca6035a968..2a1e14d4f13 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -717,7 +717,6 @@ module ts { members?: SymbolTable; // Class, interface or literal instance members exports?: SymbolTable; // Module exports exportSymbol?: Symbol; // Exported symbol associated with this symbol - exportAssignSymbol?: Symbol; // Symbol exported from external module valueDeclaration?: Declaration // First value declaration of the symbol } @@ -727,6 +726,7 @@ module ts { declaredType?: Type; // Type of class, interface, enum, or type parameter mapper?: TypeMapper; // Type mapper for instantiation alias referenced?: boolean; // True if alias symbol has been referenced as a value + exportAssignSymbol?: Symbol; // Symbol exported from external module } export interface TransientSymbol extends Symbol, SymbolLinks { } From fedbc1cd9e78fcef81d16596ef776c2cf0505fe2 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Fri, 1 Aug 2014 13:50:59 -0700 Subject: [PATCH 13/29] Fix compile errors in fourslash tests --- tests/cases/fourslash/addMethodToInterface1.ts | 2 +- tests/cases/fourslash/arrayConcatTypeCheck0.ts | 2 +- tests/cases/fourslash/arrayConcatTypeCheck1.ts | 8 ++++---- tests/cases/fourslash/genericParameterHelp.ts | 2 +- tests/cases/fourslash/importDeclPaste0.ts | 2 +- .../fourslash/multipleExportAssignmentsErrorList0.ts | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/cases/fourslash/addMethodToInterface1.ts b/tests/cases/fourslash/addMethodToInterface1.ts index b9835cfa44a..749f5601173 100644 --- a/tests/cases/fourslash/addMethodToInterface1.ts +++ b/tests/cases/fourslash/addMethodToInterface1.ts @@ -9,7 +9,7 @@ edit.disableFormatting(); -goTo.marker(1); +goTo.marker('1'); edit.insert(" compareTo(): number;\n"); diagnostics.validateTypesAtPositions(168,84,53,118,22); diff --git a/tests/cases/fourslash/arrayConcatTypeCheck0.ts b/tests/cases/fourslash/arrayConcatTypeCheck0.ts index 0e21eb44b3b..ac5404266a6 100644 --- a/tests/cases/fourslash/arrayConcatTypeCheck0.ts +++ b/tests/cases/fourslash/arrayConcatTypeCheck0.ts @@ -11,7 +11,7 @@ edit.disableFormatting(); -goTo.marker(1); +goTo.marker('1'); edit.insert(", 'world'"); diagnostics.validateTypesAtPositions(78); diff --git a/tests/cases/fourslash/arrayConcatTypeCheck1.ts b/tests/cases/fourslash/arrayConcatTypeCheck1.ts index 7f2af5973b6..42d9cdb8a1c 100644 --- a/tests/cases/fourslash/arrayConcatTypeCheck1.ts +++ b/tests/cases/fourslash/arrayConcatTypeCheck1.ts @@ -10,18 +10,18 @@ edit.disableFormatting(); -goTo.marker(1); +goTo.marker('1'); edit.deleteAtCaret(9); -goTo.marker(3); +goTo.marker('3'); edit.deleteAtCaret(7); -goTo.marker(2); +goTo.marker('2'); edit.deleteAtCaret(7); -goTo.marker(4); +goTo.marker('4'); diagnostics.validateTypesAtPositions(43); diff --git a/tests/cases/fourslash/genericParameterHelp.ts b/tests/cases/fourslash/genericParameterHelp.ts index b5601c1eb5b..e5a6385c179 100644 --- a/tests/cases/fourslash/genericParameterHelp.ts +++ b/tests/cases/fourslash/genericParameterHelp.ts @@ -27,7 +27,7 @@ ////class Bar extends testClass; -// goTo.marker("1"); +goTo.marker("1"); // verify.currentSignatureParamterCountIs(3); // verify.currentSignatureHelpIs("testFunction(a: T, b: U, c: M): M"); diff --git a/tests/cases/fourslash/importDeclPaste0.ts b/tests/cases/fourslash/importDeclPaste0.ts index 60a82aa124f..6bb8eb6894e 100644 --- a/tests/cases/fourslash/importDeclPaste0.ts +++ b/tests/cases/fourslash/importDeclPaste0.ts @@ -13,6 +13,6 @@ edit.disableFormatting(); -goTo.marker(1); +goTo.marker('1'); //edit.insert("\nimport I1 = module(\"exportEqualsInterface_A\");\n"); diff --git a/tests/cases/fourslash/multipleExportAssignmentsErrorList0.ts b/tests/cases/fourslash/multipleExportAssignmentsErrorList0.ts index 51d1d3ccf36..721d110ce68 100644 --- a/tests/cases/fourslash/multipleExportAssignmentsErrorList0.ts +++ b/tests/cases/fourslash/multipleExportAssignmentsErrorList0.ts @@ -18,10 +18,10 @@ //// edit.disableFormatting(); -goTo.marker(1); +goTo.marker('1'); edit.deleteAtCaret(24); -goTo.marker(1); +goTo.marker('1'); edit.insert("export = connectExport;\n"); From b4a450026b5b26339d6fdc66384a6954a54576eb Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Fri, 1 Aug 2014 13:51:34 -0700 Subject: [PATCH 14/29] Use compiler directly in fourslash runner so we can avoid repeated compile overhead --- src/harness/fourslash.ts | 60 ++++++++++++++++++---------------- src/harness/fourslashRunner.ts | 2 +- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 9a1f97395a0..30b70f1631e 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -226,7 +226,8 @@ module FourSlash { }); } - // NEWTODO: Re-implement commented-out section + // NEWTODO: Re-implement commented-out section + //harnessCompiler.addInputFiles(inputFiles); //try { // var resolvedFiles = harnessCompiler.resolve(); @@ -246,8 +247,15 @@ module FourSlash { // harnessCompiler.reset(); //} - /// NEWTODO: For now do not resolve, just use the input files inputFiles.forEach(file => { if (!Harness.isLibraryFile(file.unitName)) { this.languageServiceShimHost.addScript(file.unitName, file.content); } }); - this.languageServiceShimHost.addScript('lib.d.ts', Harness.Compiler.libTextMinimal); + /// NEWTODO: For now do not resolve, just use the input files + inputFiles.forEach(file => { + if (!Harness.isLibraryFile(file.unitName)) { + this.languageServiceShimHost.addScript(file.unitName, file.content); + } + }); + + this.languageServiceShimHost.addScript('lib.d.ts', Harness.Compiler.libTextMinimal); + // Sneak into the language service and get its compiler so we can examine the syntax trees this.languageService = this.languageServiceShimHost.getLanguageService().languageService; @@ -1875,6 +1883,9 @@ module FourSlash { xmlData.push(xml); } + // Cache these between executions so we don't have to re-parse them for every test + var fourslashSourceFile: ts.SourceFile = undefined; + var libdtsSourceFile: ts.SourceFile = undefined; export function runFourSlashTestContent(content: string, fileName: string): TestXmlData { // Parse out the files and their metadata var testData = parseTestData(content, fileName); @@ -1882,34 +1893,27 @@ module FourSlash { currentTestState = new TestState(testData); var result = ''; - var tsFn = 'tests/cases/fourslash/fourslash.ts'; + var fourslashFilename = 'fourslash.ts'; + var tsFn = 'tests/cases/fourslash/' + fourslashFilename; + fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), ts.ScriptTarget.ES5); + libdtsSourceFile = libdtsSourceFile || ts.createSourceFile('lib.d.ts', Harness.Compiler.libTextMinimal, ts.ScriptTarget.ES3); - fsOutput.reset(); - fsErrors.reset(); + var files: { [filename: string]: ts.SourceFile; } = {}; + files[fourslashFilename] = fourslashSourceFile; + files[fileName] = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5); + files['lib.d.ts'] = libdtsSourceFile; - var harnessCompiler = Harness.Compiler.getCompiler(); - harnessCompiler.reset(); + var host = Harness.Compiler.createCompilerHost(files, (fn, contents) => result = contents); + var program = ts.createProgram([fileName, fourslashFilename], {}, host); + var checker = ts.createTypeChecker(program); + checker.checkProgram(); - var filesToAdd = [ - { unitName: tsFn, content: Harness.IO.readFile(tsFn) }, - { unitName: fileName, content: Harness.IO.readFile(fileName) } - ]; - harnessCompiler.addInputFiles(filesToAdd); - - var emitterIOHost: Harness.Compiler.IEmitterIOHost = { - writeFile: (path: string, contents: string, writeByteOrderMark: boolean) => fsOutput.Write(contents), - resolvePath: (s: string) => s + var errs = checker.getDiagnostics(files[fileName]); + if (errs.length > 0) { + throw new Error('Error compiling ' + fileName + ': ' + errs.map(e => e.messageText).join('\r\n')); } - - harnessCompiler.emitAll(emitterIOHost); - fsOutput.Close(); - fsErrors.Close(); - - if (fsErrors.lines.length > 0) { - throw new Error('Error compiling ' + fileName + ': ' + fsErrors.lines.join('\r\n')); - } - - result = fsOutput.lines.join('\r\n'); + checker.emitFiles(); + result = result || ''; // Might have an empty fourslash file // Compile and execute the test try { @@ -1917,8 +1921,6 @@ module FourSlash { } catch (err) { // Debugging: FourSlash.currentTestState.printCurrentFileState(); throw err; - } finally { - harnessCompiler.reset(); } var xmlData = currentTestState.getTestXmlData(); diff --git a/src/harness/fourslashRunner.ts b/src/harness/fourslashRunner.ts index 676cb604800..102d4433b10 100644 --- a/src/harness/fourslashRunner.ts +++ b/src/harness/fourslashRunner.ts @@ -11,7 +11,7 @@ class FourslashRunner extends RunnerBase { public initializeTests() { if (this.tests.length === 0) { - this.tests = this.enumerateFiles(this.basePath); + this.tests = this.enumerateFiles(this.basePath, /\.ts/i); } describe("fourslash tests", () => { From c25ed6b3ca7d941d2f24af3f11e7e136532c30f4 Mon Sep 17 00:00:00 2001 From: Dan Quirk Date: Fri, 1 Aug 2014 15:06:43 -0700 Subject: [PATCH 15/29] Add timeout for CI server and switch to min reporter since dots are mostly useless there --- Jakefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jakefile b/Jakefile index a36c3f4a9d7..66eb1f95bd7 100644 --- a/Jakefile +++ b/Jakefile @@ -348,6 +348,7 @@ function deleteTemporaryProjectOutput() { } } +var testTimeout = 5000; desc("Runs the tests using the built run.js file. Syntax is jake runtests. Optional parameters 'host=', 'tests=[regex], reporter=[list|spec|json|]'."); task("runtests", ["tests", builtLocalDirectory], function() { cleanTestDirs(); @@ -367,14 +368,14 @@ task("runtests", ["tests", builtLocalDirectory], function() { reporter = process.env.reporter || process.env.r || 'dot'; // timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer - var cmd = host + " -R " + reporter + tests + colors + ' --timeout 3000 ' + run; + var cmd = host + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run; console.log(cmd); exec(cmd, deleteTemporaryProjectOutput); }, {async: true}); desc("Generates code coverage data via instanbul") task("generate-code-coverage", ["tests", builtLocalDirectory], function () { - var cmd = "istanbul cover node_modules/mocha/bin/_mocha -- -R dot " + run; + var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run; console.log(cmd); exec(cmd); }, { async: true }); From cb038467d6d0f1e6f6bbf43a485bb83a5c60a4b2 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 Aug 2014 15:20:08 -0700 Subject: [PATCH 16/29] Adding regression test for #325 --- tests/cases/compiler/testContainerList.ts | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 tests/cases/compiler/testContainerList.ts diff --git a/tests/cases/compiler/testContainerList.ts b/tests/cases/compiler/testContainerList.ts new file mode 100644 index 00000000000..29a4fbd206c --- /dev/null +++ b/tests/cases/compiler/testContainerList.ts @@ -0,0 +1,6 @@ +// Regression test for #325 +module A { + class C { + constructor(public d: {}) { } + } +} From afe3abde5b0a309ae0f7002368ef2498df02d0d7 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 Aug 2014 15:24:02 -0700 Subject: [PATCH 17/29] Adding test output file. --- .../baselines/reference/testContainerList.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/baselines/reference/testContainerList.js diff --git a/tests/baselines/reference/testContainerList.js b/tests/baselines/reference/testContainerList.js new file mode 100644 index 00000000000..d7e91a59256 --- /dev/null +++ b/tests/baselines/reference/testContainerList.js @@ -0,0 +1,19 @@ +//// [testContainerList.ts] +// Regression test for #325 +module A { + class C { + constructor(public d: {}) { } + } +} + + +//// [testContainerList.js] +var A; +(function (A) { + var C = (function () { + function C(d) { + this.d = d; + } + return C; + })(); +})(A || (A = {})); From 694dc0e75946e49069af96d8b382f9d624e6eabf Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Fri, 1 Aug 2014 17:50:57 -0700 Subject: [PATCH 18/29] Fix #225: Incompatible FormData constructor between W3C specs --- src/lib/dom.generated.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index cdb6a48fcb1..4d497b4c117 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -1865,6 +1865,14 @@ declare var Window: { new(): Window; } +interface FormData { + append(name: any, value: any, blobName?: string): void; +} +declare var FormData: { + prototype: FormData; + new (form?:HTMLFormElement): FormData; +} + interface NavigatorID { appVersion: string; appName: string; @@ -10196,14 +10204,6 @@ declare var MSManipulationEvent: { MS_MANIPULATION_STATE_CANCELLED: number; } -interface FormData { - append(name: any, value: any, blobName?: string): void; -} -declare var FormData: { - prototype: FormData; - new(): FormData; -} - interface HTMLDataListElement extends HTMLElement { options: HTMLCollection; } From 3a46a1c5e5b6046e10ffec39a4ef98fe55b49ace Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Fri, 1 Aug 2014 17:51:41 -0700 Subject: [PATCH 19/29] Fix #314: SourceBuffer.appendBuffer() is missing overload for ArrayBufferView param in lib.d.ts --- src/lib/dom.generated.d.ts | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 4d497b4c117..2e7c5eba819 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -1870,7 +1870,25 @@ interface FormData { } declare var FormData: { prototype: FormData; - new (form?:HTMLFormElement): FormData; + new (form?: HTMLFormElement): FormData; +} + +interface SourceBuffer extends EventTarget { + updating: boolean; + appendWindowStart: number; + appendWindowEnd: number; + buffered: TimeRanges; + timestampOffset: number; + audioTracks: AudioTrackList; + appendBuffer(data: ArrayBufferView): void; + appendBuffer(data: ArrayBuffer): void; + remove(start: number, end: number): void; + abort(): void; + appendStream(stream: MSStream, maxSize?: number): void; +} +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; } interface NavigatorID { @@ -10622,23 +10640,6 @@ interface RandomSource { getRandomValues(array: ArrayBufferView): ArrayBufferView; } -interface SourceBuffer extends EventTarget { - updating: boolean; - appendWindowStart: number; - appendWindowEnd: number; - buffered: TimeRanges; - timestampOffset: number; - audioTracks: AudioTrackList; - appendBuffer(data: ArrayBuffer): void; - remove(start: number, end: number): void; - abort(): void; - appendStream(stream: MSStream, maxSize?: number): void; -} -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - interface MSInputMethodContext extends EventTarget { oncandidatewindowshow: (ev: any) => any; target: HTMLElement; From 0d1ed3f12ca96f804511e93483e7a44afda2426b Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Fri, 1 Aug 2014 17:52:51 -0700 Subject: [PATCH 20/29] Update LKG --- bin/lib.d.ts | 56 +- bin/lib.dom.d.ts | 56 +- bin/lib.webworker.d.ts | 5 + bin/tc.js | 311 +- bin/typescriptServices.js | 31644 ++++++++++++++++++++++++++++++++++++ 5 files changed, 31925 insertions(+), 147 deletions(-) create mode 100644 bin/typescriptServices.js diff --git a/bin/lib.d.ts b/bin/lib.d.ts index 605738614c9..6a97175c5e8 100644 --- a/bin/lib.d.ts +++ b/bin/lib.d.ts @@ -1157,6 +1157,11 @@ interface ArrayBuffer { * Read-only. The length of the ArrayBuffer (in bytes). */ byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; } declare var ArrayBuffer: { @@ -3826,6 +3831,32 @@ declare var Window: { new(): Window; } +interface FormData { + append(name: any, value: any, blobName?: string): void; +} +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +} + +interface SourceBuffer extends EventTarget { + updating: boolean; + appendWindowStart: number; + appendWindowEnd: number; + buffered: TimeRanges; + timestampOffset: number; + audioTracks: AudioTrackList; + appendBuffer(data: ArrayBufferView): void; + appendBuffer(data: ArrayBuffer): void; + remove(start: number, end: number): void; + abort(): void; + appendStream(stream: MSStream, maxSize?: number): void; +} +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +} + interface NavigatorID { appVersion: string; appName: string; @@ -12157,14 +12188,6 @@ declare var MSManipulationEvent: { MS_MANIPULATION_STATE_CANCELLED: number; } -interface FormData { - append(name: any, value: any, blobName?: string): void; -} -declare var FormData: { - prototype: FormData; - new(): FormData; -} - interface HTMLDataListElement extends HTMLElement { options: HTMLCollection; } @@ -12583,23 +12606,6 @@ interface RandomSource { getRandomValues(array: ArrayBufferView): ArrayBufferView; } -interface SourceBuffer extends EventTarget { - updating: boolean; - appendWindowStart: number; - appendWindowEnd: number; - buffered: TimeRanges; - timestampOffset: number; - audioTracks: AudioTrackList; - appendBuffer(data: ArrayBuffer): void; - remove(start: number, end: number): void; - abort(): void; - appendStream(stream: MSStream, maxSize?: number): void; -} -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - interface MSInputMethodContext extends EventTarget { oncandidatewindowshow: (ev: any) => any; target: HTMLElement; diff --git a/bin/lib.dom.d.ts b/bin/lib.dom.d.ts index ff05bbf6b8d..c0aceb3fc11 100644 --- a/bin/lib.dom.d.ts +++ b/bin/lib.dom.d.ts @@ -30,6 +30,11 @@ interface ArrayBuffer { * Read-only. The length of the ArrayBuffer (in bytes). */ byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; } declare var ArrayBuffer: { @@ -2699,6 +2704,32 @@ declare var Window: { new(): Window; } +interface FormData { + append(name: any, value: any, blobName?: string): void; +} +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +} + +interface SourceBuffer extends EventTarget { + updating: boolean; + appendWindowStart: number; + appendWindowEnd: number; + buffered: TimeRanges; + timestampOffset: number; + audioTracks: AudioTrackList; + appendBuffer(data: ArrayBufferView): void; + appendBuffer(data: ArrayBuffer): void; + remove(start: number, end: number): void; + abort(): void; + appendStream(stream: MSStream, maxSize?: number): void; +} +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +} + interface NavigatorID { appVersion: string; appName: string; @@ -11030,14 +11061,6 @@ declare var MSManipulationEvent: { MS_MANIPULATION_STATE_CANCELLED: number; } -interface FormData { - append(name: any, value: any, blobName?: string): void; -} -declare var FormData: { - prototype: FormData; - new(): FormData; -} - interface HTMLDataListElement extends HTMLElement { options: HTMLCollection; } @@ -11456,23 +11479,6 @@ interface RandomSource { getRandomValues(array: ArrayBufferView): ArrayBufferView; } -interface SourceBuffer extends EventTarget { - updating: boolean; - appendWindowStart: number; - appendWindowEnd: number; - buffered: TimeRanges; - timestampOffset: number; - audioTracks: AudioTrackList; - appendBuffer(data: ArrayBuffer): void; - remove(start: number, end: number): void; - abort(): void; - appendStream(stream: MSStream, maxSize?: number): void; -} -declare var SourceBuffer: { - prototype: SourceBuffer; - new(): SourceBuffer; -} - interface MSInputMethodContext extends EventTarget { oncandidatewindowshow: (ev: any) => any; target: HTMLElement; diff --git a/bin/lib.webworker.d.ts b/bin/lib.webworker.d.ts index a524443368b..654d75b0aa9 100644 --- a/bin/lib.webworker.d.ts +++ b/bin/lib.webworker.d.ts @@ -30,6 +30,11 @@ interface ArrayBuffer { * Read-only. The length of the ArrayBuffer (in bytes). */ byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; } declare var ArrayBuffer: { diff --git a/bin/tc.js b/bin/tc.js index 487e01b2b39..fb6fd8be0b7 100644 --- a/bin/tc.js +++ b/bin/tc.js @@ -172,9 +172,12 @@ var ts; Duplicate_number_index_signature: { code: 2233, category: 1 /* Error */, key: "Duplicate number index signature." }, All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2234, category: 1 /* Error */, key: "All declarations of an interface must have identical type parameters." }, Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: { code: 2235, category: 1 /* Error */, key: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter." }, - Constructor_implementation_expected: { code: 2240, category: 1 /* Error */, key: "Constructor implementation expected." }, + Function_implementation_name_must_be_0: { code: 2239, category: 1 /* Error */, key: "Function implementation name must be '{0}'." }, + Constructor_implementation_is_missing: { code: 2240, category: 1 /* Error */, key: "Constructor implementation is missing." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2245, category: 1 /* Error */, key: "An export assignment cannot be used in a module with other exported elements." }, A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2246, category: 1 /* Error */, key: "A parameter property is only allowed in a constructor implementation." }, + Function_overload_must_be_static: { code: 2247, category: 1 /* Error */, key: "Function overload must be static." }, + Function_overload_must_not_be_static: { code: 2248, category: 1 /* Error */, key: "Function overload must not be static." }, Circular_definition_of_import_alias_0: { code: 3000, category: 1 /* Error */, key: "Circular definition of import alias '{0}'." }, Cannot_find_name_0: { code: 3001, category: 1 /* Error */, key: "Cannot find name '{0}'." }, Module_0_has_no_exported_member_1: { code: 3002, category: 1 /* Error */, key: "Module '{0}' has no exported member '{1}'." }, @@ -291,7 +294,7 @@ var ts; Types_of_parameters_0_and_1_are_incompatible_Colon: { code: -9999999, category: 1 /* Error */, key: "Types of parameters '{0}' and '{1}' are incompatible:" }, Unknown_identifier_0: { code: -9999999, category: 1 /* Error */, key: "Unknown identifier '{0}'." }, Property_0_is_inaccessible: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' is inaccessible." }, - Function_implementation_expected: { code: -9999999, category: 1 /* Error */, key: "Function implementation expected." }, + Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: -9999999, category: 1 /* Error */, key: "Function implementation is missing or not immediately following the declaration." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: -9999999, category: 1 /* Error */, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -320,7 +323,7 @@ var ts; Unsupported_locale_0: { code: -9999999, category: 1 /* Error */, key: "Unsupported locale {0}." }, Unable_to_open_file_0: { code: -9999999, category: 1 /* Error */, key: "Unable to open file {0}." }, Corrupted_locale_file_0: { code: -9999999, category: 1 /* Error */, key: "Corrupted locale file {0}." }, - No_input_files_specified: { code: -9999999, category: 1 /* Error */, key: "No input files specified." }, + No_input_files_specified: { code: -9999999, category: 1 /* Error */, key: "No input files specified." } }; })(ts || (ts = {})); var ts; @@ -430,7 +433,7 @@ var ts; ">>>=": 51 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 52 /* AmpersandEqualsToken */, "|=": 53 /* BarEqualsToken */, - "^=": 54 /* CaretEqualsToken */, + "^=": 54 /* CaretEqualsToken */ }; var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; @@ -1031,7 +1034,7 @@ var ts; if (token === 27 /* SlashToken */ || token === 47 /* SlashEqualsToken */) { var p = tokenPos + 1; var inEscape = false; - var inClass = false; + var inCharacterClass = false; while (true) { if (p >= len) { return token; @@ -1043,23 +1046,24 @@ var ts; if (inEscape) { inEscape = false; } - else if (ch === 47 /* slash */) { + else if (ch === 47 /* slash */ && !inCharacterClass) { break; } else if (ch === 91 /* openBracket */) { - inClass = true; + inCharacterClass = true; } else if (ch === 92 /* backslash */) { inEscape = true; } else if (ch === 93 /* closeBracket */) { - inClass = false; + inCharacterClass = false; } p++; } p++; - while (isIdentifierPart(text.charCodeAt(p))) + while (isIdentifierPart(text.charCodeAt(p))) { p++; + } pos = p; tokenValue = text.substring(tokenPos, pos); token = 4 /* RegularExpressionLiteral */; @@ -1573,6 +1577,13 @@ var ts; CharacterCodes[CharacterCodes["verticalTab"] = 0x0B] = "verticalTab"; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; + (function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; + })(ts.ByteOrderMark || (ts.ByteOrderMark = {})); + var ByteOrderMark = ts.ByteOrderMark; })(ts || (ts = {})); var ts; (function (ts) { @@ -1704,6 +1715,19 @@ var ts; return result; } ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; + } + return result; + } + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; function mapToArray(map) { var result = []; for (var id in map) @@ -1766,14 +1790,14 @@ var ts; }; } ts.chainDiagnosticMessages = chainDiagnosticMessages; - function flattenDiagnosticChain(file, start, length, diagnosticChain) { + function flattenDiagnosticChain(file, start, length, diagnosticChain, newLine) { var code = diagnosticChain.code; var category = diagnosticChain.category; var messageText = ""; var indent = 0; while (diagnosticChain) { if (indent) { - messageText += sys.newLine; + messageText += newLine; for (var i = 0; i < indent; i++) { messageText += " "; } @@ -2010,7 +2034,7 @@ var ts; pos: 0, end: 0, flags: 0, - parent: undefined, + parent: undefined }; return Node; }, @@ -2301,12 +2325,12 @@ var ts; return ts.createFileDiagnostic(file, start, length, message, arg0, arg1, arg2); } ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeFromMessageChain(node, messageChain) { + function createDiagnosticForNodeFromMessageChain(node, messageChain, newLine) { node = getErrorSpanForNode(node); var file = getSourceFileOfNode(node); var start = ts.skipTrivia(file.text, node.pos); var length = node.end - start; - return ts.flattenDiagnosticChain(file, start, length, messageChain); + return ts.flattenDiagnosticChain(file, start, length, messageChain, newLine); } ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; function getErrorSpanForNode(node) { @@ -2474,6 +2498,15 @@ var ts; return s.parameters.length > 0 && (s.parameters[s.parameters.length - 1].flags & 8 /* Rest */) !== 0; } ts.hasRestParameters = hasRestParameters; + function isInAmbientContext(node) { + while (node) { + if (node.flags & (2 /* Ambient */ | 512 /* DeclarationFile */)) + return true; + node = node.parent; + } + return false; + } + ts.isInAmbientContext = isInAmbientContext; var ParsingContext; (function (ParsingContext) { ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; @@ -2649,7 +2682,7 @@ var ts; pushCurrentLabelSet: pushCurrentLabelSet, pushFunctionBoundary: pushFunctionBoundary, pop: pop, - nodeIsNestedInLabel: nodeIsNestedInLabel, + nodeIsNestedInLabel: nodeIsNestedInLabel }; })(); function getLineAndCharacterlFromSourcePosition(position) { @@ -3489,7 +3522,11 @@ var ts; var parameter = createNode(114 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); - var signature = { parameters: [parameter] }; + var parameters = []; + parameters.push(parameter); + parameters.pos = parameter.pos; + parameters.end = parameter.end; + var signature = { parameters: parameters }; return parseArrowExpressionTail(identifier.pos, signature, false); } function tryParseParenthesizedArrowFunctionExpression() { @@ -5051,7 +5088,7 @@ var ts; getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeChecker: function () { return ts.createTypeChecker(program); }, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: function () { return commonSourceDirectory; } }; return program; function getSourceFile(filename) { @@ -5528,6 +5565,7 @@ var ts; var compilerOptions = program.getCompilerOptions(); var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; var diagnostics = []; + var newLine = program.getCompilerHost().getNewLine(); function getSourceFilePathInNewDir(newDirPath, sourceFile) { var sourceFilePath = ts.getNormalizedPathFromPathCompoments(ts.getNormalizedPathComponents(sourceFile.filename, compilerHost.getCurrentDirectory())); sourceFilePath = sourceFilePath.replace(program.getCommonSourceDirectory(), ""); @@ -5617,7 +5655,7 @@ var ts; } function writeLine() { if (!lineStart) { - output += sys.newLine; + output += newLine; lineCount++; linePos = output.length; lineStart = true; @@ -6658,6 +6696,7 @@ var ts; write(" {"); scopeEmitStart(node, "constructor"); increaseIndent(); + emitCaptureThisForNodeIfNecessary(node); if (ctor) { emitDefaultValueAssignments(ctor); emitRestParameter(ctor); @@ -6678,7 +6717,6 @@ var ts; emitEnd(node.baseType); } } - emitCaptureThisForNodeIfNecessary(node); emitMemberAssignments(node, 0); if (ctor) { var statements = ctor.body.statements; @@ -7463,7 +7501,7 @@ var ts; function writeReferencePath(referencedFile) { var declFileName = referencedFile.flags & 512 /* DeclarationFile */ ? referencedFile.filename : shouldEmitToOwnFile(referencedFile) ? getOwnEmitOutputFilePath(referencedFile, ".d.ts") : ts.getModuleNameFromFilename(compilerOptions.out) + ".d.ts"; declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, compilerHost.getCurrentDirectory(), false); - referencePathsOutput += "/// " + sys.newLine; + referencePathsOutput += "/// " + newLine; } if (root) { var addedGlobalFileReference = false; @@ -7562,7 +7600,32 @@ var ts; var potentialThisCollisions = []; var diagnostics = []; var diagnosticsModified = false; - var checker; + var checker = { + getProgram: function () { return program; }, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getNodeCount: function () { return ts.sum(program.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(program.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(program.getSourceFiles(), "symbolCount"); }, + getTypeCount: function () { return typeCount; }, + checkProgram: checkProgram, + emitFiles: invokeEmitter, + getSymbolOfNode: getSymbolOfNode, + getParentOfSymbol: getParentOfSymbol, + getTypeOfSymbol: getTypeOfSymbol, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getReturnTypeOfSignature: getReturnTypeOfSignature, + resolveEntityName: resolveEntityName, + getSymbolsInScope: getSymbolsInScope, + getSymbolOfIdentifier: getSymbolOfIdentifier, + getTypeOfExpression: getTypeOfExpression, + typeToString: typeToString, + symbolToString: symbolToString, + getAugmentedPropertiesOfApparentType: getAugmentedPropertiesOfApparentType + }; function addDiagnostic(diagnostic) { diagnostics.push(diagnostic); diagnosticsModified = true; @@ -8146,9 +8209,9 @@ var ts; } }; } - function typeToString(type, flags) { + function typeToString(type, enclosingDeclaration, flags) { var stringWriter = createSingleLineTextWriter(); - writeTypeToTextWriter(type, null, flags, stringWriter); + writeTypeToTextWriter(type, enclosingDeclaration, flags, stringWriter); return stringWriter.getText(); } function writeTypeToTextWriter(type, enclosingDeclaration, flags, writer) { @@ -8673,7 +8736,7 @@ var ts; type.baseTypes.push(baseType); } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); } } else { @@ -8713,7 +8776,7 @@ var ts; type.baseTypes.push(baseType); } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); } } else { @@ -9206,7 +9269,7 @@ var ts; type = createTypeReference(type, ts.map(node.typeArguments, function (t) { return getTypeFromTypeNode(t); })); } else { - error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, 1 /* WriteArrayAsGenericType */), typeParameters.length); + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length); type = undefined; } } @@ -9548,7 +9611,7 @@ var ts; 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); - addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); } } } @@ -9585,7 +9648,7 @@ var ts; error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { - addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); } return result; function reportError(message, arg0, arg1) { @@ -10109,7 +10172,7 @@ var ts; return { typeParameters: typeParameters, inferences: inferences, - inferredTypes: new Array(typeParameters.length), + inferredTypes: new Array(typeParameters.length) }; } function inferTypes(context, source, target) { @@ -11419,7 +11482,7 @@ var ts; } function checkAccessorDeclaration(node) { if (node.kind === 118 /* GetAccessor */) { - if (!isInAmbientContext(node) && node.body && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { + if (!ts.isInAmbientContext(node) && node.body && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } @@ -11468,15 +11531,7 @@ var ts; getTypeFromArrayTypeNode(node); } function isPrivateWithinAmbient(node) { - return (node.flags & 32 /* Private */) && isInAmbientContext(node); - } - function isInAmbientContext(node) { - while (node) { - if (node.flags & (2 /* Ambient */ | 512 /* DeclarationFile */)) - return true; - node = node.parent; - } - return false; + return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { var signature = getSignatureFromDeclaration(signatureDeclarationNode); @@ -11498,7 +11553,7 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = n.flags; - if (n.parent.kind !== 170 /* InterfaceDeclaration */ && isInAmbientContext(n)) { + if (n.parent.kind !== 170 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { flags |= 1 /* Export */; } @@ -11535,44 +11590,82 @@ var ts; var hasOverloads = false; var bodyDeclaration; var lastSeenNonAmbientDeclaration; + var previousDeclaration; var declarations = symbol.declarations; var isConstructor = (symbol.flags & 4096 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode) { + if (subsequentNode.kind === node.kind) { + var errorNode = subsequentNode.name || subsequentNode; + if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { + ts.Debug.assert(node.kind === 116 /* Method */); + ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode, diagnostic); + return; + } + else if (subsequentNode.body) { + error(errorNode, ts.Diagnostics.Function_implementation_name_must_be_0, ts.identifierToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & ts.SymbolFlags.Module; for (var i = 0; i < declarations.length; i++) { var node = declarations[i]; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 170 /* InterfaceDeclaration */ || node.parent.kind === 125 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } if (node.kind === 167 /* FunctionDeclaration */ || node.kind === 116 /* Method */ || node.kind === 117 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; - var inAmbientContext = isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 170 /* InterfaceDeclaration */ || node.parent.kind === 125 /* TypeLiteral */ || inAmbientContext; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } - if (node.body) { - if (bodyDeclaration) { - if (isConstructor) { - error(node, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); - } - else { - error(node, ts.Diagnostics.Duplicate_function_implementation); - } + if (node.body && bodyDeclaration) { + if (isConstructor) { + error(node, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); } else { + error(node, ts.Diagnostics.Duplicate_function_implementation); + } + } + else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (node.body) { + if (!bodyDeclaration) { bodyDeclaration = node; } } else { hasOverloads = true; } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } } } - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body) { - if (isConstructor) { - error(lastSeenNonAmbientDeclaration, ts.Diagnostics.Constructor_implementation_expected); - } - else { - error(lastSeenNonAmbientDeclaration, ts.Diagnostics.Function_implementation_expected); - } + if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); @@ -11675,7 +11768,7 @@ var ts; ts.forEach(node.statements, checkSourceElement); } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameters(node) || isInAmbientContext(node) || !node.body) { + if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || !node.body) { return; } ts.forEach(node.parameters, function (p) { @@ -11689,7 +11782,7 @@ var ts; return; } if (node.kind === 114 /* Parameter */) { - if (node.parent.body && ts.hasRestParameters(node.parent) && !isInAmbientContext(node)) { + if (node.parent.body && ts.hasRestParameters(node.parent) && !ts.isInAmbientContext(node)) { error(node, ts.Diagnostics.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter); } return; @@ -11726,7 +11819,7 @@ var ts; if (node.kind === 115 /* Property */ || node.kind === 116 /* Method */ || node.kind === 118 /* GetAccessor */ || node.kind === 119 /* SetAccessor */) { return false; } - if (isInAmbientContext(node)) { + if (ts.isInAmbientContext(node)) { return false; } if (node.kind === 114 /* Parameter */ && !node.parent.body) { @@ -11761,7 +11854,7 @@ var ts; return; } var enclosingClass = getAncestor(node, 169 /* ClassDeclaration */); - if (!enclosingClass || isInAmbientContext(enclosingClass)) { + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; } if (enclosingClass.baseType) { @@ -11994,7 +12087,7 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); var staticType = getTypeOfSymbol(symbol); if (node.baseType) { - emitExtends = emitExtends || !isInAmbientContext(node); + emitExtends = emitExtends || !ts.isInAmbientContext(node); checkTypeReference(node.baseType); } if (type.baseTypes.length) { @@ -12147,7 +12240,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var enumType = getDeclaredTypeOfSymbol(enumSymbol); var autoValue = 0; - var ambient = isInAmbientContext(node); + var ambient = ts.isInAmbientContext(node); ts.forEach(node.members, function (member) { var initializer = member.initializer; if (initializer) { @@ -12190,7 +12283,7 @@ var ts; var declarations = symbol.declarations; for (var i = 0; i < declarations.length; i++) { var declaration = declarations[i]; - if ((declaration.kind === 169 /* ClassDeclaration */ || (declaration.kind === 167 /* FunctionDeclaration */ && declaration.body)) && !isInAmbientContext(declaration)) { + if ((declaration.kind === 169 /* ClassDeclaration */ || (declaration.kind === 167 /* FunctionDeclaration */ && declaration.body)) && !ts.isInAmbientContext(declaration)) { return declaration; } } @@ -12200,7 +12293,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node.name); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - if (symbol.flags & 128 /* ValueModule */ && symbol.declarations.length > 1 && !isInAmbientContext(node)) { + if (symbol.flags & 128 /* ValueModule */ && symbol.declarations.length > 1 && !ts.isInAmbientContext(node)) { var classOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (classOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(classOrFunc)) { @@ -12502,7 +12595,7 @@ var ts; } function isTypeReferenceIdentifier(identifier) { var node = identifier; - while (node.parent && node.parent.kind === 112 /* QualifiedName */) + if (node.parent && node.parent.kind === 112 /* QualifiedName */) node = node.parent; return node.parent && node.parent.kind === 123 /* TypeReference */; } @@ -12566,9 +12659,18 @@ var ts; } return false; } + function isRightSideOfQualifiedName(node) { + return (node.parent.kind === 112 /* QualifiedName */ || node.parent.kind === 130 /* PropertyAccess */) && node.parent.right === node; + } function getSymbolOfIdentifier(identifier) { if (isExpression(identifier)) { - if (isRightSideOfQualifiedName()) { + if (isRightSideOfQualifiedName(identifier)) { + var node = identifier.parent; + var symbol = getNodeLinks(node).resolvedSymbol; + if (!symbol) { + checkPropertyAccess(node); + } + return getNodeLinks(node).resolvedSymbol; } return resolveEntityName(identifier, identifier, ts.SymbolFlags.Value); } @@ -12576,12 +12678,48 @@ var ts; return getSymbolOfNode(identifier.parent); } if (isTypeReferenceIdentifier(identifier)) { - var entityName = isRightSideOfQualifiedName() ? identifier.parent : identifier; + var entityName = isRightSideOfQualifiedName(identifier) ? identifier.parent : identifier; var meaning = entityName.parent.kind === 123 /* TypeReference */ ? ts.SymbolFlags.Type : ts.SymbolFlags.Namespace; return resolveEntityName(entityName, entityName, meaning); } - function isRightSideOfQualifiedName() { - return (identifier.parent.kind === 112 /* QualifiedName */ || identifier.parent.kind === 130 /* PropertyAccess */) && identifier.parent.right === identifier; + } + function getTypeOfExpression(node) { + if (isExpression(node)) { + while (isRightSideOfQualifiedName(node)) { + node = node.parent; + } + return getApparentType(checkExpression(node)); + } + return unknownType; + } + function getAugmentedPropertiesOfApparentType(type) { + var apparentType = getApparentType(type); + if (apparentType.flags & ts.TypeFlags.ObjectType) { + var propertiesByName = {}; + var results = []; + ts.forEach(getPropertiesOfType(apparentType), function (s) { + propertiesByName[s.name] = s; + results.push(s); + }); + var resolved = resolveObjectTypeMembers(type); + ts.forEachValue(resolved.members, function (s) { + if (symbolIsValue(s) && !propertiesByName[s.name]) { + propertiesByName[s.name] = s; + results.push(s); + } + }); + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (s) { + if (!propertiesByName[s.name]) { + propertiesByName[s.name] = s; + results.push(s); + } + }); + } + return results; + } + else { + return getPropertiesOfType(apparentType); } } function isExternalModuleSymbol(symbol) { @@ -12740,28 +12878,6 @@ var ts; globalRegExpType = getGlobalType("RegExp"); } initializeTypeChecker(); - checker = { - getProgram: function () { return program; }, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getNodeCount: function () { return ts.sum(program.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(program.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(program.getSourceFiles(), "symbolCount"); }, - getTypeCount: function () { return typeCount; }, - checkProgram: checkProgram, - emitFiles: invokeEmitter, - getSymbolOfNode: getSymbolOfNode, - getParentOfSymbol: getParentOfSymbol, - getTypeOfSymbol: getTypeOfSymbol, - getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, - getPropertiesOfType: getPropertiesOfType, - getSignaturesOfType: getSignaturesOfType, - getIndexTypeOfType: getIndexTypeOfType, - getReturnTypeOfSignature: getReturnTypeOfSignature, - resolveEntityName: resolveEntityName, - getSymbolsInScope: getSymbolsInScope, - getSymbolOfIdentifier: getSymbolOfIdentifier - }; return checker; } ts.createTypeChecker = createTypeChecker; @@ -12774,7 +12890,7 @@ var ts; "m": "module", "o": "out", "t": "target", - "v": "version", + "v": "version" }; var options = [ { name: "charset", type: "string" }, @@ -13031,7 +13147,8 @@ var ts; writeFile: writeFile, getCurrentDirectory: function () { return currentDirectory || (currentDirectory = sys.getCurrentDirectory()); }, useCaseSensitiveFileNames: function () { return sys.useCaseSensitiveFileNames; }, - getCanonicalFileName: ts.getCanonicalFileName + getCanonicalFileName: ts.getCanonicalFileName, + getNewLine: function () { return sys.newLine; } }; } function executeCommandLine(args) { diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js new file mode 100644 index 00000000000..f658770e030 --- /dev/null +++ b/bin/typescriptServices.js @@ -0,0 +1,31644 @@ +/*! ***************************************************************************** +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 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var ts; +(function (ts) { + ts.Diagnostics = { + Unknown_compiler_option_0: { code: 6001, category: 1 /* Error */, key: "Unknown compiler option '{0}'." }, + File_0_not_found: { code: 6002, category: 1 /* Error */, key: "File '{0}' not found." }, + File_0_must_have_extension_ts_or_d_ts: { code: 6003, category: 1 /* Error */, key: "File '{0}' must have extension '.ts' or '.d.ts'." }, + Unrecognized_escape_sequence: { code: 1000, category: 1 /* Error */, key: "Unrecognized escape sequence." }, + Unexpected_character_0: { code: 1001, category: 1 /* Error */, key: "Unexpected character {0}." }, + Missing_close_quote_character: { code: 1002, category: 1 /* Error */, key: "Missing close quote character." }, + Identifier_expected: { code: -9999999, category: 1 /* Error */, key: "Identifier expected." }, + _0_keyword_expected: { code: 1004, category: 1 /* Error */, key: "'{0}' keyword expected." }, + _0_expected: { code: -9999999, category: 1 /* Error */, key: "'{0}' expected." }, + Identifier_expected_0_is_a_keyword: { code: 1006, category: 1 /* Error */, key: "Identifier expected; '{0}' is a keyword." }, + Automatic_semicolon_insertion_not_allowed: { code: 1007, category: 1 /* Error */, key: "Automatic semicolon insertion not allowed." }, + Trailing_comma_not_allowed: { code: 1009, category: 1 /* Error */, key: "Trailing comma not allowed." }, + Asterisk_Slash_expected: { code: 1010, category: 1 /* Error */, key: "'*/' expected." }, + public_or_private_modifier_must_precede_static: { code: 1011, category: 1 /* Error */, key: "'public' or 'private' modifier must precede 'static'." }, + Unexpected_token: { code: 1012, category: 1 /* Error */, key: "Unexpected token." }, + Catch_clause_parameter_cannot_have_a_type_annotation: { code: 1013, category: 1 /* Error */, key: "Catch clause parameter cannot have a type annotation." }, + A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: 1 /* Error */, key: "A rest parameter must be last in a parameter list." }, + Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: 1 /* Error */, key: "Parameter cannot have question mark and initializer." }, + A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: 1 /* Error */, key: "A required parameter cannot follow an optional parameter." }, + An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: 1 /* Error */, key: "An index signature cannot have a rest parameter." }, + An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: 1 /* Error */, key: "An index signature parameter cannot have an accessibility modifier." }, + An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: 1 /* Error */, key: "An index signature parameter cannot have a question mark." }, + An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: 1 /* Error */, key: "An index signature parameter cannot have an initializer." }, + An_index_signature_must_have_a_type_annotation: { code: 1021, category: 1 /* Error */, key: "An index signature must have a type annotation." }, + An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: 1 /* Error */, key: "An index signature parameter must have a type annotation." }, + An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: 1 /* Error */, key: "An index signature parameter type must be 'string' or 'number'." }, + extends_clause_already_seen: { code: 1024, category: 1 /* Error */, key: "'extends' clause already seen." }, + extends_clause_must_precede_implements_clause: { code: 1025, category: 1 /* Error */, key: "'extends' clause must precede 'implements' clause." }, + Classes_can_only_extend_a_single_class: { code: 1026, category: 1 /* Error */, key: "Classes can only extend a single class." }, + implements_clause_already_seen: { code: 1027, category: 1 /* Error */, key: "'implements' clause already seen." }, + Accessibility_modifier_already_seen: { code: 1028, category: 1 /* Error */, key: "Accessibility modifier already seen." }, + _0_modifier_must_precede_1_modifier: { code: 1029, category: 1 /* Error */, key: "'{0}' modifier must precede '{1}' modifier." }, + _0_modifier_already_seen: { code: 1030, category: 1 /* Error */, key: "'{0}' modifier already seen." }, + _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: 1 /* Error */, key: "'{0}' modifier cannot appear on a class element." }, + Interface_declaration_cannot_have_implements_clause: { code: 1032, category: 1 /* Error */, key: "Interface declaration cannot have 'implements' clause." }, + super_invocation_cannot_have_type_arguments: { code: 1034, category: 1 /* Error */, key: "'super' invocation cannot have type arguments." }, + Only_ambient_modules_can_use_quoted_names: { code: 1035, category: 1 /* Error */, key: "Only ambient modules can use quoted names." }, + Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: 1 /* Error */, key: "Statements are not allowed in ambient contexts." }, + A_function_implementation_cannot_be_declared_in_an_ambient_context: { code: 1037, category: 1 /* Error */, key: "A function implementation cannot be declared in an ambient context." }, + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: 1 /* Error */, key: "A 'declare' modifier cannot be used in an already ambient context." }, + Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: 1 /* Error */, key: "Initializers are not allowed in ambient contexts." }, + _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: 1 /* Error */, key: "'{0}' modifier cannot appear on a module element." }, + A_declare_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: 1 /* Error */, key: "A 'declare' modifier cannot be used with an interface declaration." }, + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: 1 /* Error */, key: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, + A_rest_parameter_cannot_be_optional: { code: 1047, category: 1 /* Error */, key: "A rest parameter cannot be optional." }, + A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: 1 /* Error */, key: "A rest parameter cannot have an initializer." }, + A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: 1 /* Error */, key: "A 'set' accessor must have exactly one parameter." }, + A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: 1 /* Error */, key: "A 'set' accessor cannot have an optional parameter." }, + A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: 1 /* Error */, key: "A 'set' accessor parameter cannot have an initializer." }, + A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: 1 /* Error */, key: "A 'set' accessor cannot have rest parameter." }, + A_get_accessor_cannot_have_parameters: { code: 1054, category: 1 /* Error */, key: "A 'get' accessor cannot have parameters." }, + Modifiers_cannot_appear_here: { code: 1055, category: 1 /* Error */, key: "Modifiers cannot appear here." }, + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: 1 /* Error */, key: "Accessors are only available when targeting ECMAScript 5 and higher." }, + Enum_member_must_have_initializer: { code: -9999999, category: 1 /* Error */, key: "Enum member must have initializer." }, + An_export_assignment_cannot_be_used_in_an_internal_module: { code: 1063, category: 1 /* Error */, key: "An export assignment cannot be used in an internal module." }, + Ambient_enum_elements_can_only_have_integer_literal_initializers: { code: 1066, category: 1 /* Error */, key: "Ambient enum elements can only have integer literal initializers." }, + module_class_interface_enum_import_or_statement: { code: 1067, category: 3 /* NoPrefix */, key: "module, class, interface, enum, import or statement" }, + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: 1 /* Error */, key: "Unexpected token. A constructor, method, accessor, or property was expected." }, + statement: { code: 1069, category: 3 /* NoPrefix */, key: "statement" }, + case_or_default_clause: { code: 1070, category: 3 /* NoPrefix */, key: "case or default clause" }, + identifier: { code: 1071, category: 3 /* NoPrefix */, key: "identifier" }, + call_construct_index_property_or_function_signature: { code: 1072, category: 3 /* NoPrefix */, key: "call, construct, index, property or function signature" }, + expression: { code: 1073, category: 3 /* NoPrefix */, key: "expression" }, + type_name: { code: 1074, category: 3 /* NoPrefix */, key: "type name" }, + property_or_accessor: { code: 1075, category: 3 /* NoPrefix */, key: "property or accessor" }, + parameter: { code: 1076, category: 3 /* NoPrefix */, key: "parameter" }, + type: { code: 1077, category: 3 /* NoPrefix */, key: "type" }, + type_parameter: { code: 1078, category: 3 /* NoPrefix */, key: "type parameter" }, + A_declare_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: 1 /* Error */, key: "A 'declare' modifier cannot be used with an import declaration." }, + Invalid_reference_directive_syntax: { code: 1084, category: 1 /* Error */, key: "Invalid 'reference' directive syntax." }, + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: 1 /* Error */, key: "Octal literals are not available when targeting ECMAScript 5 and higher." }, + An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: 1 /* Error */, key: "An accessor cannot be declared in an ambient context." }, + _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: 1 /* Error */, key: "'{0}' modifier cannot appear on a constructor declaration." }, + _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: 1 /* Error */, key: "'{0}' modifier cannot appear on a parameter." }, + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: 1 /* Error */, key: "Only a single variable declaration is allowed in a 'for...in' statement." }, + Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: 1 /* Error */, key: "Type parameters cannot appear on a constructor declaration." }, + Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: 1 /* Error */, key: "Type annotation cannot appear on a constructor declaration." }, + An_accessor_cannot_have_type_parameters: { code: 1094, category: 1 /* Error */, key: "An accessor cannot have type parameters." }, + A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: 1 /* Error */, key: "A 'set' accessor cannot have a return type annotation." }, + An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: 1 /* Error */, key: "An index signature must have exactly one parameter." }, + _0_list_cannot_be_empty: { code: 1097, category: 1 /* Error */, key: "'{0}' list cannot be empty." }, + Type_parameter_list_cannot_be_empty: { code: 1098, category: 1 /* Error */, key: "Type parameter list cannot be empty." }, + Type_argument_list_cannot_be_empty: { code: 1099, category: 1 /* Error */, key: "Type argument list cannot be empty." }, + Invalid_use_of_0_in_strict_mode: { code: 1100, category: 1 /* Error */, key: "Invalid use of '{0}' in strict mode." }, + with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: 1 /* Error */, key: "'with' statements are not allowed in strict mode." }, + delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: 1 /* Error */, key: "'delete' cannot be called on an identifier in strict mode." }, + Invalid_left_hand_side_in_for_in_statement: { code: 1103, category: 1 /* Error */, key: "Invalid left-hand side in 'for...in' statement." }, + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: 1 /* Error */, key: "A 'continue' statement can only be used within an enclosing iteration statement." }, + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: 1 /* Error */, key: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, + Jump_target_cannot_cross_function_boundary: { code: 1107, category: 1 /* Error */, key: "Jump target cannot cross function boundary." }, + A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: 1 /* Error */, key: "A 'return' statement can only be used within a function body." }, + Expression_expected: { code: -9999999, category: 1 /* Error */, key: "Expression expected." }, + Type_expected: { code: -9999999, category: 1 /* Error */, key: "Type expected." }, + A_constructor_implementation_cannot_be_declared_in_an_ambient_context: { code: 1111, category: 1 /* Error */, key: "A constructor implementation cannot be declared in an ambient context." }, + A_class_member_cannot_be_declared_optional: { code: 1112, category: 1 /* Error */, key: "A class member cannot be declared optional." }, + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: 1 /* Error */, key: "A 'default' clause cannot appear more than once in a 'switch' statement." }, + Duplicate_label_0: { code: 1114, category: 1 /* Error */, key: "Duplicate label '{0}'" }, + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: 1 /* Error */, key: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: 1 /* Error */, key: "A 'break' statement can only jump to a label of an enclosing statement." }, + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: 1 /* Error */, key: "An object literal cannot have multiple properties with the same name in strict mode." }, + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: 1 /* Error */, key: "An object literal cannot have multiple get/set accessors with the same name." }, + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: 1 /* Error */, key: "An object literal cannot have property and accessor with the same name." }, + An_export_assignment_cannot_have_modifiers: { code: 1120, category: 1 /* Error */, key: "An export assignment cannot have modifiers." }, + Duplicate_identifier_0: { code: 2000, category: 1 /* Error */, key: "Duplicate identifier '{0}'." }, + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 2068, category: 1 /* Error */, key: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, + Multiple_constructor_implementations_are_not_allowed: { code: 2070, category: 1 /* Error */, key: "Multiple constructor implementations are not allowed." }, + A_class_may_only_implement_another_class_or_interface: { code: 2074, category: 1 /* Error */, key: "A class may only implement another class or interface." }, + get_and_set_accessor_must_have_the_same_type: { code: 2096, category: 1 /* Error */, key: "'get' and 'set' accessor must have the same type." }, + Static_members_cannot_reference_class_type_parameters: { code: 2099, category: 1 /* Error */, key: "Static members cannot reference class type parameters." }, + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2102, category: 1 /* Error */, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class" }, + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2112, category: 1 /* Error */, key: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2113, category: 1 /* Error */, key: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2114, category: 1 /* Error */, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2115, category: 1 /* Error */, key: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2116, category: 1 /* Error */, key: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2117, category: 1 /* Error */, key: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: { code: 2118, category: 1 /* Error */, key: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'." }, + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2119, category: 1 /* Error */, key: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, + A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2126, category: 1 /* Error */, key: "A 'get' accessor must return a value or consist of a single 'throw' statement." }, + Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2127, category: 1 /* Error */, key: "Getter and setter accessors do not agree in visibility." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2131, 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." }, + Untyped_function_calls_may_not_accept_type_arguments: { code: 2158, category: 1 /* Error */, key: "Untyped function calls may not accept type arguments." }, + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2120, category: 1 /* Error */, key: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2121, category: 1 /* Error */, key: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, + Setters_cannot_return_a_value: { code: 2122, category: 1 /* Error */, key: "Setters cannot return a value." }, + Invalid_left_hand_side_of_assignment_expression: { code: 2130, category: 1 /* Error */, key: "Invalid left-hand side of assignment expression." }, + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2134, category: 1 /* Error */, key: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, + All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2135, category: 1 /* Error */, key: "All symbols within a 'with' block will be resolved to 'any'." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2139, category: 1 /* Error */, key: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + Overload_signatures_must_all_be_public_or_private: { code: 2150, category: 1 /* Error */, key: "Overload signatures must all be public or private." }, + Overload_signatures_must_all_be_exported_or_not_exported: { code: 2151, category: 1 /* Error */, key: "Overload signatures must all be exported or not exported." }, + Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2152, category: 1 /* Error */, key: "Overload signatures must all be ambient or non-ambient." }, + Overload_signatures_must_all_be_optional_or_required: { code: 2153, category: 1 /* Error */, key: "Overload signatures must all be optional or required." }, + this_cannot_be_referenced_in_constructor_arguments: { code: 2155, category: 1 /* Error */, key: "'this' cannot be referenced in constructor arguments." }, + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2161, category: 1 /* Error */, key: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, + A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2163, category: 1 /* Error */, key: "A signature with an implementation cannot use a string literal type." }, + Interface_0_cannot_simultaneously_extend_types_1_and_2_Colon: { code: 2189, category: 1 /* Error */, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':" }, + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2190, category: 1 /* Error */, key: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2192, category: 1 /* Error */, key: "Individual declarations in merged declaration {0} must be all exported or all local." }, + super_cannot_be_referenced_in_constructor_arguments: { code: 2193, category: 1 /* Error */, key: "'super' cannot be referenced in constructor arguments." }, + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2194, category: 1 /* Error */, key: "Return type of constructor signature must be assignable to the instance type of the class" }, + Ambient_external_module_declaration_cannot_specify_relative_module_name: { code: 2196, category: 1 /* Error */, key: "Ambient external module declaration cannot specify relative module name." }, + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: { code: 2197, category: 1 /* Error */, key: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name." }, + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2200, category: 1 /* Error */, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2205, category: 1 /* Error */, key: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2206, category: 1 /* Error */, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2207, category: 1 /* Error */, key: "Expression resolves to '_super' that compiler uses to capture base class reference." }, + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: { code: 2224, category: 1 /* Error */, key: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter." }, + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2225, category: 1 /* Error */, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2229, category: 1 /* Error */, key: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2230, category: 1 /* Error */, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, + Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2231, category: 1 /* Error */, key: "Parameter '{0}' cannot be referenced in its initializer." }, + Duplicate_string_index_signature: { code: 2232, category: 1 /* Error */, key: "Duplicate string index signature." }, + Duplicate_number_index_signature: { code: 2233, category: 1 /* Error */, key: "Duplicate number index signature." }, + All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2234, category: 1 /* Error */, key: "All declarations of an interface must have identical type parameters." }, + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: { code: 2235, category: 1 /* Error */, key: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter." }, + Function_implementation_name_must_be_0: { code: 2239, category: 1 /* Error */, key: "Function implementation name must be '{0}'." }, + Constructor_implementation_is_missing: { code: 2240, category: 1 /* Error */, key: "Constructor implementation is missing." }, + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2245, category: 1 /* Error */, key: "An export assignment cannot be used in a module with other exported elements." }, + A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2246, category: 1 /* Error */, key: "A parameter property is only allowed in a constructor implementation." }, + Function_overload_must_be_static: { code: 2247, category: 1 /* Error */, key: "Function overload must be static." }, + Function_overload_must_not_be_static: { code: 2248, category: 1 /* Error */, key: "Function overload must not be static." }, + Circular_definition_of_import_alias_0: { code: 3000, category: 1 /* Error */, key: "Circular definition of import alias '{0}'." }, + Cannot_find_name_0: { code: 3001, category: 1 /* Error */, key: "Cannot find name '{0}'." }, + Module_0_has_no_exported_member_1: { code: 3002, category: 1 /* Error */, key: "Module '{0}' has no exported member '{1}'." }, + Cannot_find_external_module_0: { code: 3003, category: 1 /* Error */, key: "Cannot find external module '{0}'." }, + A_module_cannot_have_more_than_one_export_assignment: { code: 3004, category: 1 /* Error */, key: "A module cannot have more than one export assignment." }, + Type_0_recursively_references_itself_as_a_base_type: { code: 3005, category: 1 /* Error */, key: "Type '{0}' recursively references itself as a base type." }, + A_class_may_only_extend_another_class: { code: 3006, category: 1 /* Error */, key: "A class may only extend another class." }, + An_interface_may_only_extend_a_class_or_another_interface: { code: 3007, category: 1 /* Error */, key: "An interface may only extend a class or another interface." }, + Generic_type_0_requires_1_type_argument_s: { code: 3008, category: 1 /* Error */, key: "Generic type '{0}' requires {1} type argument(s)." }, + Type_0_is_not_generic: { code: 3009, category: 1 /* Error */, key: "Type '{0}' is not generic." }, + Cannot_find_global_type_0: { code: 3010, category: 1 /* Error */, key: "Cannot find global type '{0}'." }, + Global_type_0_must_be_a_class_or_interface_type: { code: 3011, category: 1 /* Error */, key: "Global type '{0}' must be a class or interface type." }, + Global_type_0_must_have_1_type_parameter_s: { code: 3012, category: 1 /* Error */, key: "Global type '{0}' must have {1} type parameter(s)." }, + this_cannot_be_referenced_in_a_module_body: { code: 3013, category: 1 /* Error */, key: "'this' cannot be referenced in a module body." }, + this_cannot_be_referenced_in_a_static_property_initializer: { code: 3014, category: 1 /* Error */, key: "'this' cannot be referenced in a static property initializer." }, + this_cannot_be_referenced_in_current_location: { code: -9999999, category: 1 /* Error */, key: "'this' cannot be referenced in current location." }, + super_can_only_be_referenced_in_a_derived_class: { code: 3015, category: 1 /* Error */, key: "'super' can only be referenced in a derived class." }, + Property_0_does_not_exist_on_type_1: { code: 3017, category: 1 /* Error */, key: "Property '{0}' does not exist on type '{1}'." }, + An_index_expression_argument_must_be_of_type_string_number_or_any: { code: 3018, 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: 3019, category: 1 /* Error */, key: "Type '{0}' does not satisfy the constraint '{1}':" }, + Type_0_does_not_satisfy_the_constraint_1: { code: 3019, category: 1 /* Error */, key: "Type '{0}' does not satisfy the constraint '{1}'." }, + Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 3020, category: 1 /* Error */, key: "Supplied parameters do not match any signature of call target." }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 3021, category: 1 /* Error */, key: "Cannot invoke an expression whose type lacks a call signature." }, + Only_a_void_function_can_be_called_with_the_new_keyword: { code: 3022, 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: 3023, 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_Colon: { code: 3024, 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: { code: 3024, category: 1 /* Error */, key: "Neither type '{0}' nor type '{1}' is assignable to the other." }, + No_best_common_type_exists_among_return_expressions: { code: 3027, category: 1 /* Error */, key: "No best common type exists among return expressions." }, + Operator_0_cannot_be_applied_to_types_1_and_2: { code: 3028, category: 1 /* Error */, key: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, + No_best_common_type_exists_between_0_and_1: { code: 3029, category: 1 /* Error */, key: "No best common type exists between '{0}' and '{1}'." }, + No_best_common_type_exists_between_0_1_and_2: { code: 3030, category: 1 /* Error */, key: "No best common type exists between '{0}', '{1}', and '{2}'." }, + A_rest_parameter_must_be_of_an_array_type: { code: 3031, category: 1 /* Error */, key: "A rest parameter must be of an array type." }, + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 3032, category: 1 /* Error */, key: "A parameter initializer is only allowed in a function or constructor implementation." }, + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 3033, category: 1 /* Error */, key: "Specialized overload signature is not assignable to any non-specialized signature." }, + Duplicate_function_implementation: { code: 3034, category: 1 /* Error */, key: "Duplicate function implementation." }, + Overload_signature_is_not_compatible_with_function_implementation: { code: 3035, category: 1 /* Error */, key: "Overload signature is not compatible with function implementation." }, + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 3036, category: 1 /* Error */, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, + Index_signature_is_missing_in_type_0: { code: 4003, category: 1 /* Error */, key: "Index signature is missing in type '{0}'." }, + Index_signatures_are_incompatible_Colon: { code: 4004, category: 1 /* Error */, key: "Index signatures are incompatible:" }, + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 4016, category: 3 /* NoPrefix */, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 4017, category: 3 /* NoPrefix */, key: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 4018, category: 3 /* NoPrefix */, 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: 4019, category: 3 /* NoPrefix */, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 4024, category: 1 /* Error */, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, + Named_properties_0_of_types_1_and_2_are_not_identical: { code: 4032, category: 3 /* NoPrefix */, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." }, + Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: 1 /* Error */, key: "Cannot find the common subdirectory path for the input files." }, + Cannot_read_file_0_Colon_1: { code: 5012, category: 1 /* Error */, key: "Cannot read file '{0}': {1}" }, + Unsupported_file_encoding: { code: 5013, category: 3 /* NoPrefix */, key: "Unsupported file encoding." }, + Could_not_write_file_0_Colon_1: { code: 5033, category: 1 /* Error */, key: "Could not write file '{0}': {1}" }, + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, + Version_0: { code: 6029, category: 2 /* Message */, key: "Version {0}" }, + Variable_0_implicitly_has_an_1_type: { code: 7005, category: 1 /* Error */, key: "Variable '{0}' implicitly has an '{1}' type." }, + Parameter_0_implicitly_has_an_1_type: { code: 7006, category: 1 /* Error */, key: "Parameter '{0}' implicitly has an '{1}' type." }, + Member_0_implicitly_has_an_1_type: { code: 7008, category: 1 /* Error */, key: "Member '{0}' implicitly has an '{1}' type." }, + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: 1 /* Error */, key: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: 1 /* Error */, key: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: 1 /* Error */, key: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: 1 /* Error */, key: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Lambda_function_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7014, category: 1 /* Error */, key: "Lambda function, which lacks return-type annotation, implicitly has an '{0}' return type." }, + Array_literal_implicitly_has_an_0_type: { code: 7015, category: 1 /* Error */, key: "Array literal implicitly has an '{0}' type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: 1 /* Error */, key: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, + Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: 1 /* Error */, key: "Index signature of object type implicitly has an 'any' type." }, + Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: 1 /* Error */, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, + Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: 1 /* Error */, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: 1 /* Error */, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Variable_declaration_list_cannot_be_empty: { code: -9999999, category: 1 /* Error */, key: "Variable declaration list cannot be empty." }, + Digit_expected: { code: -9999999, category: 1 /* Error */, key: "Digit expected." }, + Hexadecimal_digit_expected: { code: -9999999, category: 1 /* Error */, key: "Hexadecimal digit expected." }, + Unexpected_end_of_text: { code: -9999999, category: 1 /* Error */, key: "Unexpected end of text." }, + Unterminated_string_constant: { code: -9999999, category: 1 /* Error */, key: "Unterminated string constant." }, + Invalid_character: { code: -9999999, category: 1 /* Error */, key: "Invalid character." }, + Declaration_or_statement_expected: { code: -9999999, category: 1 /* Error */, key: "Declaration or statement expected." }, + Statement_expected: { code: -9999999, category: 1 /* Error */, key: "Statement expected." }, + case_or_default_expected: { code: -9999999, category: 1 /* Error */, key: "'case' or 'default' expected." }, + Property_or_signature_expected: { code: -9999999, category: 1 /* Error */, key: "Property or signature expected." }, + Enum_member_expected: { code: -9999999, category: 1 /* Error */, key: "Enum member expected." }, + Type_reference_expected: { code: -9999999, category: 1 /* Error */, key: "Type reference expected." }, + Variable_declaration_expected: { code: -9999999, category: 1 /* Error */, key: "Variable declaration expected." }, + Argument_expression_expected: { code: -9999999, category: 1 /* Error */, key: "Argument expression expected." }, + Property_assignment_expected: { code: -9999999, category: 1 /* Error */, key: "Property assignment expected." }, + Expression_or_comma_expected: { code: -9999999, category: 1 /* Error */, key: "Expression or comma expected." }, + Parameter_declaration_expected: { code: -9999999, category: 1 /* Error */, key: "Parameter declaration expected." }, + Type_parameter_declaration_expected: { code: -9999999, category: 1 /* Error */, key: "Type parameter declaration expected." }, + Type_argument_expected: { code: -9999999, category: 1 /* Error */, key: "Type argument expected." }, + String_literal_expected: { code: -9999999, category: 1 /* Error */, key: "String literal expected." }, + not_preceded_by_parameter_list: { code: -9999999, category: 1 /* Error */, key: "'=>' not preceded by parameter list." }, + Invalid_assignment_target: { code: -9999999, category: 1 /* Error */, key: "Invalid assignment target." }, + super_must_be_followed_by_argument_list_or_member_access: { code: -9999999, category: 1 /* Error */, key: "'super' must be followed by argument list or member access." }, + Line_break_not_permitted_here: { code: -9999999, category: 1 /* Error */, key: "Line break not permitted here." }, + catch_or_finally_expected: { code: -9999999, category: 1 /* Error */, key: "'catch' or 'finally' expected." }, + Block_or_expected: { code: -9999999, category: 1 /* Error */, key: "Block or ';' expected." }, + Modifiers_not_permitted_on_index_signature_members: { code: -9999999, category: 1 /* Error */, key: "Modifiers not permitted on index signature members." }, + Class_member_declaration_expected: { code: -9999999, category: 1 /* Error */, key: "Class member declaration expected." }, + Declaration_expected: { code: -9999999, category: 1 /* Error */, key: "Declaration expected." }, + Invalid_reference_comment: { code: -9999999, category: 1 /* Error */, key: "Invalid reference comment." }, + File_0_is_not_an_external_module: { code: -9999999, category: 1 /* Error */, key: "File '{0}' is not an external module." }, + Excessive_stack_depth_comparing_types_0_and_1: { code: -9999999, category: 1 /* Error */, key: "Excessive stack depth comparing types '{0}' and '{1}'." }, + Type_0_is_not_assignable_to_type_1_Colon: { code: -9999999, category: 1 /* Error */, key: "Type '{0}' is not assignable to type '{1}':" }, + Type_0_is_not_assignable_to_type_1: { code: -9999999, category: 1 /* Error */, key: "Type '{0}' is not assignable to type '{1}'." }, + Property_0_is_missing_in_type_1: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' is missing in type '{1}'." }, + Private_property_0_cannot_be_reimplemented: { code: -9999999, category: 1 /* Error */, key: "Private property '{0}' cannot be reimplemented." }, + Required_property_0_cannot_be_reimplemented_with_optional_property_in_1: { code: 2012, category: 1 /* Error */, key: "Required property '{0}' cannot be reimplemented with optional property in '{1}'." }, + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: -9999999, category: 1 /* Error */, key: "Super calls are not permitted outside constructors or in nested functions inside constructors" }, + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: -9999999, category: 1 /* Error */, key: "Only public methods of the base class are accessible via the 'super' keyword" }, + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: -9999999, category: 1 /* Error */, key: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, + Constructors_for_derived_classes_must_contain_a_super_call: { code: -9999999, category: 1 /* Error */, key: "Constructors for derived classes must contain a 'super' call." }, + Import_name_cannot_be_0: { code: -9999999, category: 1 /* Error */, key: "Import name cannot be '{0}'" }, + Type_parameter_name_cannot_be_0: { code: -9999999, category: 1 /* Error */, key: "Type parameter name cannot be '{0}'" }, + Class_name_cannot_be_0: { code: -9999999, category: 1 /* Error */, key: "Class name cannot be '{0}'" }, + Interface_name_cannot_be_0: { code: -9999999, category: 1 /* Error */, key: "Interface name cannot be '{0}'" }, + Enum_name_cannot_be_0: { code: -9999999, category: 1 /* Error */, key: "Enum name cannot be '{0}'" }, + Types_of_property_0_are_incompatible_Colon: { code: -9999999, category: 1 /* Error */, key: "Types of property '{0}' are incompatible:" }, + Types_of_parameters_0_and_1_are_incompatible_Colon: { code: -9999999, category: 1 /* Error */, key: "Types of parameters '{0}' and '{1}' are incompatible:" }, + Unknown_identifier_0: { code: -9999999, category: 1 /* Error */, key: "Unknown identifier '{0}'." }, + Property_0_is_inaccessible: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' is inaccessible." }, + Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: -9999999, category: 1 /* Error */, key: "Function implementation is missing or not immediately following the declaration." }, + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: -9999999, category: 1 /* Error */, key: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: -9999999, category: 1 /* Error */, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, + Class_0_incorrectly_extends_base_class_1_Colon: { code: -9999999, category: 1 /* Error */, key: "Class '{0}' incorrectly extends base class '{1}':" }, + Class_0_incorrectly_extends_base_class_1: { code: -9999999, category: 1 /* Error */, key: "Class '{0}' incorrectly extends base class '{1}'." }, + Class_static_side_0_incorrectly_extends_base_class_static_side_1_Colon: { code: -9999999, 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: { code: -9999999, 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: -9999999, category: 1 /* Error */, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, + Class_0_incorrectly_implements_interface_1_Colon: { code: -9999999, category: 1 /* Error */, key: "Class '{0}' incorrectly implements interface '{1}':" }, + Class_0_incorrectly_implements_interface_1: { code: -9999999, category: 1 /* Error */, key: "Class '{0}' incorrectly implements interface '{1}'." }, + Interface_0_incorrectly_extends_interface_1_Colon: { code: -9999999, category: 1 /* Error */, key: "Interface '{0}' incorrectly extends interface '{1}':" }, + Interface_0_incorrectly_extends_interface_1: { code: -9999999, category: 1 /* Error */, key: "Interface '{0}' incorrectly extends interface '{1}'." }, + Ambient_external_modules_cannot_be_nested_in_other_modules: { code: -9999999, category: 1 /* Error */, key: "Ambient external modules cannot be nested in other modules." }, + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { code: -9999999, category: 1 /* Error */, key: "Import declarations in an internal module cannot reference an external module." }, + A_module_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: -9999999, category: 1 /* Error */, key: "A module declaration cannot be in a different file from a class or function with which it is merged" }, + A_module_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: -9999999, category: 1 /* Error */, key: "A module declaration cannot be located prior to a class or function with which it is merged" }, + Cannot_compile_external_modules_unless_the_module_flag_is_provided: { code: -9999999, category: 1 /* Error */, key: "Cannot compile external modules unless the '--module' flag is provided." }, + Import_declaration_conflicts_with_local_declaration_of_0: { code: -9999999, category: 1 /* Error */, key: "Import declaration conflicts with local declaration of '{0}'" }, + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: -9999999, category: 1 /* Error */, key: "Module '{0}' is hidden by a local declaration with the same name" }, + Filename_0_differs_from_already_included_filename_1_only_in_casing: { code: -9999999, category: 1 /* Error */, key: "Filename '{0}' differs from already included filename '{1}' only in casing" }, + Argument_for_module_option_must_be_commonjs_or_amd: { code: -9999999, category: 1 /* Error */, key: "Argument for '--module' option must be 'commonjs' or 'amd'." }, + Argument_for_target_option_must_be_es3_or_es5: { code: -9999999, category: 1 /* Error */, key: "Argument for '--target' option must be 'es3' or 'es5'." }, + Compiler_option_0_expects_an_argument: { code: -9999999, category: 1 /* Error */, key: "Compiler option '{0}' expects an argument." }, + Unterminated_quoted_string_in_response_file_0: { code: -9999999, category: 1 /* Error */, key: "Unterminated quoted string in response file '{0}'." }, + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: -9999999, category: 1 /* Error */, key: "Locale must be of the form or -. For example '{0}' or '{1}'." }, + Unsupported_locale_0: { code: -9999999, category: 1 /* Error */, key: "Unsupported locale {0}." }, + Unable_to_open_file_0: { code: -9999999, category: 1 /* Error */, key: "Unable to open file {0}." }, + Corrupted_locale_file_0: { code: -9999999, category: 1 /* Error */, key: "Corrupted locale file {0}." }, + No_input_files_specified: { code: -9999999, category: 1 /* Error */, key: "No input files specified." } + }; +})(ts || (ts = {})); +var ts; +(function (ts) { + var textToToken = { + "any": 101 /* AnyKeyword */, + "boolean": 102 /* BooleanKeyword */, + "break": 56 /* BreakKeyword */, + "case": 57 /* CaseKeyword */, + "catch": 58 /* CatchKeyword */, + "class": 59 /* ClassKeyword */, + "continue": 61 /* ContinueKeyword */, + "const": 60 /* ConstKeyword */, + "constructor": 103 /* ConstructorKeyword */, + "debugger": 62 /* DebuggerKeyword */, + "declare": 104 /* DeclareKeyword */, + "default": 63 /* DefaultKeyword */, + "delete": 64 /* DeleteKeyword */, + "do": 65 /* DoKeyword */, + "else": 66 /* ElseKeyword */, + "enum": 67 /* EnumKeyword */, + "export": 68 /* ExportKeyword */, + "extends": 69 /* ExtendsKeyword */, + "false": 70 /* FalseKeyword */, + "finally": 71 /* FinallyKeyword */, + "for": 72 /* ForKeyword */, + "function": 73 /* FunctionKeyword */, + "get": 105 /* GetKeyword */, + "if": 74 /* IfKeyword */, + "implements": 92 /* ImplementsKeyword */, + "import": 75 /* ImportKeyword */, + "in": 76 /* InKeyword */, + "instanceof": 77 /* InstanceOfKeyword */, + "interface": 93 /* InterfaceKeyword */, + "let": 94 /* LetKeyword */, + "module": 106 /* ModuleKeyword */, + "new": 78 /* NewKeyword */, + "null": 79 /* NullKeyword */, + "number": 108 /* NumberKeyword */, + "package": 95 /* PackageKeyword */, + "private": 96 /* PrivateKeyword */, + "protected": 97 /* ProtectedKeyword */, + "public": 98 /* PublicKeyword */, + "require": 107 /* RequireKeyword */, + "return": 80 /* ReturnKeyword */, + "set": 109 /* SetKeyword */, + "static": 99 /* StaticKeyword */, + "string": 110 /* StringKeyword */, + "super": 81 /* SuperKeyword */, + "switch": 82 /* SwitchKeyword */, + "this": 83 /* ThisKeyword */, + "throw": 84 /* ThrowKeyword */, + "true": 85 /* TrueKeyword */, + "try": 86 /* TryKeyword */, + "typeof": 87 /* TypeOfKeyword */, + "var": 88 /* VarKeyword */, + "void": 89 /* VoidKeyword */, + "while": 90 /* WhileKeyword */, + "with": 91 /* WithKeyword */, + "yield": 100 /* YieldKeyword */, + "{": 5 /* OpenBraceToken */, + "}": 6 /* CloseBraceToken */, + "(": 7 /* OpenParenToken */, + ")": 8 /* CloseParenToken */, + "[": 9 /* OpenBracketToken */, + "]": 10 /* CloseBracketToken */, + ".": 11 /* DotToken */, + "...": 12 /* DotDotDotToken */, + ";": 13 /* SemicolonToken */, + ",": 14 /* CommaToken */, + "<": 15 /* LessThanToken */, + ">": 16 /* GreaterThanToken */, + "<=": 17 /* LessThanEqualsToken */, + ">=": 18 /* GreaterThanEqualsToken */, + "==": 19 /* EqualsEqualsToken */, + "!=": 20 /* ExclamationEqualsToken */, + "===": 21 /* EqualsEqualsEqualsToken */, + "!==": 22 /* ExclamationEqualsEqualsToken */, + "=>": 23 /* EqualsGreaterThanToken */, + "+": 24 /* PlusToken */, + "-": 25 /* MinusToken */, + "*": 26 /* AsteriskToken */, + "/": 27 /* SlashToken */, + "%": 28 /* PercentToken */, + "++": 29 /* PlusPlusToken */, + "--": 30 /* MinusMinusToken */, + "<<": 31 /* LessThanLessThanToken */, + ">>": 32 /* GreaterThanGreaterThanToken */, + ">>>": 33 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 34 /* AmpersandToken */, + "|": 35 /* BarToken */, + "^": 36 /* CaretToken */, + "!": 37 /* ExclamationToken */, + "~": 38 /* TildeToken */, + "&&": 39 /* AmpersandAmpersandToken */, + "||": 40 /* BarBarToken */, + "?": 41 /* QuestionToken */, + ":": 42 /* ColonToken */, + "=": 43 /* EqualsToken */, + "+=": 44 /* PlusEqualsToken */, + "-=": 45 /* MinusEqualsToken */, + "*=": 46 /* AsteriskEqualsToken */, + "/=": 47 /* SlashEqualsToken */, + "%=": 48 /* PercentEqualsToken */, + "<<=": 49 /* LessThanLessThanEqualsToken */, + ">>=": 50 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 51 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 52 /* AmpersandEqualsToken */, + "|=": 53 /* BarEqualsToken */, + "^=": 54 /* CaretEqualsToken */ + }; + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + function lookupInUnicodeMap(code, map) { + if (code < map[0]) { + return false; + } + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion === 0 /* ES3 */ ? lookupInUnicodeMap(code, unicodeES3IdentifierStart) : lookupInUnicodeMap(code, unicodeES5IdentifierStart); + } + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion === 0 /* ES3 */ ? lookupInUnicodeMap(code, unicodeES3IdentifierPart) : lookupInUnicodeMap(code, unicodeES5IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + for (var name in source) { + if (source.hasOwnProperty(name)) { + result[source[name]] = name; + } + } + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + function getLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + switch (text.charCodeAt(pos++)) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + } + } + result.push(lineStart); + return result; + } + ts.getLineStarts = getLineStarts; + function getLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + return { + line: lineNumber + 1, + character: position - lineStarts[lineNumber] + 1 + }; + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + function positionToLineAndCharacter(text, pos) { + var lineStarts = getLineStarts(text); + return getLineAndCharacterOfPosition(lineStarts, pos); + } + ts.positionToLineAndCharacter = positionToLineAndCharacter; + var hasOwnProperty = Object.prototype.hasOwnProperty; + function isWhiteSpace(ch) { + return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */; + } + function isLineBreak(ch) { + return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */; + } + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + function skipTrivia(text, pos, stopAfterLineBreak) { + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) + pos++; + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) + return pos; + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch) || isLineBreak(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + function createScanner(languageVersion, text, onError, onComment) { + var pos; + var len; + var startPos; + var tokenPos; + var token; + var tokenValue; + var precedingLineBreak; + function error(message) { + if (onError) + onError(message); + } + function isIdentifierStart(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch === 36 /* $ */ || ch === 95 /* _ */ || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + function isIdentifierPart(ch) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + function scanNumber() { + var start = pos; + while (isDigit(text.charCodeAt(pos))) + pos++; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + while (isDigit(text.charCodeAt(pos))) + pos++; + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + if (isDigit(text.charCodeAt(pos))) { + pos++; + while (isDigit(text.charCodeAt(pos))) + pos++; + end = pos; + } + else { + error(ts.Diagnostics.Digit_expected); + } + } + return +(text.substring(start, end)); + } + function scanHexDigits(count, exact) { + var digits = 0; + var value = 0; + while (digits < count || !exact) { + var ch = text.charCodeAt(pos); + if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { + value = value * 16 + ch - 48 /* _0 */; + } + else if (ch >= 65 /* A */ && ch <= 70 /* F */) { + value = value * 16 + ch - 65 /* A */ + 10; + } + else if (ch >= 97 /* a */ && ch <= 102 /* f */) { + value = value * 16 + ch - 97 /* a */ + 10; + } + else { + break; + } + pos++; + digits++; + } + if (digits < count) { + value = -1; + } + return value; + } + function scanString() { + var quote = text.charCodeAt(pos++); + var result = ""; + var start = pos; + while (true) { + if (pos >= len) { + result += text.substring(start, pos); + error(ts.Diagnostics.Unexpected_end_of_text); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */) { + result += text.substring(start, pos); + pos++; + if (pos >= len) { + error(ts.Diagnostics.Unexpected_end_of_text); + break; + } + ch = text.charCodeAt(pos++); + switch (ch) { + case 48 /* _0 */: + result += "\0"; + break; + case 98 /* b */: + result += "\b"; + break; + case 116 /* t */: + result += "\t"; + break; + case 110 /* n */: + result += "\n"; + break; + case 118 /* v */: + result += "\v"; + break; + case 102 /* f */: + result += "\f"; + break; + case 114 /* r */: + result += "\r"; + break; + case 39 /* singleQuote */: + result += "\'"; + break; + case 34 /* doubleQuote */: + result += "\""; + break; + case 120 /* x */: + case 117 /* u */: + var ch = scanHexDigits(ch === 120 /* x */ ? 2 : 4, true); + if (ch >= 0) { + result += String.fromCharCode(ch); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + } + break; + case 13 /* carriageReturn */: + if (pos < len && text.charCodeAt(pos) === 10 /* lineFeed */) + pos++; + break; + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + break; + default: + result += String.fromCharCode(ch); + } + start = pos; + continue; + } + if (isLineBreak(ch)) { + result += text.substring(start, pos); + error(ts.Diagnostics.Unterminated_string_constant); + break; + } + pos++; + } + return result; + } + function peekUnicodeEscape() { + if (pos + 5 < len && text.charCodeAt(pos + 1) === 117 /* u */) { + var start = pos; + pos += 2; + var value = scanHexDigits(4, true); + pos = start; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < len) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */ && hasOwnProperty.call(textToToken, tokenValue)) { + return token = textToToken[tokenValue]; + } + } + return token = 55 /* Identifier */; + } + function scan() { + startPos = pos; + precedingLineBreak = false; + while (true) { + tokenPos = pos; + if (pos >= len) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + precedingLineBreak = true; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 22 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 20 /* ExclamationEqualsToken */; + } + return pos++, token = 37 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 3 /* StringLiteral */; + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 48 /* PercentEqualsToken */; + } + return pos++, token = 28 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 39 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 52 /* AmpersandEqualsToken */; + } + return pos++, token = 34 /* AmpersandToken */; + case 40 /* openParen */: + return pos++, token = 7 /* OpenParenToken */; + case 41 /* closeParen */: + return pos++, token = 8 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 46 /* AsteriskEqualsToken */; + } + return pos++, token = 26 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 29 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 44 /* PlusEqualsToken */; + } + return pos++, token = 24 /* PlusToken */; + case 44 /* comma */: + return pos++, token = 14 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 30 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 45 /* MinusEqualsToken */; + } + return pos++, token = 25 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanNumber(); + return token = 2 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 12 /* DotDotDotToken */; + } + return pos++, token = 11 /* DotToken */; + case 47 /* slash */: + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < len) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (onComment) { + onComment(tokenPos, pos); + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + var safeLength = len - 1; + var commentClosed = false; + while (pos < safeLength) { + var ch = text.charCodeAt(pos); + if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch)) { + precedingLineBreak = true; + } + pos++; + } + if (!commentClosed) { + pos++; + onError(ts.Diagnostics.Asterisk_Slash_expected); + } + if (onComment) { + onComment(tokenPos, pos); + } + continue; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 47 /* SlashEqualsToken */; + } + return pos++, token = 27 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < len && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + var value = scanHexDigits(1, false); + if (value < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + value = 0; + } + tokenValue = "" + value; + return 2 /* NumericLiteral */; + } + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + tokenValue = "" + scanNumber(); + return token = 2 /* NumericLiteral */; + case 58 /* colon */: + return pos++, token = 42 /* ColonToken */; + case 59 /* semicolon */: + return pos++, token = 13 /* SemicolonToken */; + case 60 /* lessThan */: + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 49 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 31 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 17 /* LessThanEqualsToken */; + } + return pos++, token = 15 /* LessThanToken */; + case 61 /* equals */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 21 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 19 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 23 /* EqualsGreaterThanToken */; + } + return pos++, token = 43 /* EqualsToken */; + case 62 /* greaterThan */: + return pos++, token = 16 /* GreaterThanToken */; + case 63 /* question */: + return pos++, token = 41 /* QuestionToken */; + case 91 /* openBracket */: + return pos++, token = 9 /* OpenBracketToken */; + case 93 /* closeBracket */: + return pos++, token = 10 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 54 /* CaretEqualsToken */; + } + return pos++, token = 36 /* CaretToken */; + case 123 /* openBrace */: + return pos++, token = 5 /* OpenBraceToken */; + case 124 /* bar */: + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 40 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 53 /* BarEqualsToken */; + } + return pos++, token = 35 /* BarToken */; + case 125 /* closeBrace */: + return pos++, token = 6 /* CloseBraceToken */; + case 126 /* tilde */: + return pos++, token = 38 /* TildeToken */; + case 92 /* backslash */: + var ch = peekUnicodeEscape(); + if (ch >= 0 && isIdentifierStart(ch)) { + pos += 6; + tokenValue = String.fromCharCode(ch) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + return pos++, token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch)) { + pos++; + while (pos < len && isIdentifierPart(ch = text.charCodeAt(pos))) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpace(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + precedingLineBreak = true; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + return pos++, token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 16 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 51 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 33 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 50 /* GreaterThanGreaterThanEqualsToken */; + } + return pos++, token = 32 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + return pos++, token = 18 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 27 /* SlashToken */ || token === 47 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + if (p >= len) { + return token; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + return token; + } + if (inEscape) { + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + p++; + while (isIdentifierPart(text.charCodeAt(p))) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 4 /* RegularExpressionLiteral */; + } + return token; + } + function tryScan(callback) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var savePrecedingLineBreak = precedingLineBreak; + var result = callback(); + if (!result) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + precedingLineBreak = savePrecedingLineBreak; + } + return result; + } + function setText(newText) { + text = newText || ""; + len = text.length; + setTextPos(0); + } + function setTextPos(textPos) { + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + precedingLineBreak = false; + } + setText(text); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasPrecedingLineBreak: function () { return precedingLineBreak; }, + isIdentifier: function () { return token === 55 /* Identifier */ || token > ts.SyntaxKind.LastReservedWord; }, + isReservedWord: function () { return token >= ts.SyntaxKind.FirstReservedWord && token <= ts.SyntaxKind.LastReservedWord; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + scan: scan, + setText: setText, + setTextPos: setTextPos, + tryScan: tryScan + }; + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +var ts; +(function (ts) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 2] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 3] = "StringLiteral"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 4] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 5] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 6] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 7] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 8] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 9] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 10] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 11] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 12] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 13] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 14] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 15] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 16] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 17] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 18] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 19] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 20] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 21] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 22] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 23] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 24] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 25] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 26] = "AsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 27] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 28] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 29] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 30] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 31] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 32] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 33] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 34] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 35] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 36] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 37] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 38] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 39] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 40] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 41] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 42] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 43] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 44] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 45] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 46] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 47] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 48] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 49] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 50] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 51] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 52] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 53] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 54] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["Identifier"] = 55] = "Identifier"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 56] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 57] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 58] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 59] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 60] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 61] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 62] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 63] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 64] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 65] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 66] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 67] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 68] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 69] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 70] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 71] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 72] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 73] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 74] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 75] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 76] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 77] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 78] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 79] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 80] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 81] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 82] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 83] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 84] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 85] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 86] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 87] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 88] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 89] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 90] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 91] = "WithKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 92] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 93] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 94] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 95] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 96] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 97] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 98] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 99] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 100] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 101] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 102] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 103] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 104] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 105] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 106] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 107] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 108] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 109] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 110] = "StringKeyword"; + SyntaxKind[SyntaxKind["Missing"] = 111] = "Missing"; + SyntaxKind[SyntaxKind["QualifiedName"] = 112] = "QualifiedName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 113] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 114] = "Parameter"; + SyntaxKind[SyntaxKind["Property"] = 115] = "Property"; + SyntaxKind[SyntaxKind["Method"] = 116] = "Method"; + SyntaxKind[SyntaxKind["Constructor"] = 117] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 118] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 119] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 120] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 121] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 122] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypeReference"] = 123] = "TypeReference"; + SyntaxKind[SyntaxKind["TypeQuery"] = 124] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 125] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 126] = "ArrayType"; + SyntaxKind[SyntaxKind["ArrayLiteral"] = 127] = "ArrayLiteral"; + SyntaxKind[SyntaxKind["ObjectLiteral"] = 128] = "ObjectLiteral"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 129] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAccess"] = 130] = "PropertyAccess"; + SyntaxKind[SyntaxKind["IndexedAccess"] = 131] = "IndexedAccess"; + SyntaxKind[SyntaxKind["CallExpression"] = 132] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 133] = "NewExpression"; + SyntaxKind[SyntaxKind["TypeAssertion"] = 134] = "TypeAssertion"; + SyntaxKind[SyntaxKind["ParenExpression"] = 135] = "ParenExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 136] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 137] = "ArrowFunction"; + SyntaxKind[SyntaxKind["PrefixOperator"] = 138] = "PrefixOperator"; + SyntaxKind[SyntaxKind["PostfixOperator"] = 139] = "PostfixOperator"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 140] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 141] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 142] = "OmittedExpression"; + SyntaxKind[SyntaxKind["Block"] = 143] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 144] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 145] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 146] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 147] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 148] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 149] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 150] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 151] = "ForInStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 152] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 153] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 154] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 155] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 156] = "SwitchStatement"; + SyntaxKind[SyntaxKind["CaseClause"] = 157] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 158] = "DefaultClause"; + SyntaxKind[SyntaxKind["LabelledStatement"] = 159] = "LabelledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 160] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 161] = "TryStatement"; + SyntaxKind[SyntaxKind["TryBlock"] = 162] = "TryBlock"; + SyntaxKind[SyntaxKind["CatchBlock"] = 163] = "CatchBlock"; + SyntaxKind[SyntaxKind["FinallyBlock"] = 164] = "FinallyBlock"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 165] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 166] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 167] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["FunctionBlock"] = 168] = "FunctionBlock"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 169] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 170] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 171] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 172] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 173] = "ModuleBlock"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 174] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 175] = "ExportAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 176] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 177] = "SourceFile"; + SyntaxKind[SyntaxKind["Program"] = 178] = "Program"; + SyntaxKind[SyntaxKind["SyntaxList"] = 179] = "SyntaxList"; + SyntaxKind[SyntaxKind["Count"] = 180] = "Count"; + SyntaxKind[SyntaxKind["FirstAssignment"] = SyntaxKind.EqualsToken] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = SyntaxKind.CaretEqualsToken] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = SyntaxKind.BreakKeyword] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = SyntaxKind.WithKeyword] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.BreakKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.StringKeyword] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = SyntaxKind.YieldKeyword] = "LastFutureReservedWord"; + })(ts.SyntaxKind || (ts.SyntaxKind = {})); + var SyntaxKind = ts.SyntaxKind; + (function (NodeFlags) { + NodeFlags[NodeFlags["Export"] = 0x00000001] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 0x00000002] = "Ambient"; + NodeFlags[NodeFlags["QuestionMark"] = 0x00000004] = "QuestionMark"; + NodeFlags[NodeFlags["Rest"] = 0x00000008] = "Rest"; + NodeFlags[NodeFlags["Public"] = 0x00000010] = "Public"; + NodeFlags[NodeFlags["Private"] = 0x00000020] = "Private"; + NodeFlags[NodeFlags["Static"] = 0x00000040] = "Static"; + NodeFlags[NodeFlags["MultiLine"] = 0x00000080] = "MultiLine"; + NodeFlags[NodeFlags["Synthetic"] = 0x00000100] = "Synthetic"; + NodeFlags[NodeFlags["DeclarationFile"] = 0x00000200] = "DeclarationFile"; + NodeFlags[NodeFlags["Modifier"] = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Public | NodeFlags.Private | NodeFlags.Static] = "Modifier"; + })(ts.NodeFlags || (ts.NodeFlags = {})); + var NodeFlags = ts.NodeFlags; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0x00000000] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 0x00000001] = "WriteArrayAsGenericType"; + })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var TypeFormatFlags = ts.TypeFormatFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["Variable"] = 0x00000001] = "Variable"; + SymbolFlags[SymbolFlags["Property"] = 0x00000002] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 0x00000004] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 0x00000008] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 0x00000010] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 0x00000020] = "Interface"; + SymbolFlags[SymbolFlags["Enum"] = 0x00000040] = "Enum"; + SymbolFlags[SymbolFlags["ValueModule"] = 0x00000080] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 0x00000100] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 0x00000200] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 0x00000400] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 0x00000800] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 0x00001000] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 0x00002000] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 0x00004000] = "SetAccessor"; + SymbolFlags[SymbolFlags["CallSignature"] = 0x00008000] = "CallSignature"; + SymbolFlags[SymbolFlags["ConstructSignature"] = 0x00010000] = "ConstructSignature"; + SymbolFlags[SymbolFlags["IndexSignature"] = 0x00020000] = "IndexSignature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 0x00040000] = "TypeParameter"; + SymbolFlags[SymbolFlags["ExportValue"] = 0x00080000] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 0x00100000] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 0x00200000] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Import"] = 0x00400000] = "Import"; + SymbolFlags[SymbolFlags["Instantiated"] = 0x00800000] = "Instantiated"; + SymbolFlags[SymbolFlags["Merged"] = 0x01000000] = "Merged"; + SymbolFlags[SymbolFlags["Transient"] = 0x02000000] = "Transient"; + SymbolFlags[SymbolFlags["Prototype"] = 0x04000000] = "Prototype"; + SymbolFlags[SymbolFlags["Value"] = SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.EnumMember | SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule | SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor] = "Value"; + SymbolFlags[SymbolFlags["Type"] = SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.Enum | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral | SymbolFlags.TypeParameter] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = SymbolFlags.ValueModule | SymbolFlags.NamespaceModule] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = SymbolFlags.ValueModule | SymbolFlags.NamespaceModule] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = SymbolFlags.GetAccessor | SymbolFlags.SetAccessor] = "Accessor"; + SymbolFlags[SymbolFlags["Signature"] = SymbolFlags.CallSignature | SymbolFlags.ConstructSignature | SymbolFlags.IndexSignature] = "Signature"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = SymbolFlags.Value] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["VariableExcludes"] = SymbolFlags.Value & ~SymbolFlags.Variable] = "VariableExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = SymbolFlags.Value] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = SymbolFlags.Value] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = SymbolFlags.Value & ~(SymbolFlags.Function | SymbolFlags.ValueModule)] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = (SymbolFlags.Value | SymbolFlags.Type) & ~SymbolFlags.ValueModule] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = SymbolFlags.Type & ~SymbolFlags.Interface] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["EnumExcludes"] = (SymbolFlags.Value | SymbolFlags.Type) & ~(SymbolFlags.Enum | SymbolFlags.ValueModule)] = "EnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = SymbolFlags.Value & ~(SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = SymbolFlags.Value & ~SymbolFlags.Method] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = SymbolFlags.Value & ~SymbolFlags.SetAccessor] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = SymbolFlags.Value & ~SymbolFlags.GetAccessor] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = SymbolFlags.Type & ~SymbolFlags.TypeParameter] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["ImportExcludes"] = SymbolFlags.Import] = "ImportExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = SymbolFlags.Variable | SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.Enum | SymbolFlags.Module | SymbolFlags.Import] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasLocals"] = SymbolFlags.Function | SymbolFlags.Module | SymbolFlags.Method | SymbolFlags.Constructor | SymbolFlags.Accessor | SymbolFlags.Signature] = "HasLocals"; + SymbolFlags[SymbolFlags["HasExports"] = SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.Module] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral] = "HasMembers"; + SymbolFlags[SymbolFlags["IsContainer"] = SymbolFlags.HasLocals | SymbolFlags.HasExports | SymbolFlags.HasMembers] = "IsContainer"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = SymbolFlags.Property | SymbolFlags.Accessor] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = SymbolFlags.ExportNamespace | SymbolFlags.ExportType | SymbolFlags.ExportValue] = "Export"; + })(ts.SymbolFlags || (ts.SymbolFlags = {})); + var SymbolFlags = ts.SymbolFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 0x00000001] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 0x00000002] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 0x00000004] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["EmitExtends"] = 0x00000008] = "EmitExtends"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 0x00000010] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 0x00000020] = "SuperStatic"; + })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var NodeCheckFlags = ts.NodeCheckFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 0x00000001] = "Any"; + TypeFlags[TypeFlags["String"] = 0x00000002] = "String"; + TypeFlags[TypeFlags["Number"] = 0x00000004] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 0x00000008] = "Boolean"; + TypeFlags[TypeFlags["Void"] = 0x00000010] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 0x00000020] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 0x00000040] = "Null"; + TypeFlags[TypeFlags["Enum"] = 0x00000080] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 0x00000100] = "StringLiteral"; + TypeFlags[TypeFlags["TypeParameter"] = 0x00000200] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 0x00000400] = "Class"; + TypeFlags[TypeFlags["Interface"] = 0x00000800] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 0x00001000] = "Reference"; + TypeFlags[TypeFlags["Anonymous"] = 0x00002000] = "Anonymous"; + TypeFlags[TypeFlags["FromSignature"] = 0x00004000] = "FromSignature"; + TypeFlags[TypeFlags["Intrinsic"] = TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.Boolean | TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null] = "Intrinsic"; + TypeFlags[TypeFlags["StringLike"] = TypeFlags.String | TypeFlags.StringLiteral] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = TypeFlags.Number | TypeFlags.Enum] = "NumberLike"; + TypeFlags[TypeFlags["ObjectType"] = TypeFlags.Class | TypeFlags.Interface | TypeFlags.Reference | TypeFlags.Anonymous] = "ObjectType"; + })(ts.TypeFlags || (ts.TypeFlags = {})); + var TypeFlags = ts.TypeFlags; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(ts.SignatureKind || (ts.SignatureKind = {})); + var SignatureKind = ts.SignatureKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(ts.IndexKind || (ts.IndexKind = {})); + var IndexKind = ts.IndexKind; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var DiagnosticCategory = ts.DiagnosticCategory; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + })(ts.ModuleKind || (ts.ModuleKind = {})); + var ModuleKind = ts.ModuleKind; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + })(ts.ScriptTarget || (ts.ScriptTarget = {})); + var ScriptTarget = ts.ScriptTarget; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 0x7F] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 0x0A] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 0x0D] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 0x205F] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 0x1680] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 0x5F] = "_"; + CharacterCodes[CharacterCodes["$"] = 0x24] = "$"; + CharacterCodes[CharacterCodes["_0"] = 0x30] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 0x31] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 0x32] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 0x33] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 0x34] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 0x35] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 0x36] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 0x37] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 0x38] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 0x39] = "_9"; + CharacterCodes[CharacterCodes["a"] = 0x61] = "a"; + CharacterCodes[CharacterCodes["b"] = 0x62] = "b"; + CharacterCodes[CharacterCodes["c"] = 0x63] = "c"; + CharacterCodes[CharacterCodes["d"] = 0x64] = "d"; + CharacterCodes[CharacterCodes["e"] = 0x65] = "e"; + CharacterCodes[CharacterCodes["f"] = 0x66] = "f"; + CharacterCodes[CharacterCodes["g"] = 0x67] = "g"; + CharacterCodes[CharacterCodes["h"] = 0x68] = "h"; + CharacterCodes[CharacterCodes["i"] = 0x69] = "i"; + CharacterCodes[CharacterCodes["j"] = 0x6A] = "j"; + CharacterCodes[CharacterCodes["k"] = 0x6B] = "k"; + CharacterCodes[CharacterCodes["l"] = 0x6C] = "l"; + CharacterCodes[CharacterCodes["m"] = 0x6D] = "m"; + CharacterCodes[CharacterCodes["n"] = 0x6E] = "n"; + CharacterCodes[CharacterCodes["o"] = 0x6F] = "o"; + CharacterCodes[CharacterCodes["p"] = 0x70] = "p"; + CharacterCodes[CharacterCodes["q"] = 0x71] = "q"; + CharacterCodes[CharacterCodes["r"] = 0x72] = "r"; + CharacterCodes[CharacterCodes["s"] = 0x73] = "s"; + CharacterCodes[CharacterCodes["t"] = 0x74] = "t"; + CharacterCodes[CharacterCodes["u"] = 0x75] = "u"; + CharacterCodes[CharacterCodes["v"] = 0x76] = "v"; + CharacterCodes[CharacterCodes["w"] = 0x77] = "w"; + CharacterCodes[CharacterCodes["x"] = 0x78] = "x"; + CharacterCodes[CharacterCodes["y"] = 0x79] = "y"; + CharacterCodes[CharacterCodes["z"] = 0x7A] = "z"; + CharacterCodes[CharacterCodes["A"] = 0x41] = "A"; + CharacterCodes[CharacterCodes["B"] = 0x42] = "B"; + CharacterCodes[CharacterCodes["C"] = 0x43] = "C"; + CharacterCodes[CharacterCodes["D"] = 0x44] = "D"; + CharacterCodes[CharacterCodes["E"] = 0x45] = "E"; + CharacterCodes[CharacterCodes["F"] = 0x46] = "F"; + CharacterCodes[CharacterCodes["G"] = 0x47] = "G"; + CharacterCodes[CharacterCodes["H"] = 0x48] = "H"; + CharacterCodes[CharacterCodes["I"] = 0x49] = "I"; + CharacterCodes[CharacterCodes["J"] = 0x4A] = "J"; + CharacterCodes[CharacterCodes["K"] = 0x4B] = "K"; + CharacterCodes[CharacterCodes["L"] = 0x4C] = "L"; + CharacterCodes[CharacterCodes["M"] = 0x4D] = "M"; + CharacterCodes[CharacterCodes["N"] = 0x4E] = "N"; + CharacterCodes[CharacterCodes["O"] = 0x4F] = "O"; + CharacterCodes[CharacterCodes["P"] = 0x50] = "P"; + CharacterCodes[CharacterCodes["Q"] = 0x51] = "Q"; + CharacterCodes[CharacterCodes["R"] = 0x52] = "R"; + CharacterCodes[CharacterCodes["S"] = 0x53] = "S"; + CharacterCodes[CharacterCodes["T"] = 0x54] = "T"; + CharacterCodes[CharacterCodes["U"] = 0x55] = "U"; + CharacterCodes[CharacterCodes["V"] = 0x56] = "V"; + CharacterCodes[CharacterCodes["W"] = 0x57] = "W"; + CharacterCodes[CharacterCodes["X"] = 0x58] = "X"; + CharacterCodes[CharacterCodes["Y"] = 0x59] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 0x5a] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 0x26] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 0x2A] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 0x40] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 0x5C] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 0x7C] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 0x5E] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 0x7D] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 0x5D] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 0x29] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 0x3A] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 0x2C] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 0x2E] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 0x22] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 0x3D] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 0x21] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 0x3E] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 0x3C] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 0x2D] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 0x7B] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 0x5B] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 0x28] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 0x25] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 0x2B] = "plus"; + CharacterCodes[CharacterCodes["question"] = 0x3F] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 0x3B] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 0x27] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 0x2F] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 0x7E] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 0x08] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 0x0C] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 0x09] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 0x0B] = "verticalTab"; + })(ts.CharacterCodes || (ts.CharacterCodes = {})); + var CharacterCodes = ts.CharacterCodes; + (function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; + })(ts.ByteOrderMark || (ts.ByteOrderMark = {})); + var ByteOrderMark = ts.ByteOrderMark; +})(ts || (ts = {})); +var ts; +(function (ts) { + function forEach(array, callback) { + var result; + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (result = callback(array[i])) + break; + } + } + return result; + } + ts.forEach = forEach; + function contains(array, value) { + if (array) { + var len = array.length; + for (var i = 0; i < len; i++) { + if (array[i] === value) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function indexOf(array, value) { + if (array) { + var len = array.length; + for (var i = 0; i < len; i++) { + if (array[i] === value) { + return i; + } + } + } + return -1; + } + ts.indexOf = indexOf; + function filter(array, f) { + var result; + if (array) { + result = []; + for (var i = 0, len = array.length; i < len; i++) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + } + } + return result; + } + ts.filter = filter; + function map(array, f) { + var result; + if (array) { + result = []; + var len = array.length; + for (var i = 0; i < len; i++) { + result.push(f(array[i])); + } + } + return result; + } + ts.map = map; + function concatenate(array1, array2) { + if (!array2.length) + return array1; + if (!array1.length) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function sum(array, prop) { + var result = 0; + for (var i = 0; i < array.length; i++) { + result += array[i][prop]; + } + return result; + } + ts.sum = sum; + function binarySearch(array, value) { + var low = 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + if (midValue === value) { + return middle; + } + else if (midValue > value) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + ts.binarySearch = binarySearch; + var hasOwnProperty = Object.prototype.hasOwnProperty; + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + function isEmpty(map) { + for (var id in map) + return false; + return true; + } + ts.isEmpty = isEmpty; + function clone(object) { + var result = {}; + for (var id in object) { + result[id] = object[id]; + } + return result; + } + ts.clone = clone; + function forEachValue(map, callback) { + var result; + for (var id in map) { + if (result = callback(map[id])) + break; + } + return result; + } + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; + } + return result; + } + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function mapToArray(map) { + var result = []; + for (var id in map) + result.push(map[id]); + return result; + } + ts.mapToArray = mapToArray; + function formatStringFromArgs(text, args, baseIndex) { + baseIndex = baseIndex || 0; + return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + } + ts.localizedDiagnosticMessages = undefined; + function getLocaleSpecificMessage(message) { + if (ts.localizedDiagnosticMessages) { + message = ts.localizedDiagnosticMessages[message]; + } + Debug.assert(message, "Diagnostic message does not exist in locale map."); + return message; + } + function createFileDiagnostic(file, start, length, message) { + var text = getLocaleSpecificMessage(message.key); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message.key); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message.key); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function flattenDiagnosticChain(file, start, length, diagnosticChain, newLine) { + var code = diagnosticChain.code; + var category = diagnosticChain.category; + var messageText = ""; + var indent = 0; + while (diagnosticChain) { + if (indent) { + messageText += newLine; + for (var i = 0; i < indent; i++) { + messageText += " "; + } + } + messageText += diagnosticChain.messageText; + indent++; + diagnosticChain = diagnosticChain.next; + } + return { + file: file, + start: start, + length: length, + code: code, + category: category, + messageText: messageText + }; + } + ts.flattenDiagnosticChain = flattenDiagnosticChain; + function compareValues(a, b) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + return a < b ? -1 : 1; + } + function getDiagnosticFilename(diagnostic) { + return diagnostic.file ? diagnostic.file.filename : undefined; + } + function compareDiagnostics(d1, d2) { + return compareValues(getDiagnosticFilename(d1), getDiagnosticFilename(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || compareValues(d1.messageText, d2.messageText) || 0; + } + ts.compareDiagnostics = compareDiagnostics; + function deduplicateSortedDiagnostics(diagnostics) { + if (diagnostics.length < 2) { + return diagnostics; + } + var newDiagnostics = [diagnostics[0]]; + var previousDiagnostic = diagnostics[0]; + for (var i = 1; i < diagnostics.length; i++) { + var currentDiagnostic = diagnostics[i]; + var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; + if (!isDupe) { + newDiagnostics.push(currentDiagnostic); + previousDiagnostic = currentDiagnostic; + } + } + return newDiagnostics; + } + ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; + function normalizeSlashes(path) { + return path.replace(/\\/g, "/"); + } + ts.normalizeSlashes = normalizeSlashes; + function getRootLength(path) { + if (path.charCodeAt(0) === 47 /* slash */) { + if (path.charCodeAt(1) !== 47 /* slash */) + return 1; + var p1 = path.indexOf("/", 2); + if (p1 < 0) + return 2; + var p2 = path.indexOf("/", p1 + 1); + if (p2 < 0) + return p1 + 1; + return p2 + 1; + } + if (path.charCodeAt(1) === 58 /* colon */) { + if (path.charCodeAt(2) === 47 /* slash */) + return 3; + return 2; + } + return 0; + } + ts.getRootLength = getRootLength; + ts.directorySeparator = "/"; + function getNormalizedParts(normalizedSlashedPath, rootLength) { + var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); + var normalized = []; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part !== ".") { + if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { + normalized.pop(); + } + else { + normalized.push(part); + } + } + } + return normalized; + } + function normalizePath(path) { + var path = normalizeSlashes(path); + var rootLength = getRootLength(path); + var normalized = getNormalizedParts(path, rootLength); + return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + } + ts.normalizePath = normalizePath; + function getDirectoryPath(path) { + return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + } + ts.isUrl = isUrl; + function isRootedDiskPath(path) { + return getRootLength(path) !== 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + function normalizedPathComponents(path, rootLength) { + var normalizedParts = getNormalizedParts(path, rootLength); + return [path.substr(0, rootLength)].concat(normalizedParts); + } + function getNormalizedPathComponents(path, currentDirectory) { + var path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength == 0) { + path = combinePaths(normalizeSlashes(currentDirectory), path); + rootLength = getRootLength(path); + } + return normalizedPathComponents(path, rootLength); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedPathFromPathCompoments(pathComponents) { + if (pathComponents && pathComponents.length) { + return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); + } + } + ts.getNormalizedPathFromPathCompoments = getNormalizedPathFromPathCompoments; + function getNormalizedPathComponentsOfUrl(url) { + var urlLength = url.length; + var rootLength = url.indexOf("://") + "://".length; + while (rootLength < urlLength) { + if (url.charCodeAt(rootLength) === 47 /* slash */) { + rootLength++; + } + else { + break; + } + } + if (rootLength === urlLength) { + return [url]; + } + var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); + if (indexOfNextSlash !== -1) { + rootLength = indexOfNextSlash + 1; + return normalizedPathComponents(url, rootLength); + } + else { + return [url + ts.directorySeparator]; + } + } + function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { + if (isUrl(pathOrUrl)) { + return getNormalizedPathComponentsOfUrl(pathOrUrl); + } + else { + return getNormalizedPathComponents(pathOrUrl, currentDirectory); + } + } + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, isAbsolutePathAnUrl) { + var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); + var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); + if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { + directoryComponents.length--; + } + for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + if (directoryComponents[joinStartIndex] !== pathComponents[joinStartIndex]) { + break; + } + } + if (joinStartIndex) { + var relativePath = ""; + var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); + for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { + if (directoryComponents[joinStartIndex] !== "") { + relativePath = relativePath + ".." + ts.directorySeparator; + } + } + return relativePath + relativePathComponents.join(ts.directorySeparator); + } + var absolutePath = getNormalizedPathFromPathCompoments(pathComponents); + if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { + absolutePath = "file:///" + absolutePath; + } + return absolutePath; + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function getBaseFilename(path) { + var i = path.lastIndexOf(ts.directorySeparator); + return i < 0 ? path : path.substring(i + 1); + } + ts.getBaseFilename = getBaseFilename; + function combinePaths(path1, path2) { + if (!(path1 && path1.length)) + return path2; + if (!(path2 && path2.length)) + return path1; + if (path2.charAt(0) === ts.directorySeparator) + return path2; + if (path1.charAt(path1.length - 1) === ts.directorySeparator) + return path1 + path2; + return path1 + ts.directorySeparator + path2; + } + ts.combinePaths = combinePaths; + function fileExtensionIs(path, extension) { + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + } + ts.fileExtensionIs = fileExtensionIs; + function getCanonicalFileName(fileName) { + return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + ts.getCanonicalFileName = getCanonicalFileName; + function Symbol(flags, name) { + this.flags = flags; + this.name = name; + this.declarations = undefined; + } + function Type(checker, flags) { + this.flags = flags; + } + function Signature(checker) { + } + ts.objectAllocator = { + getNodeConstructor: function (kind) { + function Node() { + } + Node.prototype = { + kind: kind, + pos: 0, + end: 0, + flags: 0, + parent: undefined + }; + return Node; + }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; } + }; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(ts.AssertionLevel || (ts.AssertionLevel = {})); + var AssertionLevel = ts.AssertionLevel; + (function (Debug) { + var currentAssertionLevel = 0 /* None */; + function shouldAssert(level) { + return this.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo) { + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + } + throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + } + } + Debug.assert = assert; + function fail(message) { + Debug.assert(false, message); + } + Debug.fail = fail; + })(ts.Debug || (ts.Debug = {})); + var Debug = ts.Debug; +})(ts || (ts = {})); +var sys = (function () { + function getWScriptSystem() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var fileStream = new ActiveXObject("ADODB.Stream"); + fileStream.Type = 2; + var binaryStream = new ActiveXObject("ADODB.Stream"); + binaryStream.Type = 1; + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + function readFile(fileName, encoding) { + if (!fso.FileExists(fileName)) { + return undefined; + } + fileStream.Open(); + try { + if (encoding) { + fileStream.Charset = encoding; + fileStream.LoadFromFile(fileName); + } + else { + fileStream.Charset = "x-ansi"; + fileStream.LoadFromFile(fileName); + var bom = fileStream.ReadText(2) || ""; + fileStream.Position = 0; + fileStream.Charset = bom.length >= 2 && (bom.charCodeAt(0) === 0xFF && bom.charCodeAt(1) === 0xFE || bom.charCodeAt(0) === 0xFE && bom.charCodeAt(1) === 0xFF) ? "unicode" : "utf-8"; + } + return fileStream.ReadText(); + } + catch (e) { + throw e.number === -2147024809 ? new Error(ts.Diagnostics.Unsupported_file_encoding.key) : e; + } + finally { + fileStream.Close(); + } + } + function writeFile(fileName, data) { + fileStream.Open(); + binaryStream.Open(); + try { + fileStream.Charset = "utf-8"; + fileStream.WriteText(data); + fileStream.Position = 3; + fileStream.CopyTo(binaryStream); + binaryStream.SaveToFile(fileName, 2); + } + finally { + binaryStream.Close(); + fileStream.Close(); + } + } + return { + args: args, + newLine: "\r\n", + useCaseSensitiveFileNames: false, + write: function (s) { + WScript.StdOut.Write(s); + }, + writeErr: function (s) { + WScript.StdErr.Write(s); + }, + readFile: readFile, + writeFile: writeFile, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (directoryName) { + if (!this.directoryExists(directoryName)) { + fso.CreateFolder(directoryName); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + getCurrentDirectory: function () { + return new ActiveXObject("WScript.Shell").CurrentDirectory; + }, + getMemoryUsage: function () { + return 0; + }, + exit: function (exitCode) { + try { + WScript.Quit(exitCode); + } + catch (e) { + } + } + }; + } + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require('os'); + var platform = _os.platform(); + var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + function readFile(fileName, encoding) { + if (!_fs.existsSync(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + len &= ~1; + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + return buffer.toString("utf8", 3); + } + return buffer.toString("utf8"); + } + function writeFile(fileName, data) { + _fs.writeFileSync(fileName, data, "utf8"); + } + return { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + process.stdout.write(s); + }, + writeErr: function (s) { + process.stderr.write(s); + }, + readFile: readFile, + writeFile: writeFile, + resolvePath: function (path) { + return _path.resolve(path); + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + createDirectory: function (directoryName) { + if (!this.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + getMemoryUsage: function () { + global.gc(); + return process.memoryUsage().heapUsed; + }, + exit: function (exitCode) { + process.exit(exitCode); + } + }; + } + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWScriptSystem(); + } + else if (typeof module !== "undefined" && module.exports) { + return getNodeSystem(); + } + else { + return undefined; + } +})(); +var ts; +(function (ts) { + var nodeConstructors = new Array(180 /* Count */); + function getNodeConstructor(kind) { + return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); + } + ts.getNodeConstructor = getNodeConstructor; + function createRootNode(kind, pos, end, flags) { + var node = new (getNodeConstructor(kind))(); + node.pos = pos; + node.end = end; + node.flags = flags; + return node; + } + var moduleExtensions = [".d.ts", ".ts", ".js"]; + function getModuleNameFromFilename(filename) { + for (var i = 0; i < moduleExtensions.length; i++) { + var ext = moduleExtensions[i]; + var len = filename.length - ext.length; + if (len > 0 && filename.substr(len) === ext) + return filename.substr(0, len); + } + return filename; + } + ts.getModuleNameFromFilename = getModuleNameFromFilename; + function getSourceFileOfNode(node) { + while (node && node.kind !== 177 /* SourceFile */) + node = node.parent; + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = file.getLineAndCharacterFromPosition(node.pos); + return file.filename + "(" + loc.line + "," + loc.character + ")"; + } + ts.nodePosToString = nodePosToString; + function getStartPosOfNode(node) { + return node.pos; + } + ts.getStartPosOfNode = getStartPosOfNode; + function getTokenPosOfNode(node) { + return ts.skipTrivia(getSourceFileOfNode(node).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getSourceTextOfNodeFromSourceText(sourceText, node) { + return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + } + ts.getSourceTextOfNodeFromSourceText = getSourceTextOfNodeFromSourceText; + function getSourceTextOfNode(node) { + var text = getSourceFileOfNode(node).text; + return text.substring(ts.skipTrivia(text, node.pos), node.end); + } + ts.getSourceTextOfNode = getSourceTextOfNode; + function escapeIdentifier(identifier) { + return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; + } + ts.escapeIdentifier = escapeIdentifier; + function unescapeIdentifier(identifier) { + return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier; + } + ts.unescapeIdentifier = unescapeIdentifier; + function identifierToString(identifier) { + return identifier.kind === 111 /* Missing */ ? "(Missing)" : getSourceTextOfNode(identifier); + } + ts.identifierToString = identifierToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + node = getErrorSpanForNode(node); + var file = getSourceFileOfNode(node); + var start = ts.skipTrivia(file.text, node.pos); + var length = node.end - start; + return ts.createFileDiagnostic(file, start, length, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeFromMessageChain(node, messageChain, newLine) { + node = getErrorSpanForNode(node); + var file = getSourceFileOfNode(node); + var start = ts.skipTrivia(file.text, node.pos); + var length = node.end - start; + return ts.flattenDiagnosticChain(file, start, length, messageChain, newLine); + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getErrorSpanForNode(node) { + var errorSpan; + switch (node.kind) { + case 166 /* VariableDeclaration */: + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + case 172 /* ModuleDeclaration */: + case 171 /* EnumDeclaration */: + case 176 /* EnumMember */: + errorSpan = node.name; + break; + } + return errorSpan && errorSpan.pos < errorSpan.end ? errorSpan : node; + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function isPrologueDirective(node) { + return node.kind === 146 /* ExpressionStatement */ && node.expression.kind === 3 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 55 /* Identifier */ && node.text && (node.text === "eval" || node.text === "arguments"); + } + function isUseStrictPrologueDirective(node) { + ts.Debug.assert(isPrologueDirective(node)); + return node.expression.text === "use strict"; + } + function forEachChild(node, cbNode, cbNodes) { + function child(node) { + if (node) + return cbNode(node); + } + function children(nodes) { + if (nodes) { + if (cbNodes) + return cbNodes(nodes); + var result; + for (var i = 0, len = nodes.length; i < len; i++) { + if (result = cbNode(nodes[i])) + break; + } + return result; + } + } + if (!node) + return; + switch (node.kind) { + case 112 /* QualifiedName */: + return child(node.left) || child(node.right); + case 113 /* TypeParameter */: + return child(node.name) || child(node.constraint); + case 114 /* Parameter */: + return child(node.name) || child(node.type) || child(node.initializer); + case 115 /* Property */: + case 129 /* PropertyAssignment */: + return child(node.name) || child(node.type) || child(node.initializer); + case 120 /* CallSignature */: + case 121 /* ConstructSignature */: + case 122 /* IndexSignature */: + return children(node.typeParameters) || children(node.parameters) || child(node.type); + case 116 /* Method */: + case 117 /* Constructor */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 136 /* FunctionExpression */: + case 167 /* FunctionDeclaration */: + case 137 /* ArrowFunction */: + return child(node.name) || children(node.typeParameters) || children(node.parameters) || child(node.type) || child(node.body); + case 123 /* TypeReference */: + return child(node.typeName) || children(node.typeArguments); + case 124 /* TypeQuery */: + return child(node.exprName); + case 125 /* TypeLiteral */: + return children(node.members); + case 126 /* ArrayType */: + return child(node.elementType); + case 127 /* ArrayLiteral */: + return children(node.elements); + case 128 /* ObjectLiteral */: + return children(node.properties); + case 130 /* PropertyAccess */: + return child(node.left) || child(node.right); + case 131 /* IndexedAccess */: + return child(node.object) || child(node.index); + case 132 /* CallExpression */: + case 133 /* NewExpression */: + return child(node.func) || children(node.typeArguments) || children(node.arguments); + case 134 /* TypeAssertion */: + return child(node.type) || child(node.operand); + case 135 /* ParenExpression */: + return child(node.expression); + case 138 /* PrefixOperator */: + case 139 /* PostfixOperator */: + return child(node.operand); + case 140 /* BinaryExpression */: + return child(node.left) || child(node.right); + case 141 /* ConditionalExpression */: + return child(node.condition) || child(node.whenTrue) || child(node.whenFalse); + case 143 /* Block */: + case 162 /* TryBlock */: + case 164 /* FinallyBlock */: + case 168 /* FunctionBlock */: + case 173 /* ModuleBlock */: + case 177 /* SourceFile */: + return children(node.statements); + case 144 /* VariableStatement */: + return children(node.declarations); + case 146 /* ExpressionStatement */: + return child(node.expression); + case 147 /* IfStatement */: + return child(node.expression) || child(node.thenStatement) || child(node.elseStatement); + case 148 /* DoStatement */: + return child(node.statement) || child(node.expression); + case 149 /* WhileStatement */: + return child(node.expression) || child(node.statement); + case 150 /* ForStatement */: + return children(node.declarations) || child(node.initializer) || child(node.condition) || child(node.iterator) || child(node.statement); + case 151 /* ForInStatement */: + return child(node.declaration) || child(node.variable) || child(node.expression) || child(node.statement); + case 152 /* ContinueStatement */: + case 153 /* BreakStatement */: + return child(node.label); + case 154 /* ReturnStatement */: + return child(node.expression); + case 155 /* WithStatement */: + return child(node.expression) || child(node.statement); + case 156 /* SwitchStatement */: + return child(node.expression) || children(node.clauses); + case 157 /* CaseClause */: + case 158 /* DefaultClause */: + return child(node.expression) || children(node.statements); + case 159 /* LabelledStatement */: + return child(node.label) || child(node.statement); + case 160 /* ThrowStatement */: + return child(node.expression); + case 161 /* TryStatement */: + return child(node.tryBlock) || child(node.catchBlock) || child(node.finallyBlock); + case 163 /* CatchBlock */: + return child(node.variable) || children(node.statements); + case 166 /* VariableDeclaration */: + return child(node.name) || child(node.type) || child(node.initializer); + case 169 /* ClassDeclaration */: + return child(node.name) || children(node.typeParameters) || child(node.baseType) || children(node.implementedTypes) || children(node.members); + case 170 /* InterfaceDeclaration */: + return child(node.name) || children(node.typeParameters) || children(node.baseTypes) || children(node.members); + case 171 /* EnumDeclaration */: + return child(node.name) || children(node.members); + case 176 /* EnumMember */: + return child(node.name) || child(node.initializer); + case 172 /* ModuleDeclaration */: + return child(node.name) || child(node.body); + case 174 /* ImportDeclaration */: + return child(node.name) || child(node.entityName) || child(node.externalModuleName); + case 175 /* ExportAssignment */: + return child(node.exportName); + } + } + ts.forEachChild = forEachChild; + function hasRestParameters(s) { + return s.parameters.length > 0 && (s.parameters[s.parameters.length - 1].flags & 8 /* Rest */) !== 0; + } + ts.hasRestParameters = hasRestParameters; + function isInAmbientContext(node) { + while (node) { + if (node.flags & (2 /* Ambient */ | 512 /* DeclarationFile */)) + return true; + node = node.parent; + } + return false; + } + ts.isInAmbientContext = isInAmbientContext; + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["ModuleElements"] = 1] = "ModuleElements"; + ParsingContext[ParsingContext["BlockStatements"] = 2] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 3] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 4] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 5] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 6] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 7] = "EnumMembers"; + ParsingContext[ParsingContext["BaseTypeReferences"] = 8] = "BaseTypeReferences"; + ParsingContext[ParsingContext["VariableDeclarations"] = 9] = "VariableDeclarations"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 10] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 11] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 12] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 13] = "Parameters"; + ParsingContext[ParsingContext["TypeParameters"] = 14] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 15] = "TypeArguments"; + ParsingContext[ParsingContext["Count"] = 16] = "Count"; + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); + function parsingContextErrors(context) { + switch (context) { + case 0 /* SourceElements */: + return ts.Diagnostics.Declaration_or_statement_expected; + case 1 /* ModuleElements */: + return ts.Diagnostics.Declaration_or_statement_expected; + case 2 /* BlockStatements */: + return ts.Diagnostics.Statement_expected; + case 3 /* SwitchClauses */: + return ts.Diagnostics.case_or_default_expected; + case 4 /* SwitchClauseStatements */: + return ts.Diagnostics.Statement_expected; + case 5 /* TypeMembers */: + return ts.Diagnostics.Property_or_signature_expected; + case 6 /* ClassMembers */: + return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 7 /* EnumMembers */: + return ts.Diagnostics.Enum_member_expected; + case 8 /* BaseTypeReferences */: + return ts.Diagnostics.Type_reference_expected; + case 9 /* VariableDeclarations */: + return ts.Diagnostics.Variable_declaration_expected; + case 10 /* ArgumentExpressions */: + return ts.Diagnostics.Argument_expression_expected; + case 11 /* ObjectLiteralMembers */: + return ts.Diagnostics.Property_assignment_expected; + case 12 /* ArrayLiteralMembers */: + return ts.Diagnostics.Expression_or_comma_expected; + case 13 /* Parameters */: + return ts.Diagnostics.Parameter_declaration_expected; + case 14 /* TypeParameters */: + return ts.Diagnostics.Type_parameter_declaration_expected; + case 15 /* TypeArguments */: + return ts.Diagnostics.Type_argument_expected; + } + } + ; + var LookAheadMode; + (function (LookAheadMode) { + LookAheadMode[LookAheadMode["NotLookingAhead"] = 0] = "NotLookingAhead"; + LookAheadMode[LookAheadMode["NoErrorYet"] = 1] = "NoErrorYet"; + LookAheadMode[LookAheadMode["Error"] = 2] = "Error"; + })(LookAheadMode || (LookAheadMode = {})); + var ModifierContext; + (function (ModifierContext) { + ModifierContext[ModifierContext["SourceElements"] = 0] = "SourceElements"; + ModifierContext[ModifierContext["ModuleElements"] = 1] = "ModuleElements"; + ModifierContext[ModifierContext["ClassMembers"] = 2] = "ClassMembers"; + ModifierContext[ModifierContext["Parameters"] = 3] = "Parameters"; + })(ModifierContext || (ModifierContext = {})); + var TrailingCommaBehavior; + (function (TrailingCommaBehavior) { + TrailingCommaBehavior[TrailingCommaBehavior["Disallow"] = 0] = "Disallow"; + TrailingCommaBehavior[TrailingCommaBehavior["Allow"] = 1] = "Allow"; + TrailingCommaBehavior[TrailingCommaBehavior["Preserve"] = 2] = "Preserve"; + })(TrailingCommaBehavior || (TrailingCommaBehavior = {})); + var ControlBlockContext; + (function (ControlBlockContext) { + ControlBlockContext[ControlBlockContext["NotNested"] = 0] = "NotNested"; + ControlBlockContext[ControlBlockContext["Nested"] = 1] = "Nested"; + ControlBlockContext[ControlBlockContext["CrossingFunctionBoundary"] = 2] = "CrossingFunctionBoundary"; + })(ControlBlockContext || (ControlBlockContext = {})); + function createSourceFile(filename, sourceText, languageVersion) { + var file; + var scanner; + var token; + var parsingContext; + var commentRanges; + var identifiers = {}; + var identifierCount = 0; + var nodeCount = 0; + var lineStarts; + var isInStrictMode = false; + var lookAheadMode = 0 /* NotLookingAhead */; + var inAmbientContext = false; + var inFunctionBody = false; + var inSwitchStatement = 0 /* NotNested */; + var inIterationStatement = 0 /* NotNested */; + var labelledStatementInfo = (function () { + var functionBoundarySentinel; + var currentLabelSet; + var labelSetStack; + var isIterationStack; + function addLabel(label) { + if (!currentLabelSet) { + currentLabelSet = {}; + } + currentLabelSet[label.text] = true; + } + function pushCurrentLabelSet(isIterationStatement) { + if (!labelSetStack && !isIterationStack) { + labelSetStack = []; + isIterationStack = []; + } + ts.Debug.assert(currentLabelSet !== undefined); + labelSetStack.push(currentLabelSet); + isIterationStack.push(isIterationStatement); + currentLabelSet = undefined; + } + function pushFunctionBoundary() { + if (!functionBoundarySentinel) { + functionBoundarySentinel = {}; + if (!labelSetStack && !isIterationStack) { + labelSetStack = []; + isIterationStack = []; + } + } + ts.Debug.assert(currentLabelSet === undefined); + labelSetStack.push(functionBoundarySentinel); + isIterationStack.push(false); + } + function pop() { + ts.Debug.assert(labelSetStack.length && isIterationStack.length && currentLabelSet === undefined); + labelSetStack.pop(); + isIterationStack.pop(); + } + function nodeIsNestedInLabel(label, requireIterationStatement, stopAtFunctionBoundary) { + if (!requireIterationStatement && currentLabelSet && ts.hasProperty(currentLabelSet, label.text)) { + return 1 /* Nested */; + } + if (!labelSetStack) { + return 0 /* NotNested */; + } + var crossedFunctionBoundary = false; + for (var i = labelSetStack.length - 1; i >= 0; i--) { + var labelSet = labelSetStack[i]; + if (labelSet === functionBoundarySentinel) { + if (stopAtFunctionBoundary) { + break; + } + else { + crossedFunctionBoundary = true; + continue; + } + } + if (requireIterationStatement && isIterationStack[i] === false) { + continue; + } + if (ts.hasProperty(labelSet, label.text)) { + return crossedFunctionBoundary ? 2 /* CrossingFunctionBoundary */ : 1 /* Nested */; + } + } + return 0 /* NotNested */; + } + return { + addLabel: addLabel, + pushCurrentLabelSet: pushCurrentLabelSet, + pushFunctionBoundary: pushFunctionBoundary, + pop: pop, + nodeIsNestedInLabel: nodeIsNestedInLabel + }; + })(); + function getLineAndCharacterlFromSourcePosition(position) { + if (!lineStarts) { + lineStarts = ts.getLineStarts(sourceText); + } + return ts.getLineAndCharacterOfPosition(lineStarts, position); + } + function error(message, arg0, arg1, arg2) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + errorAtPos(start, length, message, arg0, arg1, arg2); + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var span = getErrorSpanForNode(node); + var start = ts.skipTrivia(file.text, span.pos); + var length = span.end - start; + file.syntacticErrors.push(ts.createFileDiagnostic(file, start, length, message, arg0, arg1, arg2)); + } + function reportInvalidUseInStrictMode(node) { + var name = sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + grammarErrorOnNode(node, ts.Diagnostics.Invalid_use_of_0_in_strict_mode, name); + } + function grammarErrorAtPos(start, length, message, arg0, arg1, arg2) { + file.syntacticErrors.push(ts.createFileDiagnostic(file, start, length, message, arg0, arg1, arg2)); + } + function errorAtPos(start, length, message, arg0, arg1, arg2) { + var lastErrorPos = file.syntacticErrors.length ? file.syntacticErrors[file.syntacticErrors.length - 1].start : -1; + if (start !== lastErrorPos) { + file.syntacticErrors.push(ts.createFileDiagnostic(file, start, length, message, arg0, arg1, arg2)); + } + if (lookAheadMode === 1 /* NoErrorYet */) { + lookAheadMode = 2 /* Error */; + } + } + function scanError(message) { + var pos = scanner.getTextPos(); + errorAtPos(pos, 0, message); + } + function onComment(pos, end) { + if (commentRanges) + commentRanges.push({ pos: pos, end: end }); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + function nextToken() { + return token = scanner.scan(); + } + function getTokenPos(pos) { + return ts.skipTrivia(sourceText, pos); + } + function reScanGreaterToken() { + return token = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return token = scanner.reScanSlashToken(); + } + function lookAheadHelper(callback, alwaysResetState) { + var saveToken = token; + var saveSyntacticErrorsLength = file.syntacticErrors.length; + var saveLookAheadMode = lookAheadMode; + lookAheadMode = 1 /* NoErrorYet */; + var result = callback(); + ts.Debug.assert(lookAheadMode === 2 /* Error */ || lookAheadMode === 1 /* NoErrorYet */); + if (lookAheadMode === 2 /* Error */) { + result = undefined; + } + lookAheadMode = saveLookAheadMode; + if (!result || alwaysResetState) { + token = saveToken; + file.syntacticErrors.length = saveSyntacticErrorsLength; + } + return result; + } + function lookAhead(callback) { + var result; + scanner.tryScan(function () { + result = lookAheadHelper(callback, true); + return false; + }); + return result; + } + function tryParse(callback) { + return scanner.tryScan(function () { return lookAheadHelper(callback, false); }); + } + function isIdentifier() { + return token === 55 /* Identifier */ || (isInStrictMode ? token > ts.SyntaxKind.LastFutureReservedWord : token > ts.SyntaxKind.LastReservedWord); + } + function parseExpected(t) { + if (token === t) { + nextToken(); + return true; + } + error(ts.Diagnostics._0_expected, ts.tokenToString(t)); + return false; + } + function parseOptional(t) { + if (token === t) { + nextToken(); + return true; + } + return false; + } + function canParseSemicolon() { + if (token === 13 /* SemicolonToken */) { + return true; + } + return token === 6 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token === 13 /* SemicolonToken */) { + nextToken(); + } + } + else { + error(ts.Diagnostics._0_expected, ";"); + } + } + function createNode(kind, pos) { + nodeCount++; + var node = new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(); + if (!(pos >= 0)) + pos = scanner.getStartPos(); + node.pos = pos; + node.end = pos; + return node; + } + function finishNode(node) { + node.end = scanner.getStartPos(); + return node; + } + function createMissingNode() { + return createNode(111 /* Missing */); + } + function createIdentifier(isIdentifier) { + identifierCount++; + if (isIdentifier) { + var node = createNode(55 /* Identifier */); + var text = escapeIdentifier(scanner.getTokenValue()); + node.text = ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + nextToken(); + return finishNode(node); + } + error(ts.Diagnostics.Identifier_expected); + return createMissingNode(); + } + function parseIdentifier() { + return createIdentifier(isIdentifier()); + } + function parseIdentifierName() { + return createIdentifier(token >= 55 /* Identifier */); + } + function isPropertyName() { + return token >= 55 /* Identifier */ || token === 3 /* StringLiteral */ || token === 2 /* NumericLiteral */; + } + function parsePropertyName() { + if (token === 3 /* StringLiteral */ || token === 2 /* NumericLiteral */) { + return parsePrimaryExpression(); + } + return parseIdentifierName(); + } + function isKeyword(token) { + return ts.SyntaxKind.FirstKeyword <= token && token <= ts.SyntaxKind.LastKeyword; + } + function isModifier(token) { + switch (token) { + case 98 /* PublicKeyword */: + case 96 /* PrivateKeyword */: + case 99 /* StaticKeyword */: + case 68 /* ExportKeyword */: + case 104 /* DeclareKeyword */: + return true; + } + return false; + } + function parseContextualModifier(t) { + return token === t && tryParse(function () { + nextToken(); + return token === 9 /* OpenBracketToken */ || isPropertyName(); + }); + } + function parseAnyContextualModifier() { + return isModifier(token) && tryParse(function () { + nextToken(); + return token === 9 /* OpenBracketToken */ || isPropertyName(); + }); + } + function isListElement(kind, inErrorRecovery) { + switch (kind) { + case 0 /* SourceElements */: + case 1 /* ModuleElements */: + return isSourceElement(inErrorRecovery); + case 2 /* BlockStatements */: + case 4 /* SwitchClauseStatements */: + return isStatement(inErrorRecovery); + case 3 /* SwitchClauses */: + return token === 57 /* CaseKeyword */ || token === 63 /* DefaultKeyword */; + case 5 /* TypeMembers */: + return isTypeMember(); + case 6 /* ClassMembers */: + return lookAhead(isClassMemberStart); + case 7 /* EnumMembers */: + case 11 /* ObjectLiteralMembers */: + return isPropertyName(); + case 8 /* BaseTypeReferences */: + return isIdentifier() && ((token !== 69 /* ExtendsKeyword */ && token !== 92 /* ImplementsKeyword */) || !lookAhead(function () { return (nextToken(), isIdentifier()); })); + case 9 /* VariableDeclarations */: + case 14 /* TypeParameters */: + return isIdentifier(); + case 10 /* ArgumentExpressions */: + return isExpression(); + case 12 /* ArrayLiteralMembers */: + return token === 14 /* CommaToken */ || isExpression(); + case 13 /* Parameters */: + return isParameter(); + case 15 /* TypeArguments */: + return isType(); + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isListTerminator(kind) { + if (token === 1 /* EndOfFileToken */) { + return true; + } + switch (kind) { + case 1 /* ModuleElements */: + case 2 /* BlockStatements */: + case 3 /* SwitchClauses */: + case 5 /* TypeMembers */: + case 6 /* ClassMembers */: + case 7 /* EnumMembers */: + case 11 /* ObjectLiteralMembers */: + return token === 6 /* CloseBraceToken */; + case 4 /* SwitchClauseStatements */: + return token === 6 /* CloseBraceToken */ || token === 57 /* CaseKeyword */ || token === 63 /* DefaultKeyword */; + case 8 /* BaseTypeReferences */: + return token === 5 /* OpenBraceToken */ || token === 69 /* ExtendsKeyword */ || token === 92 /* ImplementsKeyword */; + case 9 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 14 /* TypeParameters */: + return token === 16 /* GreaterThanToken */ || token === 7 /* OpenParenToken */ || token === 5 /* OpenBraceToken */ || token === 69 /* ExtendsKeyword */ || token === 92 /* ImplementsKeyword */; + case 10 /* ArgumentExpressions */: + return token === 8 /* CloseParenToken */ || token === 13 /* SemicolonToken */; + case 12 /* ArrayLiteralMembers */: + return token === 10 /* CloseBracketToken */; + case 13 /* Parameters */: + return token === 8 /* CloseParenToken */ || token === 10 /* CloseBracketToken */ || token === 5 /* OpenBraceToken */; + case 15 /* TypeArguments */: + return token === 16 /* GreaterThanToken */ || token === 7 /* OpenParenToken */; + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (token === 76 /* InKeyword */) { + return true; + } + if (token === 23 /* EqualsGreaterThanToken */) { + return true; + } + return false; + } + function isInSomeParsingContext() { + for (var kind = 0; kind < 16 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, checkForStrictMode, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = []; + result.pos = getNodePos(); + var saveIsInStrictMode = isInStrictMode; + while (!isListTerminator(kind)) { + if (isListElement(kind, false)) { + var element = parseElement(); + result.push(element); + if (!isInStrictMode && checkForStrictMode) { + if (isPrologueDirective(element)) { + if (isUseStrictPrologueDirective(element)) { + isInStrictMode = true; + checkForStrictMode = false; + } + } + else { + checkForStrictMode = false; + } + } + } + else { + error(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + break; + } + nextToken(); + } + } + isInStrictMode = saveIsInStrictMode; + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseDelimitedList(kind, parseElement, trailingCommaBehavior) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = []; + result.pos = getNodePos(); + var errorCountBeforeParsingList = file.syntacticErrors.length; + var commaStart = -1; + while (true) { + if (isListElement(kind, false)) { + result.push(parseElement()); + commaStart = scanner.getTokenPos(); + if (parseOptional(14 /* CommaToken */)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + error(ts.Diagnostics._0_expected, ","); + } + else if (isListTerminator(kind)) { + if (commaStart >= 0) { + if (trailingCommaBehavior === 0 /* Disallow */) { + if (file.syntacticErrors.length === errorCountBeforeParsingList) { + grammarErrorAtPos(commaStart, scanner.getStartPos() - commaStart, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + else if (trailingCommaBehavior === 2 /* Preserve */) { + result.push(createNode(142 /* OmittedExpression */)); + } + } + break; + } + else { + error(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + break; + } + nextToken(); + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + var pos = getNodePos(); + var result = []; + result.pos = pos; + result.end = pos; + return result; + } + function createNodeArray(node) { + var result = [node]; + result.pos = node.pos; + result.end = node.end; + return result; + } + function parseBracketedList(kind, parseElement, startToken, endToken) { + if (parseExpected(startToken)) { + var result = parseDelimitedList(kind, parseElement, 0 /* Disallow */); + parseExpected(endToken); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords) { + var entity = parseIdentifier(); + while (parseOptional(11 /* DotToken */)) { + var node = createNode(112 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = allowReservedWords ? parseIdentifierName() : parseIdentifier(); + entity = finishNode(node); + } + return entity; + } + function parseTokenNode() { + var node = createNode(token); + nextToken(); + return finishNode(node); + } + function parseLiteralNode() { + var node = createNode(token); + node.text = scanner.getTokenValue(); + nextToken(); + return finishNode(node); + } + function parseStringLiteral() { + if (token === 3 /* StringLiteral */) + return parseLiteralNode(); + error(ts.Diagnostics.String_literal_expected); + return createMissingNode(); + } + function parseTypeReference() { + var node = createNode(123 /* TypeReference */); + node.typeName = parseEntityName(false); + if (!scanner.hasPrecedingLineBreak() && token === 15 /* LessThanToken */) { + node.typeArguments = parseTypeArguments(); + } + return finishNode(node); + } + function parseTypeQuery() { + var node = createNode(124 /* TypeQuery */); + parseExpected(87 /* TypeOfKeyword */); + node.exprName = parseEntityName(true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(113 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(69 /* ExtendsKeyword */)) { + if (isType() || !isExpression()) { + node.constraint = parseType(); + } + else { + var expr = parseUnaryExpression(); + grammarErrorOnNode(expr, ts.Diagnostics.Type_expected); + } + } + return finishNode(node); + } + function parseTypeParameters() { + if (token === 15 /* LessThanToken */) { + var pos = getNodePos(); + var result = parseBracketedList(14 /* TypeParameters */, parseTypeParameter, 15 /* LessThanToken */, 16 /* GreaterThanToken */); + if (!result.length) { + var start = getTokenPos(pos); + var length = getNodePos() - start; + errorAtPos(start, length, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + return result; + } + } + function parseParameterType() { + return parseOptional(42 /* ColonToken */) ? token === 3 /* StringLiteral */ ? parseStringLiteral() : parseType() : undefined; + } + function isParameter() { + return token === 12 /* DotDotDotToken */ || isIdentifier() || isModifier(token); + } + function parseParameter(flags) { + if (flags === void 0) { flags = 0; } + var node = createNode(114 /* Parameter */); + node.flags |= parseAndCheckModifiers(3 /* Parameters */); + if (parseOptional(12 /* DotDotDotToken */)) { + node.flags |= 8 /* Rest */; + } + node.name = parseIdentifier(); + if (node.name.kind === 111 /* Missing */ && node.flags === 0 && isModifier(token)) { + nextToken(); + } + if (parseOptional(41 /* QuestionToken */)) { + node.flags |= 4 /* QuestionMark */; + } + node.type = parseParameterType(); + node.initializer = parseInitializer(true); + return finishNode(node); + } + function parseSignature(kind, returnToken) { + if (kind === 121 /* ConstructSignature */) { + parseExpected(78 /* NewKeyword */); + } + var typeParameters = parseTypeParameters(); + var parameters = parseParameterList(7 /* OpenParenToken */, 8 /* CloseParenToken */); + checkParameterList(parameters); + var type = parseOptional(returnToken) ? parseType() : undefined; + return { + typeParameters: typeParameters, + parameters: parameters, + type: type + }; + } + function parseParameterList(startDelimiter, endDelimiter) { + return parseBracketedList(13 /* Parameters */, parseParameter, startDelimiter, endDelimiter); + } + function checkParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (isInStrictMode && isEvalOrArgumentsIdentifier(parameter.name)) { + reportInvalidUseInStrictMode(parameter.name); + return; + } + else if (parameter.flags & 8 /* Rest */) { + if (i !== (parameterCount - 1)) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + return; + } + if (parameter.flags & 4 /* QuestionMark */) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + return; + } + if (parameter.initializer) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + return; + } + } + else if (parameter.flags & 4 /* QuestionMark */ || parameter.initializer) { + seenOptionalParameter = true; + if (parameter.flags & 4 /* QuestionMark */ && parameter.initializer) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + return; + } + } + else { + if (seenOptionalParameter) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + return; + } + } + } + } + function parseSignatureMember(kind, returnToken) { + var node = createNode(kind); + var sig = parseSignature(kind, returnToken); + node.typeParameters = sig.typeParameters; + node.parameters = sig.parameters; + node.type = sig.type; + parseSemicolon(); + return finishNode(node); + } + function parseIndexSignatureMember() { + var node = createNode(122 /* IndexSignature */); + var errorCountBeforeIndexSignature = file.syntacticErrors.length; + var indexerStart = scanner.getTokenPos(); + node.parameters = parseParameterList(9 /* OpenBracketToken */, 10 /* CloseBracketToken */); + var indexerLength = scanner.getStartPos() - indexerStart; + node.type = parseTypeAnnotation(); + parseSemicolon(); + if (file.syntacticErrors.length === errorCountBeforeIndexSignature) { + checkIndexSignature(node, indexerStart, indexerLength); + } + return finishNode(node); + } + function checkIndexSignature(node, indexerStart, indexerLength) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + var arityDiagnostic = ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter; + if (parameter) { + grammarErrorOnNode(parameter.name, arityDiagnostic); + } + else { + grammarErrorAtPos(indexerStart, indexerLength, arityDiagnostic); + } + return; + } + else if (parameter.flags & 8 /* Rest */) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + return; + } + else if (parameter.flags & ts.NodeFlags.Modifier) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + return; + } + else if (parameter.flags & 4 /* QuestionMark */) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + return; + } + else if (parameter.initializer) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + return; + } + else if (!parameter.type) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + return; + } + else if (parameter.type.kind !== 110 /* StringKeyword */ && parameter.type.kind !== 108 /* NumberKeyword */) { + grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return; + } + else if (!node.type) { + grammarErrorAtPos(indexerStart, indexerLength, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + return; + } + } + function parsePropertyOrMethod() { + var node = createNode(0 /* Unknown */); + node.name = parsePropertyName(); + if (parseOptional(41 /* QuestionToken */)) { + node.flags |= 4 /* QuestionMark */; + } + if (token === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */) { + node.kind = 116 /* Method */; + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + node.typeParameters = sig.typeParameters; + node.parameters = sig.parameters; + node.type = sig.type; + } + else { + node.kind = 115 /* Property */; + node.type = parseTypeAnnotation(); + } + parseSemicolon(); + return finishNode(node); + } + function isTypeMember() { + switch (token) { + case 7 /* OpenParenToken */: + case 15 /* LessThanToken */: + case 9 /* OpenBracketToken */: + return true; + default: + return isPropertyName() && lookAhead(function () { return nextToken() === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */ || token === 41 /* QuestionToken */ || token === 42 /* ColonToken */ || canParseSemicolon(); }); + } + } + function parseTypeMember() { + switch (token) { + case 7 /* OpenParenToken */: + case 15 /* LessThanToken */: + return parseSignatureMember(120 /* CallSignature */, 42 /* ColonToken */); + case 9 /* OpenBracketToken */: + return parseIndexSignatureMember(); + case 78 /* NewKeyword */: + if (lookAhead(function () { return nextToken() === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */; })) { + return parseSignatureMember(121 /* ConstructSignature */, 42 /* ColonToken */); + } + case 3 /* StringLiteral */: + case 2 /* NumericLiteral */: + return parsePropertyOrMethod(); + default: + if (token >= 55 /* Identifier */) { + return parsePropertyOrMethod(); + } + } + } + function parseTypeLiteral() { + var node = createNode(125 /* TypeLiteral */); + if (parseExpected(5 /* OpenBraceToken */)) { + node.members = parseList(5 /* TypeMembers */, false, parseTypeMember); + parseExpected(6 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseFunctionType(signatureKind) { + var node = createNode(125 /* TypeLiteral */); + var member = createNode(signatureKind); + var sig = parseSignature(signatureKind, 23 /* EqualsGreaterThanToken */); + member.typeParameters = sig.typeParameters; + member.parameters = sig.parameters; + member.type = sig.type; + finishNode(member); + node.members = createNodeArray(member); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token === 11 /* DotToken */ ? undefined : node; + } + function parseNonArrayType() { + switch (token) { + case 101 /* AnyKeyword */: + case 110 /* StringKeyword */: + case 108 /* NumberKeyword */: + case 102 /* BooleanKeyword */: + case 89 /* VoidKeyword */: + var node = tryParse(parseKeywordAndNoDot); + return node || parseTypeReference(); + case 87 /* TypeOfKeyword */: + return parseTypeQuery(); + case 5 /* OpenBraceToken */: + return parseTypeLiteral(); + case 7 /* OpenParenToken */: + case 15 /* LessThanToken */: + return parseFunctionType(120 /* CallSignature */); + case 78 /* NewKeyword */: + return parseFunctionType(121 /* ConstructSignature */); + default: + if (isIdentifier()) { + return parseTypeReference(); + } + } + error(ts.Diagnostics.Type_expected); + return createMissingNode(); + } + function isType() { + switch (token) { + case 101 /* AnyKeyword */: + case 110 /* StringKeyword */: + case 108 /* NumberKeyword */: + case 102 /* BooleanKeyword */: + case 89 /* VoidKeyword */: + case 87 /* TypeOfKeyword */: + case 5 /* OpenBraceToken */: + case 15 /* LessThanToken */: + case 78 /* NewKeyword */: + return true; + case 7 /* OpenParenToken */: + return lookAhead(function () { + nextToken(); + return token === 8 /* CloseParenToken */ || isParameter(); + }); + default: + return isIdentifier(); + } + } + function parseType() { + var type = parseNonArrayType(); + while (type && !scanner.hasPrecedingLineBreak() && parseOptional(9 /* OpenBracketToken */)) { + parseExpected(10 /* CloseBracketToken */); + var node = createNode(126 /* ArrayType */, type.pos); + node.elementType = type; + type = finishNode(node); + } + return type; + } + function parseTypeAnnotation() { + return parseOptional(42 /* ColonToken */) ? parseType() : undefined; + } + function isExpression() { + switch (token) { + case 83 /* ThisKeyword */: + case 81 /* SuperKeyword */: + case 79 /* NullKeyword */: + case 85 /* TrueKeyword */: + case 70 /* FalseKeyword */: + case 2 /* NumericLiteral */: + case 3 /* StringLiteral */: + case 7 /* OpenParenToken */: + case 9 /* OpenBracketToken */: + case 5 /* OpenBraceToken */: + case 73 /* FunctionKeyword */: + case 78 /* NewKeyword */: + case 27 /* SlashToken */: + case 47 /* SlashEqualsToken */: + case 24 /* PlusToken */: + case 25 /* MinusToken */: + case 38 /* TildeToken */: + case 37 /* ExclamationToken */: + case 64 /* DeleteKeyword */: + case 87 /* TypeOfKeyword */: + case 89 /* VoidKeyword */: + case 29 /* PlusPlusToken */: + case 30 /* MinusMinusToken */: + case 15 /* LessThanToken */: + case 55 /* Identifier */: + return true; + default: + return isIdentifier(); + } + } + function isExpressionStatement() { + return token !== 5 /* OpenBraceToken */ && token !== 73 /* FunctionKeyword */ && isExpression(); + } + function parseExpression(noIn) { + var expr = parseAssignmentExpression(noIn); + while (parseOptional(14 /* CommaToken */)) { + expr = makeBinaryExpression(expr, 14 /* CommaToken */, parseAssignmentExpression(noIn)); + } + return expr; + } + function parseInitializer(inParameter, noIn) { + if (token !== 43 /* EqualsToken */) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 5 /* OpenBraceToken */) || !isExpression()) { + return undefined; + } + } + parseExpected(43 /* EqualsToken */); + return parseAssignmentExpression(noIn); + } + function parseAssignmentExpression(noIn) { + var arrowExpression = tryParseArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + var expr = parseConditionalExpression(noIn); + if (isLeftHandSideExpression(expr) && isAssignmentOperator()) { + if (isInStrictMode && isEvalOrArgumentsIdentifier(expr)) { + reportInvalidUseInStrictMode(expr); + } + var operator = token; + nextToken(); + return makeBinaryExpression(expr, operator, parseAssignmentExpression(noIn)); + } + return expr; + } + function isLeftHandSideExpression(expr) { + if (expr) { + switch (expr.kind) { + case 130 /* PropertyAccess */: + case 131 /* IndexedAccess */: + case 133 /* NewExpression */: + case 132 /* CallExpression */: + case 127 /* ArrayLiteral */: + case 135 /* ParenExpression */: + case 128 /* ObjectLiteral */: + case 136 /* FunctionExpression */: + case 55 /* Identifier */: + case 111 /* Missing */: + case 4 /* RegularExpressionLiteral */: + case 2 /* NumericLiteral */: + case 3 /* StringLiteral */: + case 70 /* FalseKeyword */: + case 79 /* NullKeyword */: + case 83 /* ThisKeyword */: + case 85 /* TrueKeyword */: + case 81 /* SuperKeyword */: + return true; + } + } + return false; + } + function tryParseArrowFunctionExpression() { + return isSimpleArrowFunctionExpression() ? parseSimpleArrowFunctionExpression() : tryParseParenthesizedArrowFunctionExpression(); + } + function isSimpleArrowFunctionExpression() { + if (token === 23 /* EqualsGreaterThanToken */) { + return true; + } + if (token === 55 /* Identifier */) { + return lookAhead(function () { + return nextToken() === 23 /* EqualsGreaterThanToken */; + }); + } + return false; + } + function parseSimpleArrowFunctionExpression() { + ts.Debug.assert(token === 55 /* Identifier */ || token === 23 /* EqualsGreaterThanToken */); + var identifier = parseIdentifier(); + ts.Debug.assert(token === 23 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + parseExpected(23 /* EqualsGreaterThanToken */); + var parameter = createNode(114 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + var parameters = []; + parameters.push(parameter); + parameters.pos = parameter.pos; + parameters.end = parameter.end; + var signature = { parameters: parameters }; + return parseArrowExpressionTail(identifier.pos, signature, false); + } + function tryParseParenthesizedArrowFunctionExpression() { + var pos = getNodePos(); + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + return undefined; + } + if (triState === 1 /* True */) { + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + if (parseExpected(23 /* EqualsGreaterThanToken */) || token === 5 /* OpenBraceToken */) { + return parseArrowExpressionTail(pos, sig, false); + } + else { + return makeFunctionExpression(137 /* ArrowFunction */, pos, undefined, sig, createMissingNode()); + } + } + var sig = tryParseSignatureIfArrowOrBraceFollows(); + if (sig) { + parseExpected(23 /* EqualsGreaterThanToken */); + return parseArrowExpressionTail(pos, sig, false); + } + else { + return undefined; + } + } + function isParenthesizedArrowFunctionExpression() { + if (token === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */) { + return lookAhead(function () { + var first = token; + var second = nextToken(); + if (first === 7 /* OpenParenToken */) { + if (second === 8 /* CloseParenToken */) { + var third = nextToken(); + switch (third) { + case 23 /* EqualsGreaterThanToken */: + case 42 /* ColonToken */: + case 5 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + if (second === 12 /* DotDotDotToken */) { + return 1 /* True */; + } + if (!isIdentifier()) { + return 0 /* False */; + } + if (nextToken() === 42 /* ColonToken */) { + return 1 /* True */; + } + return 2 /* Unknown */; + } + else { + ts.Debug.assert(first === 15 /* LessThanToken */); + if (!isIdentifier()) { + return 0 /* False */; + } + return 2 /* Unknown */; + } + }); + } + return 0 /* False */; + } + function tryParseSignatureIfArrowOrBraceFollows() { + return tryParse(function () { + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + if (token === 23 /* EqualsGreaterThanToken */ || token === 5 /* OpenBraceToken */) { + return sig; + } + return undefined; + }); + } + function parseArrowExpressionTail(pos, sig, noIn) { + var body; + if (token === 5 /* OpenBraceToken */) { + body = parseBody(false); + } + else if (isStatement(true) && !isExpressionStatement() && token !== 73 /* FunctionKeyword */) { + body = parseBody(true); + } + else { + body = parseAssignmentExpression(noIn); + } + return makeFunctionExpression(137 /* ArrowFunction */, pos, undefined, sig, body); + } + function isAssignmentOperator() { + return token >= ts.SyntaxKind.FirstAssignment && token <= ts.SyntaxKind.LastAssignment; + } + function parseConditionalExpression(noIn) { + var expr = parseBinaryExpression(noIn); + while (parseOptional(41 /* QuestionToken */)) { + var node = createNode(141 /* ConditionalExpression */, expr.pos); + node.condition = expr; + node.whenTrue = parseAssignmentExpression(false); + parseExpected(42 /* ColonToken */); + node.whenFalse = parseAssignmentExpression(noIn); + expr = finishNode(node); + } + return expr; + } + function parseBinaryExpression(noIn) { + return parseBinaryOperators(parseUnaryExpression(), 0, noIn); + } + function parseBinaryOperators(expr, minPrecedence, noIn) { + while (true) { + reScanGreaterToken(); + var precedence = getOperatorPrecedence(); + if (precedence && precedence > minPrecedence && (!noIn || token !== 76 /* InKeyword */)) { + var operator = token; + nextToken(); + expr = makeBinaryExpression(expr, operator, parseBinaryOperators(parseUnaryExpression(), precedence, noIn)); + continue; + } + return expr; + } + } + function getOperatorPrecedence() { + switch (token) { + case 40 /* BarBarToken */: + return 1; + case 39 /* AmpersandAmpersandToken */: + return 2; + case 35 /* BarToken */: + return 3; + case 36 /* CaretToken */: + return 4; + case 34 /* AmpersandToken */: + return 5; + case 19 /* EqualsEqualsToken */: + case 20 /* ExclamationEqualsToken */: + case 21 /* EqualsEqualsEqualsToken */: + case 22 /* ExclamationEqualsEqualsToken */: + return 6; + case 15 /* LessThanToken */: + case 16 /* GreaterThanToken */: + case 17 /* LessThanEqualsToken */: + case 18 /* GreaterThanEqualsToken */: + case 77 /* InstanceOfKeyword */: + case 76 /* InKeyword */: + return 7; + case 31 /* LessThanLessThanToken */: + case 32 /* GreaterThanGreaterThanToken */: + case 33 /* GreaterThanGreaterThanGreaterThanToken */: + return 8; + case 24 /* PlusToken */: + case 25 /* MinusToken */: + return 9; + case 26 /* AsteriskToken */: + case 27 /* SlashToken */: + case 28 /* PercentToken */: + return 10; + } + return undefined; + } + function makeBinaryExpression(left, operator, right) { + var node = createNode(140 /* BinaryExpression */, left.pos); + node.left = left; + node.operator = operator; + node.right = right; + return finishNode(node); + } + function parseUnaryExpression() { + var pos = getNodePos(); + switch (token) { + case 24 /* PlusToken */: + case 25 /* MinusToken */: + case 38 /* TildeToken */: + case 37 /* ExclamationToken */: + case 64 /* DeleteKeyword */: + case 87 /* TypeOfKeyword */: + case 89 /* VoidKeyword */: + case 29 /* PlusPlusToken */: + case 30 /* MinusMinusToken */: + var operator = token; + nextToken(); + var operand = parseUnaryExpression(); + if (isInStrictMode) { + if ((token === 29 /* PlusPlusToken */ || token === 30 /* MinusMinusToken */) && isEvalOrArgumentsIdentifier(operand)) { + reportInvalidUseInStrictMode(operand); + } + else if (token === 64 /* DeleteKeyword */ && operand.kind === 55 /* Identifier */) { + grammarErrorOnNode(operand, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); + } + } + return makeUnaryExpression(138 /* PrefixOperator */, pos, operator, operand); + case 15 /* LessThanToken */: + return parseTypeAssertion(); + } + var primaryExpression = parsePrimaryExpression(); + var illegalUsageOfSuperKeyword = primaryExpression.kind === 81 /* SuperKeyword */ && token !== 7 /* OpenParenToken */ && token !== 11 /* DotToken */; + if (illegalUsageOfSuperKeyword) { + error(ts.Diagnostics.super_must_be_followed_by_argument_list_or_member_access); + } + var expr = parseCallAndAccess(primaryExpression, false); + ts.Debug.assert(isLeftHandSideExpression(expr)); + if ((token === 29 /* PlusPlusToken */ || token === 30 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + if (isInStrictMode && isEvalOrArgumentsIdentifier(expr)) { + reportInvalidUseInStrictMode(expr); + } + var operator = token; + nextToken(); + expr = makeUnaryExpression(139 /* PostfixOperator */, expr.pos, operator, expr); + } + return expr; + } + function parseTypeAssertion() { + var node = createNode(134 /* TypeAssertion */); + parseExpected(15 /* LessThanToken */); + node.type = parseType(); + parseExpected(16 /* GreaterThanToken */); + node.operand = parseUnaryExpression(); + return finishNode(node); + } + function makeUnaryExpression(kind, pos, operator, operand) { + var node = createNode(kind, pos); + node.operator = operator; + node.operand = operand; + return finishNode(node); + } + function parseCallAndAccess(expr, inNewExpression) { + while (true) { + if (parseOptional(11 /* DotToken */)) { + var propertyAccess = createNode(130 /* PropertyAccess */, expr.pos); + propertyAccess.left = expr; + propertyAccess.right = parseIdentifierName(); + expr = finishNode(propertyAccess); + continue; + } + var bracketStart = scanner.getTokenPos(); + if (parseOptional(9 /* OpenBracketToken */)) { + var indexedAccess = createNode(131 /* IndexedAccess */, expr.pos); + indexedAccess.object = expr; + if (inNewExpression && parseOptional(10 /* CloseBracketToken */)) { + indexedAccess.index = createMissingNode(); + grammarErrorAtPos(bracketStart, scanner.getStartPos() - bracketStart, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + indexedAccess.index = parseExpression(); + parseExpected(10 /* CloseBracketToken */); + } + expr = finishNode(indexedAccess); + continue; + } + if ((token === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */) && !inNewExpression) { + var callExpr = createNode(132 /* CallExpression */, expr.pos); + callExpr.func = expr; + if (token === 15 /* LessThanToken */) { + if (!(callExpr.typeArguments = tryParse(parseTypeArgumentsAndOpenParen))) + return expr; + } + else { + parseExpected(7 /* OpenParenToken */); + } + callExpr.arguments = parseDelimitedList(10 /* ArgumentExpressions */, parseAssignmentExpression, 0 /* Disallow */); + parseExpected(8 /* CloseParenToken */); + expr = finishNode(callExpr); + continue; + } + return expr; + } + } + function parseTypeArgumentsAndOpenParen() { + var result = parseTypeArguments(); + parseExpected(7 /* OpenParenToken */); + return result; + } + function parseTypeArguments() { + var typeArgumentListStart = scanner.getTokenPos(); + var errorCountBeforeTypeParameterList = file.syntacticErrors.length; + var result = parseBracketedList(15 /* TypeArguments */, parseType, 15 /* LessThanToken */, 16 /* GreaterThanToken */); + if (!result.length && file.syntacticErrors.length === errorCountBeforeTypeParameterList) { + grammarErrorAtPos(typeArgumentListStart, scanner.getStartPos() - typeArgumentListStart, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + return result; + } + function parsePrimaryExpression() { + switch (token) { + case 83 /* ThisKeyword */: + case 81 /* SuperKeyword */: + case 79 /* NullKeyword */: + case 85 /* TrueKeyword */: + case 70 /* FalseKeyword */: + return parseTokenNode(); + case 2 /* NumericLiteral */: + case 3 /* StringLiteral */: + return parseLiteralNode(); + case 7 /* OpenParenToken */: + return parseParenExpression(); + case 9 /* OpenBracketToken */: + return parseArrayLiteral(); + case 5 /* OpenBraceToken */: + return parseObjectLiteral(); + case 73 /* FunctionKeyword */: + return parseFunctionExpression(); + case 78 /* NewKeyword */: + return parseNewExpression(); + case 27 /* SlashToken */: + case 47 /* SlashEqualsToken */: + if (reScanSlashToken() === 4 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + default: + if (isIdentifier()) { + return parseIdentifier(); + } + } + error(ts.Diagnostics.Expression_expected); + return createMissingNode(); + } + function parseParenExpression() { + var node = createNode(135 /* ParenExpression */); + parseExpected(7 /* OpenParenToken */); + node.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + return finishNode(node); + } + function parseArrayLiteralElement() { + return token === 14 /* CommaToken */ ? createNode(142 /* OmittedExpression */) : parseAssignmentExpression(); + } + function parseArrayLiteral() { + var node = createNode(127 /* ArrayLiteral */); + parseExpected(9 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) + node.flags |= 128 /* MultiLine */; + node.elements = parseDelimitedList(12 /* ArrayLiteralMembers */, parseArrayLiteralElement, 2 /* Preserve */); + parseExpected(10 /* CloseBracketToken */); + return finishNode(node); + } + function parsePropertyAssignment() { + var node = createNode(129 /* PropertyAssignment */); + node.name = parsePropertyName(); + if (token === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */) { + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + var body = parseBody(false); + node.initializer = makeFunctionExpression(136 /* FunctionExpression */, node.pos, undefined, sig, body); + } + else { + parseExpected(42 /* ColonToken */); + node.initializer = parseAssignmentExpression(false); + } + return finishNode(node); + } + function parseObjectLiteralMember() { + var initialPos = getNodePos(); + var initialToken = token; + if (parseContextualModifier(105 /* GetKeyword */) || parseContextualModifier(109 /* SetKeyword */)) { + var kind = initialToken === 105 /* GetKeyword */ ? 118 /* GetAccessor */ : 119 /* SetAccessor */; + return parseAndCheckMemberAccessorDeclaration(kind, initialPos, 0); + } + return parsePropertyAssignment(); + } + function parseObjectLiteral() { + var node = createNode(128 /* ObjectLiteral */); + parseExpected(5 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.flags |= 128 /* MultiLine */; + } + var trailingCommaBehavior = languageVersion === 0 /* ES3 */ ? 1 /* Allow */ : 2 /* Preserve */; + node.properties = parseDelimitedList(11 /* ObjectLiteralMembers */, parseObjectLiteralMember, trailingCommaBehavior); + parseExpected(6 /* CloseBraceToken */); + var seen = {}; + var Property = 1; + var GetAccessor = 2; + var SetAccesor = 4; + var GetOrSetAccessor = GetAccessor | SetAccesor; + ts.forEach(node.properties, function (p) { + if (p.kind === 142 /* OmittedExpression */) { + return; + } + var currentKind; + if (p.kind === 129 /* PropertyAssignment */) { + currentKind = Property; + } + else if (p.kind === 118 /* GetAccessor */) { + currentKind = GetAccessor; + } + else if (p.kind === 119 /* SetAccessor */) { + currentKind = SetAccesor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + ts.SyntaxKind[p.kind]); + } + if (!ts.hasProperty(seen, p.name.text)) { + seen[p.name.text] = currentKind; + } + else { + var existingKind = seen[p.name.text]; + if (currentKind === Property && existingKind === Property) { + if (isInStrictMode) { + grammarErrorOnNode(p.name, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); + } + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen[p.name.text] = currentKind | existingKind; + } + else { + grammarErrorOnNode(p.name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + grammarErrorOnNode(p.name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + }); + return finishNode(node); + } + function parseFunctionExpression() { + var pos = getNodePos(); + parseExpected(73 /* FunctionKeyword */); + var name = isIdentifier() ? parseIdentifier() : undefined; + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + var body = parseBody(false); + if (name && isInStrictMode && isEvalOrArgumentsIdentifier(name)) { + reportInvalidUseInStrictMode(name); + } + return makeFunctionExpression(136 /* FunctionExpression */, pos, name, sig, body); + } + function makeFunctionExpression(kind, pos, name, sig, body) { + var node = createNode(kind, pos); + node.name = name; + node.typeParameters = sig.typeParameters; + node.parameters = sig.parameters; + node.type = sig.type; + node.body = body; + return finishNode(node); + } + function parseNewExpression() { + var node = createNode(133 /* NewExpression */); + parseExpected(78 /* NewKeyword */); + node.func = parseCallAndAccess(parsePrimaryExpression(), true); + if (parseOptional(7 /* OpenParenToken */) || token === 15 /* LessThanToken */ && (node.typeArguments = tryParse(parseTypeArgumentsAndOpenParen))) { + node.arguments = parseDelimitedList(10 /* ArgumentExpressions */, parseAssignmentExpression, 0 /* Disallow */); + parseExpected(8 /* CloseParenToken */); + } + return finishNode(node); + } + function parseBlock(ignoreMissingOpenBrace, checkForStrictMode) { + var node = createNode(143 /* Block */); + if (parseExpected(5 /* OpenBraceToken */) || ignoreMissingOpenBrace) { + node.statements = parseList(2 /* BlockStatements */, checkForStrictMode, parseStatement); + parseExpected(6 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseBody(ignoreMissingOpenBrace) { + var saveInFunctionBody = inFunctionBody; + var saveInSwitchStatement = inSwitchStatement; + var saveInIterationStatement = inIterationStatement; + inFunctionBody = true; + if (inSwitchStatement === 1 /* Nested */) { + inSwitchStatement = 2 /* CrossingFunctionBoundary */; + } + if (inIterationStatement === 1 /* Nested */) { + inIterationStatement = 2 /* CrossingFunctionBoundary */; + } + labelledStatementInfo.pushFunctionBoundary(); + var block = parseBlock(ignoreMissingOpenBrace, true); + block.kind = 168 /* FunctionBlock */; + labelledStatementInfo.pop(); + inFunctionBody = saveInFunctionBody; + inSwitchStatement = saveInSwitchStatement; + inIterationStatement = saveInIterationStatement; + return block; + } + function parseEmptyStatement() { + var node = createNode(145 /* EmptyStatement */); + parseExpected(13 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(147 /* IfStatement */); + parseExpected(74 /* IfKeyword */); + parseExpected(7 /* OpenParenToken */); + node.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(66 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(148 /* DoStatement */); + parseExpected(65 /* DoKeyword */); + var saveInIterationStatement = inIterationStatement; + inIterationStatement = 1 /* Nested */; + node.statement = parseStatement(); + inIterationStatement = saveInIterationStatement; + parseExpected(90 /* WhileKeyword */); + parseExpected(7 /* OpenParenToken */); + node.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + parseOptional(13 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(149 /* WhileStatement */); + parseExpected(90 /* WhileKeyword */); + parseExpected(7 /* OpenParenToken */); + node.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + var saveInIterationStatement = inIterationStatement; + inIterationStatement = 1 /* Nested */; + node.statement = parseStatement(); + inIterationStatement = saveInIterationStatement; + return finishNode(node); + } + function parseForOrForInStatement() { + var pos = getNodePos(); + parseExpected(72 /* ForKeyword */); + parseExpected(7 /* OpenParenToken */); + if (token !== 13 /* SemicolonToken */) { + if (parseOptional(88 /* VarKeyword */)) { + var declarations = parseVariableDeclarationList(0, true); + if (!declarations.length) { + error(ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + else { + var varOrInit = parseExpression(true); + } + } + var forOrForInStatement; + if (parseOptional(76 /* InKeyword */)) { + var forInStatement = createNode(151 /* ForInStatement */, pos); + if (declarations) { + if (declarations.length > 1) { + error(ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + } + forInStatement.declaration = declarations[0]; + } + else { + forInStatement.variable = varOrInit; + } + forInStatement.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + forOrForInStatement = forInStatement; + } + else { + var forStatement = createNode(150 /* ForStatement */, pos); + if (declarations) + forStatement.declarations = declarations; + if (varOrInit) + forStatement.initializer = varOrInit; + parseExpected(13 /* SemicolonToken */); + if (token !== 13 /* SemicolonToken */ && token !== 8 /* CloseParenToken */) { + forStatement.condition = parseExpression(); + } + parseExpected(13 /* SemicolonToken */); + if (token !== 8 /* CloseParenToken */) { + forStatement.iterator = parseExpression(); + } + parseExpected(8 /* CloseParenToken */); + forOrForInStatement = forStatement; + } + var saveInIterationStatement = inIterationStatement; + inIterationStatement = 1 /* Nested */; + forOrForInStatement.statement = parseStatement(); + inIterationStatement = saveInIterationStatement; + return finishNode(forOrForInStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + var errorCountBeforeStatement = file.syntacticErrors.length; + var keywordStart = scanner.getTokenPos(); + var keywordLength = scanner.getTextPos() - keywordStart; + parseExpected(kind === 153 /* BreakStatement */ ? 56 /* BreakKeyword */ : 61 /* ContinueKeyword */); + if (!canParseSemicolon()) + node.label = parseIdentifier(); + parseSemicolon(); + finishNode(node); + if (!inAmbientContext && errorCountBeforeStatement === file.syntacticErrors.length) { + if (node.label) { + checkBreakOrContinueStatementWithLabel(node); + } + else { + checkBareBreakOrContinueStatement(node); + } + } + return node; + } + function checkBareBreakOrContinueStatement(node) { + if (node.kind === 153 /* BreakStatement */) { + if (inIterationStatement === 1 /* Nested */ || inSwitchStatement === 1 /* Nested */) { + return; + } + else if (inIterationStatement === 0 /* NotNested */ && inSwitchStatement === 0 /* NotNested */) { + grammarErrorOnNode(node, ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement); + return; + } + } + else if (node.kind === 152 /* ContinueStatement */) { + if (inIterationStatement === 1 /* Nested */) { + return; + } + else if (inIterationStatement === 0 /* NotNested */) { + grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement); + return; + } + } + else { + ts.Debug.fail("checkAnonymousBreakOrContinueStatement"); + } + ts.Debug.assert(inIterationStatement === 2 /* CrossingFunctionBoundary */ || inSwitchStatement === 2 /* CrossingFunctionBoundary */); + grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + function checkBreakOrContinueStatementWithLabel(node) { + var nodeIsNestedInLabel = labelledStatementInfo.nodeIsNestedInLabel(node.label, node.kind === 152 /* ContinueStatement */, false); + if (nodeIsNestedInLabel === 1 /* Nested */) { + return; + } + if (nodeIsNestedInLabel === 2 /* CrossingFunctionBoundary */) { + grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + return; + } + if (node.kind === 152 /* ContinueStatement */) { + grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + else if (node.kind === 153 /* BreakStatement */) { + grammarErrorOnNode(node, ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement); + } + else { + ts.Debug.fail("checkBreakOrContinueStatementWithLabel"); + } + } + function parseReturnStatement() { + var node = createNode(154 /* ReturnStatement */); + var errorCountBeforeReturnStatement = file.syntacticErrors.length; + var returnTokenStart = scanner.getTokenPos(); + var returnTokenLength = scanner.getTextPos() - returnTokenStart; + parseExpected(80 /* ReturnKeyword */); + if (!canParseSemicolon()) + node.expression = parseExpression(); + parseSemicolon(); + if (!inFunctionBody && !inAmbientContext && errorCountBeforeReturnStatement === file.syntacticErrors.length) { + grammarErrorAtPos(returnTokenStart, returnTokenLength, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(155 /* WithStatement */); + var startPos = scanner.getTokenPos(); + parseExpected(91 /* WithKeyword */); + var endPos = scanner.getStartPos(); + parseExpected(7 /* OpenParenToken */); + node.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + node.statement = parseStatement(); + node = finishNode(node); + if (isInStrictMode) { + grammarErrorAtPos(startPos, endPos - startPos, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + return node; + } + function parseCaseClause() { + var node = createNode(157 /* CaseClause */); + parseExpected(57 /* CaseKeyword */); + node.expression = parseExpression(); + parseExpected(42 /* ColonToken */); + node.statements = parseList(4 /* SwitchClauseStatements */, false, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(158 /* DefaultClause */); + parseExpected(63 /* DefaultKeyword */); + parseExpected(42 /* ColonToken */); + node.statements = parseList(4 /* SwitchClauseStatements */, false, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token === 57 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(156 /* SwitchStatement */); + parseExpected(82 /* SwitchKeyword */); + parseExpected(7 /* OpenParenToken */); + node.expression = parseExpression(); + parseExpected(8 /* CloseParenToken */); + parseExpected(5 /* OpenBraceToken */); + var saveInSwitchStatement = inSwitchStatement; + inSwitchStatement = 1 /* Nested */; + node.clauses = parseList(3 /* SwitchClauses */, false, parseCaseOrDefaultClause); + inSwitchStatement = saveInSwitchStatement; + parseExpected(6 /* CloseBraceToken */); + var defaultClauses = ts.filter(node.clauses, function (clause) { return clause.kind === 158 /* DefaultClause */; }); + for (var i = 1, n = defaultClauses.length; i < n; i++) { + var clause = defaultClauses[i]; + var start = ts.skipTrivia(file.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + } + return finishNode(node); + } + function parseThrowStatement() { + var node = createNode(160 /* ThrowStatement */); + parseExpected(84 /* ThrowKeyword */); + if (scanner.hasPrecedingLineBreak()) { + error(ts.Diagnostics.Line_break_not_permitted_here); + } + node.expression = parseExpression(); + parseSemicolon(); + return finishNode(node); + } + function parseTryStatement() { + var node = createNode(161 /* TryStatement */); + node.tryBlock = parseTokenAndBlock(86 /* TryKeyword */, 162 /* TryBlock */); + if (token === 58 /* CatchKeyword */) { + node.catchBlock = parseCatchBlock(); + } + if (token === 71 /* FinallyKeyword */) { + node.finallyBlock = parseTokenAndBlock(71 /* FinallyKeyword */, 164 /* FinallyBlock */); + } + if (!(node.catchBlock || node.finallyBlock)) { + error(ts.Diagnostics.catch_or_finally_expected); + } + return finishNode(node); + } + function parseTokenAndBlock(token, kind) { + var pos = getNodePos(); + parseExpected(token); + var result = parseBlock(false, false); + result.kind = kind; + result.pos = pos; + return result; + } + function parseCatchBlock() { + var pos = getNodePos(); + parseExpected(58 /* CatchKeyword */); + parseExpected(7 /* OpenParenToken */); + var variable = parseIdentifier(); + var typeAnnotationColonStart = scanner.getTokenPos(); + var typeAnnotationColonLength = scanner.getTextPos() - typeAnnotationColonStart; + var typeAnnotation = parseTypeAnnotation(); + parseExpected(8 /* CloseParenToken */); + var result = parseBlock(false, false); + result.kind = 163 /* CatchBlock */; + result.pos = pos; + result.variable = variable; + if (typeAnnotation) { + errorAtPos(typeAnnotationColonStart, typeAnnotationColonLength, ts.Diagnostics.Catch_clause_parameter_cannot_have_a_type_annotation); + } + if (isInStrictMode && isEvalOrArgumentsIdentifier(variable)) { + reportInvalidUseInStrictMode(variable); + } + return result; + } + function parseDebuggerStatement() { + var node = createNode(165 /* DebuggerStatement */); + parseExpected(62 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function isIterationStatementStart() { + return token === 90 /* WhileKeyword */ || token === 65 /* DoKeyword */ || token === 72 /* ForKeyword */; + } + function parseStatementWithLabelSet() { + labelledStatementInfo.pushCurrentLabelSet(isIterationStatementStart()); + var statement = parseStatement(); + labelledStatementInfo.pop(); + return statement; + } + function isLabel() { + return isIdentifier() && lookAhead(function () { return nextToken() === 42 /* ColonToken */; }); + } + function parseLabelledStatement() { + var node = createNode(159 /* LabelledStatement */); + node.label = parseIdentifier(); + parseExpected(42 /* ColonToken */); + if (labelledStatementInfo.nodeIsNestedInLabel(node.label, false, true)) { + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, getSourceTextOfNodeFromSourceText(sourceText, node.label)); + } + labelledStatementInfo.addLabel(node.label); + node.statement = isLabel() ? parseLabelledStatement() : parseStatementWithLabelSet(); + return finishNode(node); + } + function parseExpressionStatement() { + var node = createNode(146 /* ExpressionStatement */); + node.expression = parseExpression(); + parseSemicolon(); + return finishNode(node); + } + function isStatement(inErrorRecovery) { + switch (token) { + case 13 /* SemicolonToken */: + return !inErrorRecovery; + case 5 /* OpenBraceToken */: + case 88 /* VarKeyword */: + case 73 /* FunctionKeyword */: + case 74 /* IfKeyword */: + case 65 /* DoKeyword */: + case 90 /* WhileKeyword */: + case 72 /* ForKeyword */: + case 61 /* ContinueKeyword */: + case 56 /* BreakKeyword */: + case 80 /* ReturnKeyword */: + case 91 /* WithKeyword */: + case 82 /* SwitchKeyword */: + case 84 /* ThrowKeyword */: + case 86 /* TryKeyword */: + case 62 /* DebuggerKeyword */: + return true; + case 93 /* InterfaceKeyword */: + case 59 /* ClassKeyword */: + case 106 /* ModuleKeyword */: + case 67 /* EnumKeyword */: + if (isDeclaration()) + return false; + case 98 /* PublicKeyword */: + case 96 /* PrivateKeyword */: + case 99 /* StaticKeyword */: + if (lookAhead(function () { return nextToken() >= 55 /* Identifier */; })) + return false; + default: + return isExpression(); + } + } + function parseStatement() { + switch (token) { + case 5 /* OpenBraceToken */: + return parseBlock(false, false); + case 88 /* VarKeyword */: + return parseVariableStatement(); + case 73 /* FunctionKeyword */: + return parseFunctionDeclaration(); + case 13 /* SemicolonToken */: + return parseEmptyStatement(); + case 74 /* IfKeyword */: + return parseIfStatement(); + case 65 /* DoKeyword */: + return parseDoStatement(); + case 90 /* WhileKeyword */: + return parseWhileStatement(); + case 72 /* ForKeyword */: + return parseForOrForInStatement(); + case 61 /* ContinueKeyword */: + return parseBreakOrContinueStatement(152 /* ContinueStatement */); + case 56 /* BreakKeyword */: + return parseBreakOrContinueStatement(153 /* BreakStatement */); + case 80 /* ReturnKeyword */: + return parseReturnStatement(); + case 91 /* WithKeyword */: + return parseWithStatement(); + case 82 /* SwitchKeyword */: + return parseSwitchStatement(); + case 84 /* ThrowKeyword */: + return parseThrowStatement(); + case 86 /* TryKeyword */: + return parseTryStatement(); + case 62 /* DebuggerKeyword */: + return parseDebuggerStatement(); + default: + if (isLabel()) { + return parseLabelledStatement(); + } + return parseExpressionStatement(); + } + } + function parseStatementOrFunction() { + return token === 73 /* FunctionKeyword */ ? parseFunctionDeclaration() : parseStatement(); + } + function parseAndCheckFunctionBody(isConstructor) { + var initialPosition = scanner.getTokenPos(); + var errorCountBeforeBody = file.syntacticErrors.length; + if (token === 5 /* OpenBraceToken */) { + var body = parseBody(false); + if (body && inAmbientContext && file.syntacticErrors.length === errorCountBeforeBody) { + var diagnostic = isConstructor ? ts.Diagnostics.A_constructor_implementation_cannot_be_declared_in_an_ambient_context : ts.Diagnostics.A_function_implementation_cannot_be_declared_in_an_ambient_context; + grammarErrorAtPos(initialPosition, 1, diagnostic); + } + return body; + } + if (canParseSemicolon()) { + parseSemicolon(); + return undefined; + } + error(ts.Diagnostics.Block_or_expected); + } + function parseVariableDeclaration(flags, noIn) { + var node = createNode(166 /* VariableDeclaration */); + node.flags = flags; + var errorCountBeforeVariableDeclaration = file.syntacticErrors.length; + node.name = parseIdentifier(); + node.type = parseTypeAnnotation(); + var initializerStart = scanner.getTokenPos(); + var initializerFirstTokenLength = scanner.getTextPos() - initializerStart; + node.initializer = parseInitializer(false, noIn); + if (inAmbientContext && node.initializer && errorCountBeforeVariableDeclaration === file.syntacticErrors.length) { + grammarErrorAtPos(initializerStart, initializerFirstTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (isInStrictMode && isEvalOrArgumentsIdentifier(node.name)) { + reportInvalidUseInStrictMode(node.name); + } + return finishNode(node); + } + function parseVariableDeclarationList(flags, noIn) { + return parseDelimitedList(9 /* VariableDeclarations */, function () { return parseVariableDeclaration(flags, noIn); }, 0 /* Disallow */); + } + function parseVariableStatement(pos, flags) { + var node = createNode(144 /* VariableStatement */, pos); + if (flags) + node.flags = flags; + var errorCountBeforeVarStatement = file.syntacticErrors.length; + parseExpected(88 /* VarKeyword */); + node.declarations = parseVariableDeclarationList(flags, false); + parseSemicolon(); + if (!node.declarations.length && file.syntacticErrors.length === errorCountBeforeVarStatement) { + grammarErrorOnNode(node, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + return finishNode(node); + } + function parseFunctionDeclaration(pos, flags) { + var node = createNode(167 /* FunctionDeclaration */, pos); + if (flags) + node.flags = flags; + parseExpected(73 /* FunctionKeyword */); + node.name = parseIdentifier(); + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + node.typeParameters = sig.typeParameters; + node.parameters = sig.parameters; + node.type = sig.type; + node.body = parseAndCheckFunctionBody(false); + if (isInStrictMode && isEvalOrArgumentsIdentifier(node.name)) { + reportInvalidUseInStrictMode(node.name); + } + return finishNode(node); + } + function parseConstructorDeclaration(pos, flags) { + var node = createNode(117 /* Constructor */, pos); + node.flags = flags; + parseExpected(103 /* ConstructorKeyword */); + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + node.typeParameters = sig.typeParameters; + node.parameters = sig.parameters; + node.type = sig.type; + node.body = parseAndCheckFunctionBody(true); + if (node.typeParameters) { + grammarErrorAtPos(node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + if (node.type) { + grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + return finishNode(node); + } + function parsePropertyMemberDeclaration(pos, flags) { + var errorCountBeforePropertyDeclaration = file.syntacticErrors.length; + var name = parsePropertyName(); + var questionStart = scanner.getTokenPos(); + if (parseOptional(41 /* QuestionToken */)) { + errorAtPos(questionStart, scanner.getStartPos() - questionStart, ts.Diagnostics.A_class_member_cannot_be_declared_optional); + } + if (token === 7 /* OpenParenToken */ || token === 15 /* LessThanToken */) { + var method = createNode(116 /* Method */, pos); + method.flags = flags; + method.name = name; + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + method.typeParameters = sig.typeParameters; + method.parameters = sig.parameters; + method.type = sig.type; + method.body = parseAndCheckFunctionBody(false); + return finishNode(method); + } + else { + var property = createNode(115 /* Property */, pos); + property.flags = flags; + property.name = name; + property.type = parseTypeAnnotation(); + var initializerStart = scanner.getTokenPos(); + var initializerFirstTokenLength = scanner.getTextPos() - initializerStart; + property.initializer = parseInitializer(false); + parseSemicolon(); + if (inAmbientContext && property.initializer && errorCountBeforePropertyDeclaration === file.syntacticErrors.length) { + grammarErrorAtPos(initializerStart, initializerFirstTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + return finishNode(property); + } + } + function parseAndCheckMemberAccessorDeclaration(kind, pos, flags) { + var errorCountBeforeAccessor = file.syntacticErrors.length; + var accessor = parseMemberAccessorDeclaration(kind, pos, flags); + if (errorCountBeforeAccessor === file.syntacticErrors.length) { + if (languageVersion < 1 /* ES5 */) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (inAmbientContext) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.typeParameters) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (kind === 118 /* GetAccessor */ && accessor.parameters.length) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); + } + else if (kind === 119 /* SetAccessor */) { + if (accessor.type) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else if (accessor.parameters.length !== 1) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.flags & 8 /* Rest */) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.flags & ts.NodeFlags.Modifier) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + else if (parameter.flags & 4 /* QuestionMark */) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + return accessor; + } + function parseMemberAccessorDeclaration(kind, pos, flags) { + var node = createNode(kind, pos); + node.flags = flags; + node.name = parsePropertyName(); + var sig = parseSignature(120 /* CallSignature */, 42 /* ColonToken */); + node.typeParameters = sig.typeParameters; + node.parameters = sig.parameters; + node.type = sig.type; + if (inAmbientContext && canParseSemicolon()) { + parseSemicolon(); + node.body = createMissingNode(); + } + else { + node.body = parseBody(false); + } + return finishNode(node); + } + function isClassMemberStart() { + var idToken; + while (isModifier(token)) { + idToken = token; + nextToken(); + } + if (isPropertyName()) { + idToken = token; + nextToken(); + } + if (token === 9 /* OpenBracketToken */) { + return true; + } + if (idToken !== undefined) { + if (!isKeyword(idToken) || idToken === 109 /* SetKeyword */ || idToken === 105 /* GetKeyword */) { + return true; + } + switch (token) { + case 7 /* OpenParenToken */: + case 15 /* LessThanToken */: + case 42 /* ColonToken */: + case 43 /* EqualsToken */: + case 41 /* QuestionToken */: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseAndCheckModifiers(context) { + var flags = 0; + var lastStaticModifierStart; + var lastStaticModifierLength; + var lastDeclareModifierStart; + var lastDeclareModifierLength; + var lastPrivateModifierStart; + var lastPrivateModifierLength; + while (true) { + var modifierStart = scanner.getTokenPos(); + var modifierToken = token; + if (!parseAnyContextualModifier()) + break; + var modifierLength = scanner.getStartPos() - modifierStart; + switch (modifierToken) { + case 98 /* PublicKeyword */: + if (flags & 32 /* Private */ || flags & 16 /* Public */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 64 /* Static */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_must_precede_1_modifier, "public", "static"); + } + else if (context === 1 /* ModuleElements */ || context === 0 /* SourceElements */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "public"); + } + flags |= 16 /* Public */; + break; + case 96 /* PrivateKeyword */: + if (flags & 32 /* Private */ || flags & 16 /* Public */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 64 /* Static */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_must_precede_1_modifier, "private", "static"); + } + else if (context === 1 /* ModuleElements */ || context === 0 /* SourceElements */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "private"); + } + lastPrivateModifierStart = modifierStart; + lastPrivateModifierLength = modifierLength; + flags |= 32 /* Private */; + break; + case 99 /* StaticKeyword */: + if (flags & 64 /* Static */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (context === 1 /* ModuleElements */ || context === 0 /* SourceElements */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + } + else if (context === 3 /* Parameters */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + lastStaticModifierStart = modifierStart; + lastStaticModifierLength = modifierLength; + flags |= 64 /* Static */; + break; + case 68 /* ExportKeyword */: + if (flags & 1 /* Export */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (context === 2 /* ClassMembers */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (context === 3 /* Parameters */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 104 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (context === 2 /* ClassMembers */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (context === 3 /* Parameters */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (inAmbientContext && context === 1 /* ModuleElements */) { + grammarErrorAtPos(modifierStart, modifierLength, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + lastDeclareModifierStart = modifierStart; + lastDeclareModifierLength = modifierLength; + flags |= 2 /* Ambient */; + break; + } + } + if (token === 103 /* ConstructorKeyword */ && flags & 64 /* Static */) { + grammarErrorAtPos(lastStaticModifierStart, lastStaticModifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + else if (token === 103 /* ConstructorKeyword */ && flags & 32 /* Private */) { + grammarErrorAtPos(lastPrivateModifierStart, lastPrivateModifierLength, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); + } + else if (token === 75 /* ImportKeyword */) { + if (flags & 2 /* Ambient */) { + grammarErrorAtPos(lastDeclareModifierStart, lastDeclareModifierLength, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + } + else if (token === 93 /* InterfaceKeyword */) { + if (flags & 2 /* Ambient */) { + grammarErrorAtPos(lastDeclareModifierStart, lastDeclareModifierLength, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); + } + } + else if (token !== 68 /* ExportKeyword */ && !(flags & 2 /* Ambient */) && inAmbientContext && context === 0 /* SourceElements */) { + var declarationStart = scanner.getTokenPos(); + var declarationFirstTokenLength = scanner.getTextPos() - declarationStart; + grammarErrorAtPos(declarationStart, declarationFirstTokenLength, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + return flags; + } + function parseClassMemberDeclaration() { + var pos = getNodePos(); + var flags = parseAndCheckModifiers(2 /* ClassMembers */); + if (parseContextualModifier(105 /* GetKeyword */)) { + return parseAndCheckMemberAccessorDeclaration(118 /* GetAccessor */, pos, flags); + } + if (parseContextualModifier(109 /* SetKeyword */)) { + return parseAndCheckMemberAccessorDeclaration(119 /* SetAccessor */, pos, flags); + } + if (token === 103 /* ConstructorKeyword */) { + return parseConstructorDeclaration(pos, flags); + } + if (token >= 55 /* Identifier */ || token === 3 /* StringLiteral */ || token === 2 /* NumericLiteral */) { + return parsePropertyMemberDeclaration(pos, flags); + } + if (token === 9 /* OpenBracketToken */) { + if (flags) { + var start = getTokenPos(pos); + var length = getNodePos() - start; + errorAtPos(start, length, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); + } + return parseIndexSignatureMember(); + } + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassDeclaration(pos, flags) { + var node = createNode(169 /* ClassDeclaration */, pos); + node.flags = flags; + var errorCountBeforeClassDeclaration = file.syntacticErrors.length; + parseExpected(59 /* ClassKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.baseType = parseOptional(69 /* ExtendsKeyword */) ? parseTypeReference() : undefined; + var implementsKeywordStart = scanner.getTokenPos(); + var implementsKeywordLength; + if (parseOptional(92 /* ImplementsKeyword */)) { + implementsKeywordLength = scanner.getStartPos() - implementsKeywordStart; + node.implementedTypes = parseDelimitedList(8 /* BaseTypeReferences */, parseTypeReference, 0 /* Disallow */); + } + var errorCountBeforeClassBody = file.syntacticErrors.length; + if (parseExpected(5 /* OpenBraceToken */)) { + node.members = parseList(6 /* ClassMembers */, false, parseClassMemberDeclaration); + parseExpected(6 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + if (node.implementedTypes && !node.implementedTypes.length && errorCountBeforeClassBody === errorCountBeforeClassDeclaration) { + grammarErrorAtPos(implementsKeywordStart, implementsKeywordLength, ts.Diagnostics._0_list_cannot_be_empty, "implements"); + } + return finishNode(node); + } + function parseInterfaceDeclaration(pos, flags) { + var node = createNode(170 /* InterfaceDeclaration */, pos); + node.flags = flags; + var errorCountBeforeInterfaceDeclaration = file.syntacticErrors.length; + parseExpected(93 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + var extendsKeywordStart = scanner.getTokenPos(); + var extendsKeywordLength; + if (parseOptional(69 /* ExtendsKeyword */)) { + extendsKeywordLength = scanner.getStartPos() - extendsKeywordStart; + node.baseTypes = parseDelimitedList(8 /* BaseTypeReferences */, parseTypeReference, 0 /* Disallow */); + } + var errorCountBeforeInterfaceBody = file.syntacticErrors.length; + node.members = parseTypeLiteral().members; + if (node.baseTypes && !node.baseTypes.length && errorCountBeforeInterfaceBody === errorCountBeforeInterfaceDeclaration) { + grammarErrorAtPos(extendsKeywordStart, extendsKeywordLength, ts.Diagnostics._0_list_cannot_be_empty, "extends"); + } + return finishNode(node); + } + function parseAndCheckEnumDeclaration(pos, flags) { + function isIntegerLiteral(expression) { + function isInteger(literalExpression) { + return /^[0-9]+([eE]\+?[0-9]+)?$/.test(literalExpression.text); + } + if (expression.kind === 138 /* PrefixOperator */) { + var unaryExpression = expression; + if (unaryExpression.operator === 24 /* PlusToken */ || unaryExpression.operator === 25 /* MinusToken */) { + expression = unaryExpression.operand; + } + } + if (expression.kind === 2 /* NumericLiteral */) { + return isInteger(expression); + } + return false; + } + var inConstantEnumMemberSection = true; + function parseAndCheckEnumMember() { + var node = createNode(176 /* EnumMember */); + var errorCountBeforeEnumMember = file.syntacticErrors.length; + node.name = parsePropertyName(); + node.initializer = parseInitializer(false); + if (inAmbientContext) { + if (node.initializer && !isIntegerLiteral(node.initializer) && errorCountBeforeEnumMember === file.syntacticErrors.length) { + grammarErrorOnNode(node.name, ts.Diagnostics.Ambient_enum_elements_can_only_have_integer_literal_initializers); + } + } + else if (node.initializer) { + inConstantEnumMemberSection = isIntegerLiteral(node.initializer); + } + else if (!inConstantEnumMemberSection && errorCountBeforeEnumMember === file.syntacticErrors.length) { + grammarErrorOnNode(node.name, ts.Diagnostics.Enum_member_must_have_initializer); + } + return finishNode(node); + } + var node = createNode(171 /* EnumDeclaration */, pos); + node.flags = flags; + parseExpected(67 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(5 /* OpenBraceToken */)) { + node.members = parseDelimitedList(7 /* EnumMembers */, parseAndCheckEnumMember, 1 /* Allow */); + parseExpected(6 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBody() { + var node = createNode(173 /* ModuleBlock */); + if (parseExpected(5 /* OpenBraceToken */)) { + node.statements = parseList(1 /* ModuleElements */, false, parseModuleElement); + parseExpected(6 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseInternalModuleTail(pos, flags) { + var node = createNode(172 /* ModuleDeclaration */, pos); + node.flags = flags; + node.name = parseIdentifier(); + if (parseOptional(11 /* DotToken */)) { + node.body = parseInternalModuleTail(getNodePos(), 1 /* Export */); + } + else { + node.body = parseModuleBody(); + ts.forEach(node.body.statements, function (s) { + if (s.kind === 175 /* ExportAssignment */) { + grammarErrorOnNode(s, ts.Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); + } + else if (s.kind === 174 /* ImportDeclaration */ && s.externalModuleName) { + grammarErrorOnNode(s, ts.Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + } + }); + } + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(pos, flags) { + var node = createNode(172 /* ModuleDeclaration */, pos); + node.flags = flags; + node.name = parseStringLiteral(); + if (!inAmbientContext) { + var errorCount = file.syntacticErrors.length; + if (!errorCount || file.syntacticErrors[errorCount - 1].start < getTokenPos(pos)) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + var saveInAmbientContext = inAmbientContext; + inAmbientContext = true; + node.body = parseModuleBody(); + inAmbientContext = saveInAmbientContext; + return finishNode(node); + } + function parseModuleDeclaration(pos, flags) { + parseExpected(106 /* ModuleKeyword */); + return token === 3 /* StringLiteral */ ? parseAmbientExternalModuleDeclaration(pos, flags) : parseInternalModuleTail(pos, flags); + } + function parseImportDeclaration(pos, flags) { + var node = createNode(174 /* ImportDeclaration */, pos); + node.flags = flags; + parseExpected(75 /* ImportKeyword */); + node.name = parseIdentifier(); + parseExpected(43 /* EqualsToken */); + var entityName = parseEntityName(false); + if (entityName.kind === 55 /* Identifier */ && entityName.text === "require" && parseOptional(7 /* OpenParenToken */)) { + node.externalModuleName = parseStringLiteral(); + parseExpected(8 /* CloseParenToken */); + } + else { + node.entityName = entityName; + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignmentTail(pos) { + var node = createNode(175 /* ExportAssignment */, pos); + node.exportName = parseIdentifier(); + parseSemicolon(); + return finishNode(node); + } + function isDeclaration() { + switch (token) { + case 88 /* VarKeyword */: + case 73 /* FunctionKeyword */: + return true; + case 59 /* ClassKeyword */: + case 93 /* InterfaceKeyword */: + case 67 /* EnumKeyword */: + case 75 /* ImportKeyword */: + return lookAhead(function () { return nextToken() >= 55 /* Identifier */; }); + case 106 /* ModuleKeyword */: + return lookAhead(function () { return nextToken() >= 55 /* Identifier */ || token === 3 /* StringLiteral */; }); + case 68 /* ExportKeyword */: + return lookAhead(function () { return nextToken() === 43 /* EqualsToken */ || isDeclaration(); }); + case 104 /* DeclareKeyword */: + case 98 /* PublicKeyword */: + case 96 /* PrivateKeyword */: + case 99 /* StaticKeyword */: + return lookAhead(function () { + nextToken(); + return isDeclaration(); + }); + } + } + function parseDeclaration(modifierContext) { + var pos = getNodePos(); + var errorCountBeforeModifiers = file.syntacticErrors.length; + var flags = parseAndCheckModifiers(modifierContext); + if (token === 68 /* ExportKeyword */) { + var modifiersEnd = scanner.getStartPos(); + nextToken(); + if (parseOptional(43 /* EqualsToken */)) { + var exportAssignmentTail = parseExportAssignmentTail(pos); + if (flags !== 0 && errorCountBeforeModifiers === file.syntacticErrors.length) { + var modifiersStart = ts.skipTrivia(sourceText, pos); + grammarErrorAtPos(modifiersStart, modifiersEnd - modifiersStart, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + return exportAssignmentTail; + } + } + var saveInAmbientContext = inAmbientContext; + if (flags & 2 /* Ambient */) { + inAmbientContext = true; + } + var result; + switch (token) { + case 88 /* VarKeyword */: + result = parseVariableStatement(pos, flags); + break; + case 73 /* FunctionKeyword */: + result = parseFunctionDeclaration(pos, flags); + break; + case 59 /* ClassKeyword */: + result = parseClassDeclaration(pos, flags); + break; + case 93 /* InterfaceKeyword */: + result = parseInterfaceDeclaration(pos, flags); + break; + case 67 /* EnumKeyword */: + result = parseAndCheckEnumDeclaration(pos, flags); + break; + case 106 /* ModuleKeyword */: + result = parseModuleDeclaration(pos, flags); + break; + case 75 /* ImportKeyword */: + result = parseImportDeclaration(pos, flags); + break; + default: + error(ts.Diagnostics.Declaration_expected); + } + inAmbientContext = saveInAmbientContext; + return result; + } + function isSourceElement(inErrorRecovery) { + return isDeclaration() || isStatement(inErrorRecovery); + } + function parseSourceElement() { + return parseSourceElementOrModuleElement(0 /* SourceElements */); + } + function parseModuleElement() { + return parseSourceElementOrModuleElement(1 /* ModuleElements */); + } + function parseSourceElementOrModuleElement(modifierContext) { + if (isDeclaration()) { + return parseDeclaration(modifierContext); + } + var statementStart = scanner.getTokenPos(); + var statementFirstTokenLength = scanner.getTextPos() - statementStart; + var errorCountBeforeStatement = file.syntacticErrors.length; + var statement = parseStatement(); + if (inAmbientContext && file.syntacticErrors.length === errorCountBeforeStatement) { + grammarErrorAtPos(statementStart, statementFirstTokenLength, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + return statement; + } + function processReferenceComments() { + var referencedFiles = []; + var amdDependencies = []; + commentRanges = []; + token = scanner.scan(); + for (var i = 0; i < commentRanges.length; i++) { + var range = commentRanges[i]; + var comment = sourceText.substring(range.pos, range.end); + var simpleReferenceRegEx = /^\/\/\/\s*/gim; + if (isNoDefaultLibRegEx.exec(comment)) { + file.hasNoDefaultLib = true; + } + else { + var fullReferenceRegEx = /^(\/\/\/\s*/; + var matchResult = fullReferenceRegEx.exec(comment); + if (!matchResult) { + var start = range.pos; + var length = range.end - start; + errorAtPos(start, length, ts.Diagnostics.Invalid_reference_comment); + } + else { + referencedFiles.push({ + pos: range.pos, + end: range.end, + filename: matchResult[3] + }); + } + } + } + else { + var amdDependencyRegEx = /^\/\/\/\s*= 0 ? filename : filename + extension; + } + function processRootFile(filename, isDefaultLib) { + processSourceFile(ts.normalizePath(addExtension(filename, ".ts")), isDefaultLib); + } + function processSourceFile(filename, isDefaultLib, refFile, refPos, refEnd) { + if (refEnd !== undefined && refPos !== undefined) { + var start = refPos; + var length = refEnd - refPos; + } + if (!ts.fileExtensionIs(filename, ".ts")) { + errors.push(ts.createFileDiagnostic(refFile, start, length, ts.Diagnostics.File_0_must_have_extension_ts_or_d_ts, filename)); + } + else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { + errors.push(ts.createFileDiagnostic(refFile, start, length, ts.Diagnostics.File_0_not_found, filename)); + } + } + function findSourceFile(filename, isDefaultLib, refFile, refStart, refLength) { + var canonicalName = host.getCanonicalFileName(filename); + var file = getSourceFile(filename); + if (file) { + if (host.useCaseSensitiveFileNames() && canonicalName !== file.filename) { + errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, file.filename)); + } + } + else { + file = host.getSourceFile(filename, options.target, function (hostErrorMessage) { + errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + }); + if (file) { + filesByName[host.getCanonicalFileName(filename)] = file; + seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + if (!options.noResolve) { + var basePath = ts.getDirectoryPath(filename); + processReferencedFiles(file, basePath); + processImportedModules(file, basePath); + } + if (isDefaultLib) { + files.unshift(file); + } + else { + files.push(file); + } + ts.forEach(file.syntacticErrors, function (e) { + errors.push(e); + }); + } + } + return file; + } + function processReferencedFiles(file, basePath) { + ts.forEach(file.referencedFiles, function (ref) { + processSourceFile(ts.normalizePath(ts.combinePaths(basePath, ref.filename)), false, file, ref.pos, ref.end); + }); + } + function processImportedModules(file, basePath) { + ts.forEach(file.statements, function (node) { + if (node.kind === 174 /* ImportDeclaration */ && node.externalModuleName) { + var nameLiteral = node.externalModuleName; + var moduleName = nameLiteral.text; + if (moduleName) { + var searchPath = basePath; + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); + if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) + break; + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) + break; + searchPath = parentPath; + } + } + } + else if (node.kind === 172 /* ModuleDeclaration */ && node.name.kind === 3 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || file.flags & 512 /* DeclarationFile */)) { + forEachChild(node.body, function (node) { + if (node.kind === 174 /* ImportDeclaration */ && node.externalModuleName) { + var nameLiteral = node.externalModuleName; + var moduleName = nameLiteral.text; + if (moduleName) { + var searchName = ts.normalizePath(ts.combinePaths(basePath, moduleName)); + var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); + if (!tsFile) { + findModuleSourceFile(searchName + ".d.ts", nameLiteral); + } + } + } + }); + } + }); + function findModuleSourceFile(filename, nameLiteral) { + return findSourceFile(filename, false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); + } + } + function verifyCompilerOptions() { + if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { + if (options.mapRoot) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + if (options.sourceRoot) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + return; + } + var firstExternalModule = ts.forEach(files, function (f) { return isExternalModule(f) ? f : undefined; }); + if (firstExternalModule && options.module === 0 /* None */) { + var externalModuleErrorSpan = getErrorSpanForNode(firstExternalModule.externalModuleIndicator); + var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); + var errorLength = externalModuleErrorSpan.end - errorStart; + errors.push(ts.createFileDiagnostic(firstExternalModule, errorStart, errorLength, ts.Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); + } + if (options.outDir || options.sourceRoot || (options.mapRoot && (!options.out || firstExternalModule !== undefined))) { + var commonPathComponents; + ts.forEach(files, function (sourceFile) { + if (!(sourceFile.flags & 512 /* DeclarationFile */) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { + var sourcePathCompoments = ts.getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); + sourcePathCompoments.pop(); + if (commonPathComponents) { + for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathCompoments.length); i++) { + if (commonPathComponents[i] !== sourcePathCompoments[i]) { + if (i === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + return; + } + commonPathComponents.length = i; + break; + } + } + if (sourcePathCompoments.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathCompoments.length; + } + } + else { + commonPathComponents = sourcePathCompoments; + } + } + }); + commonSourceDirectory = ts.getNormalizedPathFromPathCompoments(commonPathComponents); + if (commonSourceDirectory) { + commonSourceDirectory += ts.directorySeparator; + } + } + } + } + ts.createProgram = createProgram; +})(ts || (ts = {})); +var ts; +(function (ts) { + function isInstantiated(node) { + if (node.kind === 170 /* InterfaceDeclaration */) { + return false; + } + else if (node.kind === 174 /* ImportDeclaration */ && !(node.flags & 1 /* Export */)) { + return false; + } + else if (node.kind === 173 /* ModuleBlock */ && !ts.forEachChild(node, isInstantiated)) { + return false; + } + else if (node.kind === 172 /* ModuleDeclaration */ && !isInstantiated(node.body)) { + return false; + } + else { + return true; + } + } + ts.isInstantiated = isInstantiated; + function bindSourceFile(file) { + var parent; + var container; + var lastContainer; + var symbolCount = 0; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + file.locals = {}; + container = file; + bind(file); + file.symbolCount = symbolCount; + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolKind) { + symbol.flags |= symbolKind; + if (!symbol.declarations) + symbol.declarations = []; + symbol.declarations.push(node); + if (symbolKind & ts.SymbolFlags.HasExports && !symbol.exports) + symbol.exports = {}; + if (symbolKind & ts.SymbolFlags.HasMembers && !symbol.members) + symbol.members = {}; + node.symbol = symbol; + if (symbolKind & ts.SymbolFlags.Value && !symbol.valueDeclaration) + symbol.valueDeclaration = node; + } + function getDeclarationName(node) { + if (node.name) { + if (node.kind === 172 /* ModuleDeclaration */ && node.name.kind === 3 /* StringLiteral */) { + return '"' + node.name.text + '"'; + } + return node.name.text; + } + switch (node.kind) { + case 117 /* Constructor */: + return "__constructor"; + case 120 /* CallSignature */: + return "__call"; + case 121 /* ConstructSignature */: + return "__new"; + case 122 /* IndexSignature */: + return "__index"; + } + } + function getDisplayName(node) { + return node.name ? ts.identifierToString(node.name) : getDeclarationName(node); + } + function declareSymbol(symbols, parent, node, includes, excludes) { + var name = getDeclarationName(node); + if (name !== undefined) { + var symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + if (symbol.flags & excludes) { + if (node.name) { + node.name.parent = node; + } + file.semanticErrors.push(ts.createDiagnosticForNode(node.name ? node.name : node, ts.Diagnostics.Duplicate_identifier_0, getDisplayName(node))); + symbol = createSymbol(0, name); + } + } + else { + symbol = createSymbol(0, "__missing"); + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + if (node.kind === 169 /* ClassDeclaration */ && symbol.exports) { + var prototypeSymbol = createSymbol(2 /* Property */ | 67108864 /* Prototype */, "prototype"); + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.semanticErrors.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[prototypeSymbol.name] = prototypeSymbol; + prototypeSymbol.parent = symbol; + } + return symbol; + } + function isAmbientContext(node) { + while (node) { + if (node.flags & 2 /* Ambient */) + return true; + node = node.parent; + } + return false; + } + function declareModuleMember(node, symbolKind, symbolExcludes) { + var exportKind = 0; + if (symbolKind & ts.SymbolFlags.Value) { + exportKind |= 524288 /* ExportValue */; + } + if (symbolKind & ts.SymbolFlags.Type) { + exportKind |= 1048576 /* ExportType */; + } + if (symbolKind & ts.SymbolFlags.Namespace) { + exportKind |= 2097152 /* ExportNamespace */; + } + if (node.flags & 1 /* Export */ || (node.kind !== 174 /* ImportDeclaration */ && isAmbientContext(container))) { + if (exportKind) { + var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + node.localSymbol = local; + } + else { + declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + } + } + else { + declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + } + } + function bindChildren(node, symbolKind) { + if (symbolKind & ts.SymbolFlags.HasLocals) { + node.locals = {}; + } + var saveParent = parent; + var saveContainer = container; + parent = node; + if (symbolKind & ts.SymbolFlags.IsContainer) { + container = node; + if (lastContainer) + lastContainer.nextContainer = container; + lastContainer = container; + } + ts.forEachChild(node, bind); + container = saveContainer; + parent = saveParent; + } + function bindDeclaration(node, symbolKind, symbolExcludes) { + switch (container.kind) { + case 172 /* ModuleDeclaration */: + declareModuleMember(node, symbolKind, symbolExcludes); + break; + case 177 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolKind, symbolExcludes); + break; + } + case 120 /* CallSignature */: + case 121 /* ConstructSignature */: + case 122 /* IndexSignature */: + case 116 /* Method */: + case 117 /* Constructor */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + break; + case 169 /* ClassDeclaration */: + if (node.flags & 64 /* Static */) { + declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + break; + } + case 125 /* TypeLiteral */: + case 128 /* ObjectLiteral */: + case 170 /* InterfaceDeclaration */: + declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes); + break; + case 171 /* EnumDeclaration */: + declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + break; + } + bindChildren(node, symbolKind); + } + function bindConstructorDeclaration(node) { + bindDeclaration(node, 4096 /* Constructor */, 0); + ts.forEach(node.parameters, function (p) { + if (p.flags & (16 /* Public */ | 32 /* Private */)) { + bindDeclaration(p, 2 /* Property */, ts.SymbolFlags.PropertyExcludes); + } + }); + } + function bindModuleDeclaration(node) { + if (node.name.kind === 3 /* StringLiteral */) { + bindDeclaration(node, 128 /* ValueModule */, ts.SymbolFlags.ValueModuleExcludes); + } + else if (isInstantiated(node)) { + bindDeclaration(node, 128 /* ValueModule */, ts.SymbolFlags.ValueModuleExcludes); + } + else { + bindDeclaration(node, 256 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); + } + } + function bindAnonymousDeclaration(node, symbolKind, name) { + var symbol = createSymbol(symbolKind, name); + addDeclarationToSymbol(symbol, node, symbolKind); + bindChildren(node, symbolKind); + } + function bindCatchVariableDeclaration(node) { + var symbol = createSymbol(1 /* Variable */, node.variable.text || "__missing"); + addDeclarationToSymbol(symbol, node.variable, 1 /* Variable */); + var saveParent = parent; + parent = node; + ts.forEachChild(node, bind); + parent = saveParent; + } + function bind(node) { + node.parent = parent; + switch (node.kind) { + case 113 /* TypeParameter */: + bindDeclaration(node, 262144 /* TypeParameter */, ts.SymbolFlags.TypeParameterExcludes); + break; + case 114 /* Parameter */: + bindDeclaration(node, 1 /* Variable */, ts.SymbolFlags.ParameterExcludes); + break; + case 166 /* VariableDeclaration */: + bindDeclaration(node, 1 /* Variable */, ts.SymbolFlags.VariableExcludes); + break; + case 115 /* Property */: + case 129 /* PropertyAssignment */: + bindDeclaration(node, 2 /* Property */, ts.SymbolFlags.PropertyExcludes); + break; + case 176 /* EnumMember */: + bindDeclaration(node, 4 /* EnumMember */, ts.SymbolFlags.EnumMemberExcludes); + break; + case 120 /* CallSignature */: + bindDeclaration(node, 32768 /* CallSignature */, 0); + break; + case 116 /* Method */: + bindDeclaration(node, 2048 /* Method */, ts.SymbolFlags.MethodExcludes); + break; + case 121 /* ConstructSignature */: + bindDeclaration(node, 65536 /* ConstructSignature */, 0); + break; + case 122 /* IndexSignature */: + bindDeclaration(node, 131072 /* IndexSignature */, 0); + break; + case 167 /* FunctionDeclaration */: + bindDeclaration(node, 8 /* Function */, ts.SymbolFlags.FunctionExcludes); + break; + case 117 /* Constructor */: + bindConstructorDeclaration(node); + break; + case 118 /* GetAccessor */: + bindDeclaration(node, 8192 /* GetAccessor */, ts.SymbolFlags.GetAccessorExcludes); + break; + case 119 /* SetAccessor */: + bindDeclaration(node, 16384 /* SetAccessor */, ts.SymbolFlags.SetAccessorExcludes); + break; + case 125 /* TypeLiteral */: + bindAnonymousDeclaration(node, 512 /* TypeLiteral */, "__type"); + break; + case 128 /* ObjectLiteral */: + bindAnonymousDeclaration(node, 1024 /* ObjectLiteral */, "__object"); + break; + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + bindAnonymousDeclaration(node, 8 /* Function */, "__function"); + break; + case 163 /* CatchBlock */: + bindCatchVariableDeclaration(node); + break; + case 169 /* ClassDeclaration */: + bindDeclaration(node, 16 /* Class */, ts.SymbolFlags.ClassExcludes); + break; + case 170 /* InterfaceDeclaration */: + bindDeclaration(node, 32 /* Interface */, ts.SymbolFlags.InterfaceExcludes); + break; + case 171 /* EnumDeclaration */: + bindDeclaration(node, 64 /* Enum */, ts.SymbolFlags.EnumExcludes); + break; + case 172 /* ModuleDeclaration */: + bindModuleDeclaration(node); + break; + case 174 /* ImportDeclaration */: + bindDeclaration(node, 4194304 /* Import */, ts.SymbolFlags.ImportExcludes); + break; + case 177 /* SourceFile */: + if (ts.isExternalModule(node)) { + bindAnonymousDeclaration(node, 128 /* ValueModule */, '"' + ts.getModuleNameFromFilename(node.filename) + '"'); + break; + } + default: + var saveParent = parent; + parent = node; + ts.forEachChild(node, bind); + parent = saveParent; + } + } + } + ts.bindSourceFile = bindSourceFile; +})(ts || (ts = {})); +var ts; +(function (ts) { + var indentStrings = []; + function getIndentString(level) { + return indentStrings[level] || (indentStrings[level] = level === 0 ? "" : getIndentString(level - 1) + " "); + } + function emitFiles(resolver) { + var program = resolver.getProgram(); + var compilerHost = program.getCompilerHost(); + var compilerOptions = program.getCompilerOptions(); + var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; + var diagnostics = []; + var newLine = program.getCompilerHost().getNewLine(); + function getSourceFilePathInNewDir(newDirPath, sourceFile) { + var sourceFilePath = ts.getNormalizedPathFromPathCompoments(ts.getNormalizedPathComponents(sourceFile.filename, compilerHost.getCurrentDirectory())); + sourceFilePath = sourceFilePath.replace(program.getCommonSourceDirectory(), ""); + return ts.combinePaths(newDirPath, sourceFilePath); + } + function shouldEmitToOwnFile(sourceFile) { + if (!(sourceFile.flags & 512 /* DeclarationFile */)) { + if ((ts.isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { + return true; + } + } + } + function getOwnEmitOutputFilePath(sourceFile, extension) { + if (program.getCompilerOptions().outDir) { + var emitOutputFilePathWithoutExtension = ts.getModuleNameFromFilename(getSourceFilePathInNewDir(program.getCompilerOptions().outDir, sourceFile)); + } + else { + var emitOutputFilePathWithoutExtension = ts.getModuleNameFromFilename(sourceFile.filename); + } + return emitOutputFilePathWithoutExtension + extension; + } + function isExternalModuleOrDeclarationFile(sourceFile) { + return ts.isExternalModule(sourceFile) || (sourceFile.flags & 512 /* DeclarationFile */) !== 0; + } + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 117 /* Constructor */ && member.body) { + return member; + } + }); + } + function getAllAccessorDeclarations(node, accessor) { + var firstAccessor; + var getAccessor; + var setAccessor; + ts.forEach(node.members, function (member) { + if ((member.kind === 118 /* GetAccessor */ || member.kind === 119 /* SetAccessor */) && member.name.text === accessor.name.text && (member.flags & 64 /* Static */) === (accessor.flags & 64 /* Static */)) { + if (!firstAccessor) { + firstAccessor = member; + } + if (member.kind === 118 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 119 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + }); + return { + firstAccessor: firstAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + function createTextWriter() { + var output = ""; + var indent = 0; + var lineStart = true; + var lineCount = 0; + var linePos = 0; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + var pos = 0; + while (pos < s.length) { + switch (s.charCodeAt(pos++)) { + case 13 /* carriageReturn */: + if (pos < s.length && s.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + case 10 /* lineFeed */: + lineCount++; + linePos = output.length - s.length + pos; + break; + } + } + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + return { + write: write, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { return indent++; }, + decreaseIndent: function () { return indent--; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount + 1; }, + getColumn: function () { return lineStart ? indent * 4 + 1 : output.length - linePos + 1; }, + getText: function () { return output; } + }; + } + var currentSourceFile; + function getSourceTextOfLocalNode(node) { + var text = currentSourceFile.text; + return text.substring(ts.skipTrivia(text, node.pos), node.end); + } + function writeFile(filename, data) { + compilerHost.writeFile(filename, data, function (hostErrorMessage) { + diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage)); + }); + } + function emitJavaScript(jsFilePath, root) { + var writer = createTextWriter(); + var write = writer.write; + var writeLine = writer.writeLine; + var increaseIndent = writer.increaseIndent; + var decreaseIndent = writer.decreaseIndent; + var extendsEmitted = false; + var writeEmittedFiles = writeJavaScriptFile; + var emit = emitNode; + var emitStart = function (node) { + }; + var emitEnd = function (node) { + }; + var emitToken = emitTokenText; + var emitNewSourceFileStart = function (node) { + }; + var scopeEmitStart = function (scopeDeclaration, scopeName) { + }; + var scopeEmitEnd = function () { + }; + var sourceMapData; + function initializeEmitterWithSourceMaps() { + var sourceMapDir; + var sourceMapSourceIndex = -1; + var sourceMapNameIndexMap = {}; + var sourceMapNameIndices = []; + function getSourceMapNameIndex() { + return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + } + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + var lastEncodedNameIndex = 0; + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + function base64VLQFormatEncode(inValue) { + function base64FormatEncode(inValue) { + if (inValue < 64) { + return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } + } + function recordSourceMapSpan(pos) { + var sourceLinePos = currentSourceFile.getLineAndCharacterFromPosition(pos); + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine != emittedLine || lastRecordedSourceMapSpan.emittedColumn != emittedColumn || lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + nameIndex: getSourceMapNameIndex(), + sourceIndex: sourceMapSourceIndex + }; + } + else { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + } + } + function recordEmitNodeStartSpan(node) { + recordSourceMapSpan(ts.getTokenPosOfNode(node)); + } + function recordEmitNodeEndSpan(node) { + recordSourceMapSpan(node.end); + } + function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + recordSourceMapSpan(tokenStartPos); + var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + recordSourceMapSpan(tokenEndPos); + return tokenEndPos; + } + function recordNewSourceFileStart(node) { + var sourcesDirectoryPath = compilerOptions.sourceRoot ? program.getCommonSourceDirectory() : sourceMapDir; + sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.filename, compilerHost.getCurrentDirectory(), true)); + sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; + sourceMapData.inputSourceFileNames.push(node.filename); + } + function recordScopeNameOfNode(node, scopeName) { + function recordScopeNameIndex(scopeNameIndex) { + sourceMapNameIndices.push(scopeNameIndex); + } + function recordScopeNameStart(scopeName) { + var scopeNameIndex = -1; + if (scopeName) { + var parentIndex = getSourceMapNameIndex(); + if (parentIndex !== -1) { + scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; + } + scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); + if (scopeNameIndex === undefined) { + scopeNameIndex = sourceMapData.sourceMapNames.length; + sourceMapData.sourceMapNames.push(scopeName); + sourceMapNameIndexMap[scopeName] = scopeNameIndex; + } + } + recordScopeNameIndex(scopeNameIndex); + } + if (scopeName) { + recordScopeNameStart(scopeName); + } + else if (node.kind === 167 /* FunctionDeclaration */ || node.kind === 136 /* FunctionExpression */ || node.kind === 116 /* Method */ || node.kind === 118 /* GetAccessor */ || node.kind === 119 /* SetAccessor */ || node.kind === 172 /* ModuleDeclaration */ || node.kind === 169 /* ClassDeclaration */ || node.kind === 171 /* EnumDeclaration */) { + if (node.name) { + scopeName = node.name.text; + } + recordScopeNameStart(scopeName); + } + else { + recordScopeNameIndex(getSourceMapNameIndex()); + } + } + function recordScopeNameEnd() { + sourceMapNameIndices.pop(); + } + ; + function writeJavaScriptAndSourceMapFile(emitOutput) { + encodeLastRecordedSourceMapSpan(); + writeFile(sourceMapData.sourceMapFilePath, JSON.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings + })); + sourceMapDataList.push(sourceMapData); + writeJavaScriptFile(emitOutput + "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL); + } + var sourceMapJsFile = ts.getBaseFilename(ts.normalizeSlashes(jsFilePath)); + sourceMapData = { + sourceMapFilePath: jsFilePath + ".map", + jsSourceMappingURL: sourceMapJsFile + ".map", + sourceMapFile: sourceMapJsFile, + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (root) { + sourceMapDir = ts.getDirectoryPath(getSourceFilePathInNewDir(sourceMapDir, root)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(program.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), compilerHost.getCurrentDirectory(), true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); + } + function emitNodeWithMap(node) { + if (node) { + if (node.kind != 177 /* SourceFile */) { + recordEmitNodeStartSpan(node); + emitNode(node); + recordEmitNodeEndSpan(node); + } + else { + recordNewSourceFileStart(node); + emitNode(node); + } + } + } + writeEmittedFiles = writeJavaScriptAndSourceMapFile; + emit = emitNodeWithMap; + emitStart = recordEmitNodeStartSpan; + emitEnd = recordEmitNodeEndSpan; + emitToken = writeTextWithSpanRecord; + emitNewSourceFileStart = recordNewSourceFileStart; + scopeEmitStart = recordScopeNameOfNode; + scopeEmitEnd = recordScopeNameEnd; + } + function writeJavaScriptFile(emitOutput) { + writeFile(jsFilePath, emitOutput); + } + function emitTokenText(tokenKind, startPos, emitFn) { + var tokenString = ts.tokenToString(tokenKind); + if (emitFn) { + emitFn(); + } + else { + write(tokenString); + } + return startPos + tokenString.length; + } + function emitOptional(prefix, node) { + if (node) { + write(prefix); + emit(node); + } + } + function emitCommaList(nodes, count) { + if (!(count >= 0)) + count = nodes.length; + if (nodes) { + for (var i = 0; i < count; i++) { + if (i) + write(", "); + emit(nodes[i]); + } + } + } + function emitMultiLineList(nodes) { + if (nodes) { + for (var i = 0; i < nodes.length; i++) { + if (i) + write(","); + writeLine(); + emit(nodes[i]); + } + } + } + function emitLines(nodes) { + emitLinesStartingAt(nodes, 0); + } + function emitLinesStartingAt(nodes, startIndex) { + for (var i = startIndex; i < nodes.length; i++) { + writeLine(); + emit(nodes[i]); + } + } + function emitLiteral(node) { + var text = getSourceTextOfLocalNode(node); + if (node.kind === 3 /* StringLiteral */ && compilerOptions.sourceMap) { + writer.writeLiteral(text); + } + else { + write(text); + } + } + function emitQuotedIdentifier(node) { + if (node.kind === 3 /* StringLiteral */) { + emitLiteral(node); + } + else { + write("\""); + if (node.kind === 2 /* NumericLiteral */) { + write(node.text); + } + else { + write(getSourceTextOfLocalNode(node)); + } + write("\""); + } + } + function isNonExpressionIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 114 /* Parameter */: + case 166 /* VariableDeclaration */: + case 115 /* Property */: + case 129 /* PropertyAssignment */: + case 176 /* EnumMember */: + case 116 /* Method */: + case 167 /* FunctionDeclaration */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 136 /* FunctionExpression */: + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + case 171 /* EnumDeclaration */: + case 172 /* ModuleDeclaration */: + case 174 /* ImportDeclaration */: + return parent.name === node; + case 153 /* BreakStatement */: + case 152 /* ContinueStatement */: + case 175 /* ExportAssignment */: + return false; + case 159 /* LabelledStatement */: + return node.parent.label === node; + case 163 /* CatchBlock */: + return node.parent.variable === node; + } + } + function emitIdentifier(node) { + if (!isNonExpressionIdentifier(node)) { + var prefix = resolver.getExpressionNamePrefix(node); + if (prefix) { + write(prefix); + write("."); + } + } + write(getSourceTextOfLocalNode(node)); + } + function emitThis(node) { + if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { + write("_this"); + } + else { + write("this"); + } + } + function emitSuper(node) { + var flags = resolver.getNodeCheckFlags(node); + if (flags & 16 /* SuperInstance */) { + write("_super.prototype"); + } + else if (flags & 32 /* SuperStatic */) { + write("_super"); + } + else { + write("super"); + } + } + function emitArrayLiteral(node) { + if (node.flags & 128 /* MultiLine */) { + write("["); + increaseIndent(); + emitMultiLineList(node.elements); + decreaseIndent(); + writeLine(); + write("]"); + } + else { + write("["); + emitCommaList(node.elements); + write("]"); + } + } + function emitObjectLiteral(node) { + if (!node.properties.length) { + write("{}"); + } + else if (node.flags & 128 /* MultiLine */) { + write("{"); + increaseIndent(); + emitMultiLineList(node.properties); + decreaseIndent(); + writeLine(); + write("}"); + } + else { + write("{ "); + emitCommaList(node.properties); + write(" }"); + } + } + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + emit(node.initializer); + } + function emitPropertyAccess(node) { + var text = resolver.getPropertyAccessSubstitution(node); + if (text) { + write(text); + return; + } + emit(node.left); + write("."); + emit(node.right); + } + function emitIndexedAccess(node) { + emit(node.object); + write("["); + emit(node.index); + write("]"); + } + function emitCallExpression(node) { + var superCall = false; + if (node.func.kind === 81 /* SuperKeyword */) { + write("_super"); + superCall = true; + } + else { + emit(node.func); + superCall = node.func.kind === 130 /* PropertyAccess */ && node.func.left.kind === 81 /* SuperKeyword */; + } + if (superCall) { + write(".call("); + emitThis(node.func); + if (node.arguments.length) { + write(", "); + emitCommaList(node.arguments); + } + write(")"); + } + else { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitNewExpression(node) { + write("new "); + emit(node.func); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitParenExpression(node) { + if (node.expression.kind === 134 /* TypeAssertion */) { + var operand = node.expression.operand; + while (operand.kind == 134 /* TypeAssertion */) { + operand = operand.operand; + } + if (operand.kind !== 138 /* PrefixOperator */ && operand.kind !== 139 /* PostfixOperator */ && operand.kind !== 133 /* NewExpression */ && !(operand.kind === 132 /* CallExpression */ && node.parent.kind === 133 /* NewExpression */) && !(operand.kind === 136 /* FunctionExpression */ && node.parent.kind === 132 /* CallExpression */)) { + emit(operand); + return; + } + } + write("("); + emit(node.expression); + write(")"); + } + function emitUnaryExpression(node) { + if (node.kind === 138 /* PrefixOperator */) { + write(ts.tokenToString(node.operator)); + } + if (node.operator >= 55 /* Identifier */) { + write(" "); + } + else if (node.kind === 138 /* PrefixOperator */ && node.operand.kind === 138 /* PrefixOperator */) { + var operand = node.operand; + if (node.operator === 24 /* PlusToken */ && (operand.operator === 24 /* PlusToken */ || operand.operator === 29 /* PlusPlusToken */)) { + write(" "); + } + else if (node.operator === 25 /* MinusToken */ && (operand.operator === 25 /* MinusToken */ || operand.operator === 30 /* MinusMinusToken */)) { + write(" "); + } + } + emit(node.operand); + if (node.kind === 139 /* PostfixOperator */) { + write(ts.tokenToString(node.operator)); + } + } + function emitBinaryExpression(node) { + emit(node.left); + if (node.operator !== 14 /* CommaToken */) + write(" "); + write(ts.tokenToString(node.operator)); + write(" "); + emit(node.right); + } + function emitConditionalExpression(node) { + emit(node.condition); + write(" ? "); + emit(node.whenTrue); + write(" : "); + emit(node.whenFalse); + } + function emitBlock(node) { + emitToken(5 /* OpenBraceToken */, node.pos); + increaseIndent(); + scopeEmitStart(node.parent); + if (node.kind === 173 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 172 /* ModuleDeclaration */); + emitCaptureThisForNodeIfNecessary(node.parent); + } + emitLines(node.statements); + decreaseIndent(); + writeLine(); + emitToken(6 /* CloseBraceToken */, node.statements.end); + scopeEmitEnd(); + } + function emitEmbeddedStatement(node) { + if (node.kind === 143 /* Block */) { + write(" "); + emit(node); + } + else { + increaseIndent(); + writeLine(); + emit(node); + decreaseIndent(); + } + } + function emitExpressionStatement(node) { + var isArrowExpression = node.expression.kind === 137 /* ArrowFunction */; + if (isArrowExpression) + write("("); + emit(node.expression); + if (isArrowExpression) + write(")"); + write(";"); + } + function emitIfStatement(node) { + var endPos = emitToken(74 /* IfKeyword */, node.pos); + write(" "); + endPos = emitToken(7 /* OpenParenToken */, endPos); + emit(node.expression); + emitToken(8 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + emitToken(66 /* ElseKeyword */, node.thenStatement.end); + if (node.elseStatement.kind === 147 /* IfStatement */) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (node.statement.kind === 143 /* Block */) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emit(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var endPos = emitToken(72 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(7 /* OpenParenToken */, endPos); + if (node.declarations) { + emitToken(88 /* VarKeyword */, endPos); + write(" "); + emitCommaList(node.declarations); + } + if (node.initializer) { + emit(node.initializer); + } + write(";"); + emitOptional(" ", node.condition); + write(";"); + emitOptional(" ", node.iterator); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var endPos = emitToken(72 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(7 /* OpenParenToken */, endPos); + if (node.declaration) { + emitToken(88 /* VarKeyword */, endPos); + write(" "); + emit(node.declaration); + } + else { + emit(node.variable); + } + write(" in "); + emit(node.expression); + emitToken(8 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitBreakOrContinueStatement(node) { + emitToken(node.kind === 153 /* BreakStatement */ ? 56 /* BreakKeyword */ : 61 /* ContinueKeyword */, node.pos); + emitOptional(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + emitToken(80 /* ReturnKeyword */, node.pos); + emitOptional(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var endPos = emitToken(82 /* SwitchKeyword */, node.pos); + write(" "); + emitToken(7 /* OpenParenToken */, endPos); + emit(node.expression); + endPos = emitToken(8 /* CloseParenToken */, node.expression.end); + write(" "); + emitToken(5 /* OpenBraceToken */, endPos); + increaseIndent(); + emitLines(node.clauses); + decreaseIndent(); + writeLine(); + emitToken(6 /* CloseBraceToken */, node.clauses.end); + } + function emitCaseOrDefaultClause(node) { + if (node.kind === 157 /* CaseClause */) { + write("case "); + emit(node.expression); + write(":"); + } + else { + write("default:"); + } + increaseIndent(); + emitLines(node.statements); + decreaseIndent(); + } + function emitThrowStatement(node) { + write("throw "); + emit(node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchBlock); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitCatchBlock(node) { + writeLine(); + var endPos = emitToken(58 /* CatchKeyword */, node.pos); + write(" "); + emitToken(7 /* OpenParenToken */, endPos); + emit(node.variable); + emitToken(8 /* CloseParenToken */, node.variable.end); + write(" "); + emitBlock(node); + } + function emitDebuggerStatement(node) { + emitToken(62 /* DebuggerKeyword */, node.pos); + write(";"); + } + function emitLabelledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function getContainingModule(node) { + do { + node = node.parent; + } while (node && node.kind !== 172 /* ModuleDeclaration */); + return node; + } + function emitModuleMemberName(node) { + emitStart(node.name); + if (node.flags & 1 /* Export */) { + var container = getContainingModule(node); + write(container ? resolver.getLocalNameOfContainer(container) : "exports"); + write("."); + } + emitNode(node.name); + emitEnd(node.name); + } + function emitVariableDeclaration(node) { + emitModuleMemberName(node); + emitOptional(" = ", node.initializer); + } + function emitVariableStatement(node) { + if (!(node.flags & 1 /* Export */)) + write("var "); + emitCommaList(node.declarations); + write(";"); + } + function emitParameter(node) { + emit(node.name); + } + function emitDefaultValueAssignments(node) { + ts.forEach(node.parameters, function (param) { + if (param.initializer) { + writeLine(); + emitStart(param); + write("if ("); + emitNode(param.name); + write(" === void 0)"); + emitEnd(param); + write(" { "); + emitStart(param); + emitNode(param.name); + write(" = "); + emitNode(param.initializer); + emitEnd(param); + write("; }"); + } + }); + } + function emitRestParameter(node) { + if (ts.hasRestParameters(node)) { + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; + writeLine(); + emitStart(restParam); + write("var "); + emitNode(restParam.name); + write(" = [];"); + emitEnd(restParam); + writeLine(); + write("for ("); + emitStart(restParam); + write("var _i = " + restIndex + ";"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write("_i < arguments.length;"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write("_i++"); + emitEnd(restParam); + write(") {"); + increaseIndent(); + writeLine(); + emitStart(restParam); + emitNode(restParam.name); + write("[_i - " + restIndex + "] = arguments[_i];"); + emitEnd(restParam); + decreaseIndent(); + writeLine(); + write("}"); + } + } + function emitAccessor(node) { + write(node.kind === 118 /* GetAccessor */ ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node); + } + function emitFunctionDeclaration(node) { + if (!node.body) + return; + write("function "); + if (node.kind === 167 /* FunctionDeclaration */ || (node.kind === 136 /* FunctionExpression */ && node.name)) { + emit(node.name); + } + emitSignatureAndBody(node); + } + function emitCaptureThisForNodeIfNecessary(node) { + if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { + writeLine(); + emitStart(node); + write("var _this = this;"); + emitEnd(node); + } + } + function emitSignatureParameters(node) { + write("("); + if (node) { + emitCommaList(node.parameters, node.parameters.length - (ts.hasRestParameters(node) ? 1 : 0)); + } + write(")"); + } + function emitSignatureAndBody(node) { + emitSignatureParameters(node); + write(" {"); + scopeEmitStart(node); + increaseIndent(); + var startIndex = 0; + if (node.body.kind === 168 /* FunctionBlock */) { + startIndex = emitDirectivePrologues(node.body.statements, true); + } + var outPos = writer.getTextPos(); + emitCaptureThisForNodeIfNecessary(node); + emitDefaultValueAssignments(node); + emitRestParameter(node); + if (node.body.kind !== 168 /* FunctionBlock */ && outPos === writer.getTextPos()) { + decreaseIndent(); + write(" "); + emitStart(node.body); + write("return "); + emitNode(node.body); + emitEnd(node.body); + write("; "); + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + else { + if (node.body.kind === 168 /* FunctionBlock */) { + emitLinesStartingAt(node.body.statements, startIndex); + } + else { + writeLine(); + write("return "); + emit(node.body); + write(";"); + } + decreaseIndent(); + writeLine(); + if (node.body.kind === 168 /* FunctionBlock */) { + emitToken(6 /* CloseBraceToken */, node.body.statements.end); + } + else { + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + } + scopeEmitEnd(); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + emitEnd(node); + write(";"); + } + } + function findInitialSuperCall(ctor) { + if (ctor.body) { + var statement = ctor.body.statements[0]; + if (statement && statement.kind === 146 /* ExpressionStatement */) { + var expr = statement.expression; + if (expr && expr.kind === 132 /* CallExpression */) { + var func = expr.func; + if (func && func.kind === 81 /* SuperKeyword */) { + return statement; + } + } + } + } + } + function emitParameterPropertyAssignments(node) { + ts.forEach(node.parameters, function (param) { + if (param.flags & (16 /* Public */ | 32 /* Private */)) { + writeLine(); + emitStart(param); + emitStart(param.name); + write("this."); + emitNode(param.name); + emitEnd(param.name); + write(" = "); + emit(param.name); + write(";"); + emitEnd(param); + } + }); + } + function emitMemberAccess(memberName) { + if (memberName.kind === 3 /* StringLiteral */ || memberName.kind === 2 /* NumericLiteral */) { + write("["); + emitNode(memberName); + write("]"); + } + else { + write("."); + emitNode(memberName); + } + } + function emitMemberAssignments(node, staticFlag) { + ts.forEach(node.members, function (member) { + if (member.kind === 115 /* Property */ && (member.flags & 64 /* Static */) === staticFlag && member.initializer) { + writeLine(); + emitStart(member); + emitStart(member.name); + if (staticFlag) { + emitNode(node.name); + } + else { + write("this"); + } + emitMemberAccess(member.name); + emitEnd(member.name); + write(" = "); + emit(member.initializer); + write(";"); + emitEnd(member); + } + }); + } + function emitMemberFunctions(node) { + ts.forEach(node.members, function (member) { + if (member.kind === 116 /* Method */) { + if (!member.body) + return; + writeLine(); + emitStart(member); + emitStart(member.name); + emitNode(node.name); + if (!(member.flags & 64 /* Static */)) { + write(".prototype"); + } + emitMemberAccess(member.name); + emitEnd(member.name); + write(" = "); + emitStart(member); + emitFunctionDeclaration(member); + emitEnd(member); + emitEnd(member); + write(";"); + } + else if (member.kind === 118 /* GetAccessor */ || member.kind === 119 /* SetAccessor */) { + var accessors = getAllAccessorDeclarations(node, member); + if (member === accessors.firstAccessor) { + writeLine(); + emitStart(member); + write("Object.defineProperty("); + emitStart(member.name); + emitNode(node.name); + if (!(member.flags & 64 /* Static */)) { + write(".prototype"); + } + write(", "); + emitQuotedIdentifier(member.name); + emitEnd(member.name); + write(", {"); + increaseIndent(); + if (accessors.getAccessor) { + writeLine(); + write("get: "); + emitStart(accessors.getAccessor); + write("function "); + emitSignatureAndBody(accessors.getAccessor); + emitEnd(accessors.getAccessor); + write(","); + } + if (accessors.setAccessor) { + writeLine(); + write("set: "); + emitStart(accessors.setAccessor); + write("function "); + emitSignatureAndBody(accessors.setAccessor); + emitEnd(accessors.setAccessor); + write(","); + } + writeLine(); + write("enumerable: true,"); + writeLine(); + write("configurable: true"); + decreaseIndent(); + writeLine(); + write("});"); + emitEnd(member); + } + } + }); + } + function emitClassDeclaration(node) { + var ctor = getFirstConstructorWithBody(node); + write("var "); + emit(node.name); + write(" = (function ("); + if (node.baseType) + write("_super"); + write(") {"); + increaseIndent(); + scopeEmitStart(node); + if (node.baseType) { + writeLine(); + emitStart(node.baseType); + write("__extends("); + emit(node.name); + write(", _super);"); + emitEnd(node.baseType); + } + writeLine(); + emitStart(ctor || node); + write("function "); + emit(node.name); + emitSignatureParameters(ctor); + write(" {"); + scopeEmitStart(node, "constructor"); + increaseIndent(); + emitCaptureThisForNodeIfNecessary(node); + if (ctor) { + emitDefaultValueAssignments(ctor); + emitRestParameter(ctor); + if (node.baseType) { + var superCall = findInitialSuperCall(ctor); + if (superCall) { + writeLine(); + emit(superCall); + } + } + emitParameterPropertyAssignments(ctor); + } + else { + if (node.baseType) { + writeLine(); + emitStart(node.baseType); + write("_super.apply(this, arguments);"); + emitEnd(node.baseType); + } + } + emitMemberAssignments(node, 0); + if (ctor) { + var statements = ctor.body.statements; + if (superCall) + statements = statements.slice(1); + emitLines(statements); + } + decreaseIndent(); + writeLine(); + emitToken(6 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); + scopeEmitEnd(); + emitEnd(ctor || node); + emitMemberFunctions(node); + emitMemberAssignments(node, 64 /* Static */); + writeLine(); + function emitClassReturnStatement() { + write("return "); + emitNode(node.name); + } + emitToken(6 /* CloseBraceToken */, node.members.end, emitClassReturnStatement); + write(";"); + decreaseIndent(); + writeLine(); + emitToken(6 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + emitStart(node); + write(")("); + if (node.baseType) { + emit(node.baseType.typeName); + } + write(");"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + emitEnd(node); + write(";"); + } + } + function emitEnumDeclaration(node) { + if (!(node.flags & 1 /* Export */)) { + emitStart(node); + write("var "); + emit(node.name); + emitEnd(node); + write(";"); + } + writeLine(); + emitStart(node); + write("(function ("); + emitStart(node.name); + write(resolver.getLocalNameOfContainer(node)); + emitEnd(node.name); + write(") {"); + increaseIndent(); + scopeEmitStart(node); + ts.forEach(node.members, function (member) { + writeLine(); + emitStart(member); + write(resolver.getLocalNameOfContainer(node)); + write("["); + write(resolver.getLocalNameOfContainer(node)); + write("["); + emitQuotedIdentifier(member.name); + write("] = "); + if (member.initializer) { + emit(member.initializer); + } + else { + write(resolver.getEnumMemberValue(member).toString()); + } + write("] = "); + emitQuotedIdentifier(member.name); + emitEnd(member); + write(";"); + }); + decreaseIndent(); + writeLine(); + emitToken(6 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + write(")("); + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + write("var "); + emit(node.name); + write(" = "); + emitModuleMemberName(node); + emitEnd(node); + write(";"); + } + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 172 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function emitModuleDeclaration(node) { + if (!ts.isInstantiated(node)) + return; + if (!(node.flags & 1 /* Export */)) { + emitStart(node); + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); + } + emitStart(node); + write("(function ("); + emitStart(node.name); + write(resolver.getLocalNameOfContainer(node)); + emitEnd(node.name); + write(") "); + if (node.body.kind === 173 /* ModuleBlock */) { + emit(node.body); + } + else { + write("{"); + increaseIndent(); + scopeEmitStart(node); + emitCaptureThisForNodeIfNecessary(node); + writeLine(); + emit(node.body); + decreaseIndent(); + writeLine(); + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + emitToken(6 /* CloseBraceToken */, moduleBlock.statements.end); + scopeEmitEnd(); + } + write(")("); + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + write("var "); + emit(node.name); + write(" = "); + emitModuleMemberName(node); + emitEnd(node); + write(";"); + } + } + function emitImportDeclaration(node) { + var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); + if (!emitImportDeclaration) { + emitImportDeclaration = !ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportedViaEntityName(node); + } + if (emitImportDeclaration) { + if (node.externalModuleName && node.parent.kind === 177 /* SourceFile */ && compilerOptions.module === 2 /* AMD */) { + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + write(";"); + emitEnd(node); + } + } + else { + writeLine(); + emitStart(node); + if (!(node.flags & 1 /* Export */)) + write("var "); + emitModuleMemberName(node); + write(" = "); + if (node.entityName) { + emit(node.entityName); + } + else { + write("require("); + emitStart(node.externalModuleName); + emitLiteral(node.externalModuleName); + emitEnd(node.externalModuleName); + emitToken(8 /* CloseParenToken */, node.externalModuleName.end); + } + write(";"); + emitEnd(node); + } + } + } + function getExternalImportDeclarations(node) { + var result = []; + ts.forEach(node.statements, function (stat) { + if (stat.kind === 174 /* ImportDeclaration */ && stat.externalModuleName && resolver.isReferencedImportDeclaration(stat)) { + result.push(stat); + } + }); + return result; + } + function getFirstExportAssignment(sourceFile) { + return ts.forEach(sourceFile.statements, function (node) { + if (node.kind === 175 /* ExportAssignment */) { + return node; + } + }); + } + function emitAMDModule(node, startIndex) { + var imports = getExternalImportDeclarations(node); + writeLine(); + write("define([\"require\", \"exports\""); + ts.forEach(imports, function (imp) { + write(", "); + emitLiteral(imp.externalModuleName); + }); + ts.forEach(node.amdDependencies, function (amdDependency) { + var text = "\"" + amdDependency + "\""; + write(", "); + write(text); + }); + write("], function (require, exports"); + ts.forEach(imports, function (imp) { + write(", "); + emit(imp.name); + }); + write(") {"); + increaseIndent(); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + var exportName = resolver.getExportAssignmentName(node); + if (exportName) { + writeLine(); + var exportAssignement = getFirstExportAssignment(node); + emitStart(exportAssignement); + write("return "); + emitStart(exportAssignement.exportName); + write(exportName); + emitEnd(exportAssignement.exportName); + write(";"); + emitEnd(exportAssignement); + } + decreaseIndent(); + writeLine(); + write("});"); + } + function emitCommonJSModule(node, startIndex) { + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + var exportName = resolver.getExportAssignmentName(node); + if (exportName) { + writeLine(); + var exportAssignement = getFirstExportAssignment(node); + emitStart(exportAssignement); + write("module.exports = "); + emitStart(exportAssignement.exportName); + write(exportName); + emitEnd(exportAssignement.exportName); + write(";"); + emitEnd(exportAssignement); + } + } + function emitDirectivePrologues(statements, startWithNewLine) { + for (var i = 0; i < statements.length; ++i) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + return i; + } + } + return statements.length; + } + function emitSourceFile(node) { + currentSourceFile = node; + var startIndex = emitDirectivePrologues(node.statements, false); + if (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */) { + writeLine(); + write("var __extends = this.__extends || function (d, b) {"); + increaseIndent(); + writeLine(); + write("for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + writeLine(); + write("function __() { this.constructor = d; }"); + writeLine(); + write("__.prototype = b.prototype;"); + writeLine(); + write("d.prototype = new __();"); + decreaseIndent(); + writeLine(); + write("};"); + extendsEmitted = true; + } + if (ts.isExternalModule(node)) { + if (compilerOptions.module === 2 /* AMD */) { + emitAMDModule(node, startIndex); + } + else { + emitCommonJSModule(node, startIndex); + } + } + else { + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + } + } + function emitNode(node) { + if (!node || node.flags & 2 /* Ambient */) + return; + switch (node.kind) { + case 55 /* Identifier */: + return emitIdentifier(node); + case 114 /* Parameter */: + return emitParameter(node); + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + return emitAccessor(node); + case 83 /* ThisKeyword */: + return emitThis(node); + case 81 /* SuperKeyword */: + return emitSuper(node); + case 79 /* NullKeyword */: + return write("null"); + case 85 /* TrueKeyword */: + return write("true"); + case 70 /* FalseKeyword */: + return write("false"); + case 2 /* NumericLiteral */: + case 3 /* StringLiteral */: + case 4 /* RegularExpressionLiteral */: + return emitLiteral(node); + case 112 /* QualifiedName */: + return emitPropertyAccess(node); + case 127 /* ArrayLiteral */: + return emitArrayLiteral(node); + case 128 /* ObjectLiteral */: + return emitObjectLiteral(node); + case 129 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 130 /* PropertyAccess */: + return emitPropertyAccess(node); + case 131 /* IndexedAccess */: + return emitIndexedAccess(node); + case 132 /* CallExpression */: + return emitCallExpression(node); + case 133 /* NewExpression */: + return emitNewExpression(node); + case 134 /* TypeAssertion */: + return emit(node.operand); + case 135 /* ParenExpression */: + return emitParenExpression(node); + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + return emitFunctionDeclaration(node); + case 138 /* PrefixOperator */: + case 139 /* PostfixOperator */: + return emitUnaryExpression(node); + case 140 /* BinaryExpression */: + return emitBinaryExpression(node); + case 141 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 142 /* OmittedExpression */: + return; + case 143 /* Block */: + case 162 /* TryBlock */: + case 164 /* FinallyBlock */: + case 168 /* FunctionBlock */: + case 173 /* ModuleBlock */: + return emitBlock(node); + case 144 /* VariableStatement */: + return emitVariableStatement(node); + case 145 /* EmptyStatement */: + return write(";"); + case 146 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 147 /* IfStatement */: + return emitIfStatement(node); + case 148 /* DoStatement */: + return emitDoStatement(node); + case 149 /* WhileStatement */: + return emitWhileStatement(node); + case 150 /* ForStatement */: + return emitForStatement(node); + case 151 /* ForInStatement */: + return emitForInStatement(node); + case 152 /* ContinueStatement */: + case 153 /* BreakStatement */: + return emitBreakOrContinueStatement(node); + case 154 /* ReturnStatement */: + return emitReturnStatement(node); + case 155 /* WithStatement */: + return emitWithStatement(node); + case 156 /* SwitchStatement */: + return emitSwitchStatement(node); + case 157 /* CaseClause */: + case 158 /* DefaultClause */: + return emitCaseOrDefaultClause(node); + case 159 /* LabelledStatement */: + return emitLabelledStatement(node); + case 160 /* ThrowStatement */: + return emitThrowStatement(node); + case 161 /* TryStatement */: + return emitTryStatement(node); + case 163 /* CatchBlock */: + return emitCatchBlock(node); + case 165 /* DebuggerStatement */: + return emitDebuggerStatement(node); + case 166 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 169 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 171 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 172 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 174 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 177 /* SourceFile */: + return emitSourceFile(node); + } + } + if (compilerOptions.sourceMap) { + initializeEmitterWithSourceMaps(); + } + if (root) { + emit(root); + } + else { + ts.forEach(program.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + emit(sourceFile); + } + }); + } + writeLine(); + writeEmittedFiles(writer.getText()); + } + function emitDeclarations(jsFilePath, root) { + var writer = createTextWriter(); + var write = writer.write; + var writeLine = writer.writeLine; + var increaseIndent = writer.increaseIndent; + var decreaseIndent = writer.decreaseIndent; + var enclosingDeclaration; + function emitLines(nodes) { + for (var i = 0, n = nodes.length; i < n; i++) { + emitNode(nodes[i]); + } + } + function emitCommaList(nodes, eachNodeEmitFn) { + var currentWriterPos = writer.getTextPos(); + for (var i = 0, n = nodes.length; i < n; i++) { + if (currentWriterPos !== writer.getTextPos()) { + write(", "); + } + currentWriterPos = writer.getTextPos(); + eachNodeEmitFn(nodes[i]); + } + } + function emitSourceTextOfNode(node) { + write(getSourceTextOfLocalNode(node)); + } + function emitSourceFile(node) { + currentSourceFile = node; + enclosingDeclaration = node; + emitLines(node.statements); + } + function emitExportAssignment(node) { + write("export = "); + emitSourceTextOfNode(node.exportName); + write(";"); + writeLine(); + } + function emitDeclarationFlags(node) { + if (node.flags & 64 /* Static */) { + if (node.flags & 32 /* Private */) { + write("private "); + } + write("static "); + } + else { + if (node.flags & 32 /* Private */) { + write("private "); + } + else if (node.parent === currentSourceFile) { + if (node.flags & 1 /* Export */) { + write("export "); + } + if (node.kind !== 170 /* InterfaceDeclaration */) { + write("declare "); + } + } + } + } + function emitImportDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + if (node.flags & 1 /* Export */) { + write("export "); + } + write("import "); + emitSourceTextOfNode(node.name); + write(" = "); + if (node.entityName) { + emitSourceTextOfNode(node.entityName); + write(";"); + } + else { + write("require("); + emitSourceTextOfNode(node.externalModuleName); + write(");"); + } + writeLine(); + } + } + function emitModuleDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitDeclarationFlags(node); + write("module "); + emitSourceTextOfNode(node.name); + while (node.body.kind !== 173 /* ModuleBlock */) { + node = node.body; + write("."); + emitSourceTextOfNode(node.name); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitEnumDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitDeclarationFlags(node); + write("enum "); + emitSourceTextOfNode(node.name); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + } + } + function emitEnumMemberDeclaration(node) { + emitSourceTextOfNode(node.name); + var enumMemberValue = resolver.getEnumMemberValue(node); + if (enumMemberValue !== undefined) { + write(" = "); + write(enumMemberValue.toString()); + } + write(","); + writeLine(); + } + function emitTypeParameters(typeParameters) { + function emitTypeParameter(node) { + emitSourceTextOfNode(node.name); + if (node.constraint) { + write(" extends "); + resolver.writeTypeAtLocation(node.constraint, enclosingDeclaration, 0 /* None */, writer); + } + } + if (typeParameters) { + write("<"); + emitCommaList(typeParameters, emitTypeParameter); + write(">"); + } + } + function emitHeritageClause(typeReferences, isImplementsList) { + function emitTypeOfTypeReference(node) { + resolver.writeTypeAtLocation(node, enclosingDeclaration, 1 /* WriteArrayAsGenericType */, writer); + } + if (typeReferences) { + write(isImplementsList ? " implements " : " extends "); + emitCommaList(typeReferences, emitTypeOfTypeReference); + } + } + function emitClassDeclaration(node) { + function emitParameterProperties(constructorDeclaration) { + if (constructorDeclaration) { + ts.forEach(constructorDeclaration.parameters, function (param) { + if (param.flags & (16 /* Public */ | 32 /* Private */)) { + emitPropertyDeclaration(param); + } + }); + } + } + if (resolver.isDeclarationVisible(node)) { + emitDeclarationFlags(node); + write("class "); + emitSourceTextOfNode(node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + if (node.baseType) { + emitHeritageClause([node.baseType], false); + } + emitHeritageClause(node.implementedTypes, true); + write(" {"); + writeLine(); + increaseIndent(); + emitParameterProperties(getFirstConstructorWithBody(node)); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitInterfaceDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitDeclarationFlags(node); + write("interface "); + emitSourceTextOfNode(node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + emitHeritageClause(node.baseTypes, false); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitPropertyDeclaration(node) { + emitDeclarationFlags(node); + emitVariableDeclaration(node); + write(";"); + writeLine(); + } + function emitVariableDeclaration(node) { + if (node.kind !== 166 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + emitSourceTextOfNode(node.name); + if (node.kind === 115 /* Property */ && (node.flags & 4 /* QuestionMark */)) { + write("?"); + } + if (!(node.flags & 32 /* Private */)) { + write(": "); + resolver.writeTypeAtLocation(node, enclosingDeclaration, 0 /* None */, writer); + } + } + } + function emitVariableStatement(node) { + var hasDeclarationWithEmit = ts.forEach(node.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + if (hasDeclarationWithEmit) { + emitDeclarationFlags(node); + write("var "); + emitCommaList(node.declarations, emitVariableDeclaration); + write(";"); + writeLine(); + } + } + function emitAccessorDeclaration(node) { + var accessors = getAllAccessorDeclarations(node.parent, node); + if (node === accessors.firstAccessor) { + emitDeclarationFlags(node); + emitSourceTextOfNode(node.name); + if (!(node.flags & 32 /* Private */)) { + write(": "); + resolver.writeTypeAtLocation(node, enclosingDeclaration, 0 /* None */, writer); + } + write(";"); + writeLine(); + } + } + function emitFunctionDeclaration(node) { + if ((node.kind !== 167 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { + emitDeclarationFlags(node); + if (node.kind === 167 /* FunctionDeclaration */) { + write("function "); + emitSourceTextOfNode(node.name); + } + else if (node.kind === 117 /* Constructor */) { + write("constructor"); + } + else { + emitSourceTextOfNode(node.name); + if (node.flags & 4 /* QuestionMark */) { + write("?"); + } + } + emitSignatureDeclaration(node); + } + } + function emitConstructSignatureDeclaration(node) { + write("new "); + emitSignatureDeclaration(node); + } + function emitSignatureDeclaration(node) { + emitTypeParameters(node.typeParameters); + if (node.kind === 122 /* IndexSignature */) { + write("["); + } + else { + write("("); + } + emitCommaList(node.parameters, emitParameterDeclaration); + if (node.kind === 122 /* IndexSignature */) { + write("]"); + } + else { + write(")"); + } + if (node.kind !== 117 /* Constructor */ && !(node.flags & 32 /* Private */)) { + write(": "); + resolver.writeReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, 0 /* None */, writer); + } + write(";"); + writeLine(); + } + function emitParameterDeclaration(node) { + if (node.flags & 8 /* Rest */) { + write("..."); + } + emitSourceTextOfNode(node.name); + if (node.initializer || (node.flags & 4 /* QuestionMark */)) { + write("?"); + } + if (!(node.parent.flags & 32 /* Private */)) { + write(": "); + resolver.writeTypeAtLocation(node, enclosingDeclaration, 0 /* None */, writer); + } + } + function emitNode(node) { + switch (node.kind) { + case 117 /* Constructor */: + case 167 /* FunctionDeclaration */: + case 116 /* Method */: + return emitFunctionDeclaration(node); + case 121 /* ConstructSignature */: + return emitConstructSignatureDeclaration(node); + case 120 /* CallSignature */: + case 122 /* IndexSignature */: + return emitSignatureDeclaration(node); + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 144 /* VariableStatement */: + return emitVariableStatement(node); + case 115 /* Property */: + return emitPropertyDeclaration(node); + case 170 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 169 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 176 /* EnumMember */: + return emitEnumMemberDeclaration(node); + case 171 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 172 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 174 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 175 /* ExportAssignment */: + return emitExportAssignment(node); + case 177 /* SourceFile */: + return emitSourceFile(node); + } + } + function resolveScriptReference(sourceFile, reference) { + var referenceFileName = compilerOptions.noResolve ? reference.filename : ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(sourceFile.filename), reference.filename)); + return program.getSourceFile(referenceFileName); + } + var referencePathsOutput = ""; + function writeReferencePath(referencedFile) { + var declFileName = referencedFile.flags & 512 /* DeclarationFile */ ? referencedFile.filename : shouldEmitToOwnFile(referencedFile) ? getOwnEmitOutputFilePath(referencedFile, ".d.ts") : ts.getModuleNameFromFilename(compilerOptions.out) + ".d.ts"; + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, compilerHost.getCurrentDirectory(), false); + referencePathsOutput += "/// " + newLine; + } + if (root) { + var addedGlobalFileReference = false; + ts.forEach(root.referencedFiles, function (fileReference) { + var referencedFile = resolveScriptReference(root, fileReference); + if ((referencedFile.flags & 512 /* DeclarationFile */) || shouldEmitToOwnFile(referencedFile) || !addedGlobalFileReference) { + writeReferencePath(referencedFile); + if (!isExternalModuleOrDeclarationFile(referencedFile)) { + addedGlobalFileReference = true; + } + } + }); + emitNode(root); + } + else { + var emittedReferencedFiles = []; + ts.forEach(program.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = resolveScriptReference(sourceFile, fileReference); + if (isExternalModuleOrDeclarationFile(referencedFile) && !ts.contains(emittedReferencedFiles, referencedFile)) { + writeReferencePath(referencedFile); + emittedReferencedFiles.push(referencedFile); + } + }); + emitNode(sourceFile); + } + }); + } + writeFile(ts.getModuleNameFromFilename(jsFilePath) + ".d.ts", referencePathsOutput + writer.getText()); + } + var shouldEmitDeclarations = resolver.shouldEmitDeclarations(); + function emitFile(jsFilePath, sourceFile) { + emitJavaScript(jsFilePath, sourceFile); + if (shouldEmitDeclarations) { + emitDeclarations(jsFilePath, sourceFile); + } + } + ts.forEach(program.getSourceFiles(), function (sourceFile) { + if (shouldEmitToOwnFile(sourceFile)) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, ".js"); + emitFile(jsFilePath, sourceFile); + } + }); + if (compilerOptions.out) { + emitFile(compilerOptions.out); + } + return { + errors: diagnostics, + sourceMaps: sourceMapDataList + }; + } + ts.emitFiles = emitFiles; +})(ts || (ts = {})); +var ts; +(function (ts) { + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + function createTypeChecker(program) { + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var emptyArray = []; + var emptySymbols = {}; + var undefinedSymbol = createSymbol(2 /* Property */ | 33554432 /* Transient */, "undefined"); + var argumentsSymbol = createSymbol(2 /* Property */ | 33554432 /* Transient */, "arguments"); + var unknownSymbol = createSymbol(2 /* Property */ | 33554432 /* Transient */, "unknown"); + var resolvingSymbol = createSymbol(33554432 /* Transient */, "__resolving__"); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var stringType = createIntrinsicType(2 /* String */, "string"); + var numberType = createIntrinsicType(4 /* Number */, "number"); + var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); + var voidType = createIntrinsicType(16 /* Void */, "void"); + var undefinedType = createIntrinsicType(32 /* Undefined */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */, "null"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var resolvingType = createIntrinsicType(1 /* Any */, "__resolving__"); + 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 globals = {}; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var stringLiteralTypes = {}; + var emitExtends = false; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var potentialThisCollisions = []; + var diagnostics = []; + var diagnosticsModified = false; + var checker = { + getProgram: function () { return program; }, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getNodeCount: function () { return ts.sum(program.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(program.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(program.getSourceFiles(), "symbolCount"); }, + getTypeCount: function () { return typeCount; }, + checkProgram: checkProgram, + emitFiles: invokeEmitter, + getSymbolOfNode: getSymbolOfNode, + getParentOfSymbol: getParentOfSymbol, + getTypeOfSymbol: getTypeOfSymbol, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getReturnTypeOfSignature: getReturnTypeOfSignature, + resolveEntityName: resolveEntityName, + getSymbolsInScope: getSymbolsInScope, + getSymbolOfIdentifier: getSymbolOfIdentifier, + getTypeOfExpression: getTypeOfExpression, + typeToString: typeToString, + symbolToString: symbolToString, + getAugmentedPropertiesOfApparentType: getAugmentedPropertiesOfApparentType + }; + function addDiagnostic(diagnostic) { + diagnostics.push(diagnostic); + diagnosticsModified = true; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + addDiagnostic(diagnostic); + } + function createSymbol(flags, name) { + return new Symbol(flags, name); + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 1 /* Variable */) + result |= ts.SymbolFlags.VariableExcludes; + if (flags & 2 /* Property */) + result |= ts.SymbolFlags.PropertyExcludes; + if (flags & 4 /* EnumMember */) + result |= ts.SymbolFlags.EnumMemberExcludes; + if (flags & 8 /* Function */) + result |= ts.SymbolFlags.FunctionExcludes; + if (flags & 16 /* Class */) + result |= ts.SymbolFlags.ClassExcludes; + if (flags & 32 /* Interface */) + result |= ts.SymbolFlags.InterfaceExcludes; + if (flags & 64 /* Enum */) + result |= ts.SymbolFlags.EnumExcludes; + if (flags & 128 /* ValueModule */) + result |= ts.SymbolFlags.ValueModuleExcludes; + if (flags & 2048 /* Method */) + result |= ts.SymbolFlags.MethodExcludes; + if (flags & 8192 /* GetAccessor */) + result |= ts.SymbolFlags.GetAccessorExcludes; + if (flags & 16384 /* SetAccessor */) + result |= ts.SymbolFlags.SetAccessorExcludes; + if (flags & 262144 /* TypeParameter */) + result |= ts.SymbolFlags.TypeParameterExcludes; + if (flags & 4194304 /* Import */) + result |= ts.SymbolFlags.ImportExcludes; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) + source.mergeId = nextMergeId++; + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags | 16777216 /* Merged */, symbol.name); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.members) + result.members = cloneSymbolTable(symbol.members); + if (symbol.exports) + result.exports = cloneSymbolTable(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function extendSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + target.flags |= source.flags; + if (!target.valueDeclaration && source.valueDeclaration) + target.valueDeclaration = source.valueDeclaration; + ts.forEach(source.declarations, function (node) { + target.declarations.push(node); + }); + if (source.members) { + if (!target.members) + target.members = {}; + extendSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = {}; + extendSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else { + ts.forEach(source.declarations, function (node) { + error(node.name ? node.name : node, ts.Diagnostics.Duplicate_identifier_0, symbolToString(source)); + }); + } + } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } + function extendSymbolTable(target, source) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 16777216 /* Merged */)) { + target[id] = symbol = cloneSymbol(symbol); + } + extendSymbol(symbol, source[id]); + } + } + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + if (!symbol.id) + symbol.id = nextSymbolId++; + return symbolLinks[symbol.id] || (symbolLinks[symbol.id] = {}); + } + function getNodeLinks(node) { + if (!node.id) + node.id = nextNodeId++; + return nodeLinks[node.id] || (nodeLinks[node.id] = {}); + } + function getSourceFile(node) { + return getAncestor(node, 177 /* SourceFile */); + } + function isGlobalSourceFile(node) { + return node.kind === 177 /* SourceFile */ && !ts.isExternalModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning && ts.hasProperty(symbols, name)) { + var symbol = symbols[name]; + ts.Debug.assert((symbol.flags & 8388608 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 4194304 /* Import */) { + var target = resolveImport(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + 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); + return undefined; + } + if (!s && nameNotFoundMessage) { + error(errorLocation, nameNotFoundMessage, nameArg); + } + return s; + } + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = getSymbol(location.locals, name, meaning)) { + return returnResolvedSymbol(result); + } + } + switch (location.kind) { + case 177 /* SourceFile */: + if (!ts.isExternalModule(location)) + break; + case 172 /* ModuleDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & ts.SymbolFlags.ModuleMember)) { + return returnResolvedSymbol(result); + } + break; + case 171 /* EnumDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 4 /* EnumMember */)) { + return returnResolvedSymbol(result); + } + break; + case 115 /* Property */: + if (location.parent.kind === 169 /* ClassDeclaration */ && !(location.flags & 64 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (getSymbol(ctor.locals, name, meaning & ts.SymbolFlags.Value)) { + memberWithInitializerThatReferencesIdentifierFromConstructor = location; + } + } + } + break; + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & ts.SymbolFlags.Type)) { + if (lastLocation && lastLocation.flags & 64 /* Static */) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + else { + return returnResolvedSymbol(result); + } + } + break; + case 116 /* Method */: + case 117 /* Constructor */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 167 /* FunctionDeclaration */: + case 137 /* ArrowFunction */: + if (name === "arguments") { + return returnResolvedSymbol(argumentsSymbol); + } + break; + case 136 /* FunctionExpression */: + if (name === "arguments") { + return returnResolvedSymbol(argumentsSymbol); + } + var id = location.name; + if (id && name === id.text) { + return returnResolvedSymbol(location.symbol); + } + break; + case 163 /* CatchBlock */: + var id = location.variable; + if (name === id.text) { + return returnResolvedSymbol(location.variable.symbol); + } + break; + } + lastLocation = location; + location = location.parent; + } + if (result = getSymbol(globals, name, meaning)) { + return returnResolvedSymbol(result); + } + return returnResolvedSymbol(undefined); + } + function resolveImport(symbol) { + ts.Debug.assert((symbol.flags & 4194304 /* Import */) !== 0, "Should only get Imports here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfKind(symbol, 174 /* ImportDeclaration */); + var target = node.externalModuleName ? resolveExternalModuleName(node, node.externalModuleName) : resolveEntityName(node, node.entityName, node.entityName.kind === 112 /* QualifiedName */ ? ts.SymbolFlags.Value | ts.SymbolFlags.Type | ts.SymbolFlags.Namespace : ts.SymbolFlags.Namespace); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + function resolveEntityName(location, name, meaning) { + if (name.kind === 55 /* Identifier */) { + var symbol = resolveName(location, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(name)); + if (!symbol) { + return; + } + } + else if (name.kind === 112 /* QualifiedName */) { + var namespace = resolveEntityName(location, name.left, ts.SymbolFlags.Namespace); + if (!namespace || namespace === unknownSymbol || name.right.kind === 111 /* Missing */) + return; + var symbol = getSymbol(namespace.exports, name.right.text, meaning); + if (!symbol) { + error(location, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.identifierToString(name.right)); + return; + } + } + else { + return; + } + ts.Debug.assert((symbol.flags & 8388608 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return symbol.flags & meaning ? symbol : resolveImport(symbol); + } + function isExternalModuleNameRelative(moduleName) { + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + function resolveExternalModuleName(location, moduleLiteral) { + var searchPath = ts.getDirectoryPath(getSourceFile(location).filename); + var moduleName = moduleLiteral.text; + if (!moduleName) + return; + var isRelative = isExternalModuleNameRelative(moduleName); + if (!isRelative) { + var symbol = getSymbol(globals, '"' + moduleName + '"', 128 /* ValueModule */); + if (symbol) { + return getResolvedExportSymbol(symbol); + } + } + while (true) { + var filename = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); + var sourceFile = program.getSourceFile(filename + ".ts") || program.getSourceFile(filename + ".d.ts"); + if (sourceFile || isRelative) + break; + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) + break; + searchPath = parentPath; + } + if (sourceFile) { + if (sourceFile.symbol) { + return getResolvedExportSymbol(sourceFile.symbol); + } + error(moduleLiteral, ts.Diagnostics.File_0_is_not_an_external_module, sourceFile.filename); + return; + } + error(moduleLiteral, ts.Diagnostics.Cannot_find_external_module_0, moduleName); + } + function getResolvedExportSymbol(moduleSymbol) { + var symbol = getExportAssignmentSymbol(moduleSymbol); + if (symbol) { + if (symbol.flags & (ts.SymbolFlags.Value | ts.SymbolFlags.Type | ts.SymbolFlags.Namespace)) { + return symbol; + } + if (symbol.flags & 4194304 /* Import */) { + return resolveImport(symbol); + } + } + return moduleSymbol; + } + function getExportAssignmentSymbol(symbol) { + checkTypeOfExportAssignmentSymbol(symbol); + return symbol.exportAssignSymbol === unknownSymbol ? undefined : symbol.exportAssignSymbol; + } + function checkTypeOfExportAssignmentSymbol(containerSymbol) { + if (!containerSymbol.exportAssignSymbol) { + var exportInformation = collectExportInformationForSourceFileOrModule(containerSymbol); + if (exportInformation.exportAssignments.length) { + if (exportInformation.exportAssignments.length > 1) { + ts.forEach(exportInformation.exportAssignments, function (node) { return error(node, ts.Diagnostics.A_module_cannot_have_more_than_one_export_assignment); }); + } + var node = exportInformation.exportAssignments[0]; + if (exportInformation.hasExportedMember) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + 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)); + } + } + containerSymbol.exportAssignSymbol = exportSymbol || unknownSymbol; + } + } + function collectExportInformationForSourceFileOrModule(symbol) { + var seenExportedMember = false; + var result = []; + ts.forEach(symbol.declarations, function (declaration) { + var block = (declaration.kind === 177 /* SourceFile */ ? declaration : declaration.body); + ts.forEach(block.statements, function (node) { + if (node.kind === 175 /* ExportAssignment */) { + result.push(node); + } + else { + seenExportedMember = seenExportedMember || (node.flags & 1 /* Export */) !== 0; + } + }); + }); + return { + hasExportedMember: seenExportedMember, + exportAssignments: result + }; + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 524288 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) : symbol; + } + function symbolIsValue(symbol) { + if (symbol.flags & ts.SymbolFlags.Value) { + return true; + } + if (symbol.flags & 4194304 /* Import */) { + return (resolveImport(symbol).flags & ts.SymbolFlags.Value) !== 0; + } + if (symbol.flags & 8388608 /* Instantiated */) { + return (getSymbolLinks(symbol).target.flags & ts.SymbolFlags.Value) !== 0; + } + return false; + } + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + for (var i = 0; i < declarations.length; i++) { + var declaration = declarations[i]; + if (declaration.kind === kind) { + return declaration; + } + } + return undefined; + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if (member.kind === 117 /* Constructor */ && member.body) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + result.id = typeCount++; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createObjectType(kind, symbol) { + var type = createType(kind); + type.symbol = symbol; + return type; + } + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) !== 95 /* _ */; + } + function getNamedMembers(members) { + var result; + for (var id in members) { + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + } + } + return result || emptyArray; + } + function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexType) + type.stringIndexType = stringIndexType; + if (numberIndexType) + type.numberIndexType = numberIndexType; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + return setObjectTypeMembers(createObjectType(8192 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function isOptionalProperty(propertySymbol) { + if (propertySymbol.flags & 67108864 /* Prototype */) { + return false; + } + return (propertySymbol.valueDeclaration.flags & 4 /* QuestionMark */) && propertySymbol.valueDeclaration.kind !== 114 /* Parameter */; + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 177 /* SourceFile */: + if (!ts.isExternalModule(location)) { + break; + } + case 172 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + if (result = callback(getSymbolOfNode(location).members)) { + return result; + } + break; + } + } + return callback(globals); + } + function getAccessibleSymbol(symbol, enclosingDeclaration, meaning) { + function getAccessibleSymbolFromSymbolTable(symbols) { + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + var accessibleParent = getAccessibleSymbol(symbolFromSymbolTable.parent, enclosingDeclaration, ts.SymbolFlags.Namespace); + return !!accessibleParent; + } + } + if (isAccessible(symbols[symbol.name])) { + return symbol; + } + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 4194304 /* Import */) { + if (isAccessible(symbolFromSymbolTable, resolveImport(symbolFromSymbolTable))) { + return symbolFromSymbolTable; + } + } + }); + } + if (symbol) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + if (!symbolTable[symbol.name]) { + return false; + } + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (symbolFromSymbolTable === symbol) { + return true; + } + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 4194304 /* Import */) ? resolveImport(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + return false; + }); + return qualify; + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + function getSymbolName(symbol) { + if (symbol.declarations && symbol.declarations.length > 0) { + var declaration = symbol.declarations[0]; + if (declaration.name) { + return ts.identifierToString(declaration.name); + } + } + return symbol.name; + } + if (enclosingDeclaration && !(symbol.flags & ts.SymbolFlags.PropertyOrAccessor & ts.SymbolFlags.Signature & 4096 /* Constructor */ & 2048 /* Method */ & 262144 /* TypeParameter */)) { + var symbolName; + while (symbol) { + var isFirstName = !symbolName; + var meaningToLook = isFirstName ? meaning : ts.SymbolFlags.Namespace; + var accessibleSymbol = getAccessibleSymbol(symbol, enclosingDeclaration, meaningToLook); + symbolName = getSymbolName(accessibleSymbol || symbol) + (isFirstName ? "" : ("." + symbolName)); + if (accessibleSymbol && !needsQualification(accessibleSymbol, enclosingDeclaration, meaningToLook)) { + break; + } + symbol = accessibleSymbol ? accessibleSymbol.parent : symbol.parent; + } + return symbolName; + } + return getSymbolName(symbol); + } + function createSingleLineTextWriter() { + var result = ""; + return { + write: function (s) { + result += s; + }, + writeLine: function () { + result += " "; + }, + increaseIndent: function () { + }, + decreaseIndent: function () { + }, + getText: function () { + return result; + } + }; + } + function typeToString(type, enclosingDeclaration, flags) { + var stringWriter = createSingleLineTextWriter(); + writeTypeToTextWriter(type, enclosingDeclaration, flags, stringWriter); + return stringWriter.getText(); + } + function writeTypeToTextWriter(type, enclosingDeclaration, flags, writer) { + var typeStack; + return writeType(type, true); + function writeType(type, allowFunctionOrConstructorTypeLiteral) { + if (type.flags & ts.TypeFlags.Intrinsic) { + writer.write(type.intrinsicName); + } + else if (type.flags & 4096 /* Reference */) { + writeTypeReference(type); + } + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */ | 128 /* Enum */ | 512 /* TypeParameter */)) { + writer.write(symbolToString(type.symbol, enclosingDeclaration, ts.SymbolFlags.Type)); + } + else if (type.flags & 8192 /* Anonymous */) { + writeAnonymousType(type, allowFunctionOrConstructorTypeLiteral); + } + else if (type.flags & 256 /* StringLiteral */) { + writer.write(type.text); + } + else { + writer.write("{ ... }"); + } + } + function writeTypeReference(type) { + if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { + writeType(type.typeArguments[0], false); + writer.write("[]"); + } + else { + writer.write(symbolToString(type.target.symbol, enclosingDeclaration, ts.SymbolFlags.Type)); + writer.write("<"); + for (var i = 0; i < type.typeArguments.length; i++) { + if (i > 0) { + writer.write(", "); + } + writeType(type.typeArguments[i], true); + } + writer.write(">"); + } + } + function writeAnonymousType(type, allowFunctionOrConstructorTypeLiteral) { + if (type.symbol && type.symbol.flags & (16 /* Class */ | 64 /* Enum */ | 128 /* ValueModule */)) { + writeTypeofSymbol(type); + } + else if (type.symbol && type.symbol.flags & (8 /* Function */ | 2048 /* Method */) && typeStack && ts.contains(typeStack, type)) { + writeTypeofSymbol(type); + } + else { + if (!typeStack) { + typeStack = []; + } + typeStack.push(type); + writeLiteralType(type, allowFunctionOrConstructorTypeLiteral); + typeStack.pop(); + } + } + function writeTypeofSymbol(type) { + writer.write("typeof "); + writer.write(symbolToString(type.symbol, enclosingDeclaration, ts.SymbolFlags.Value)); + } + function writeLiteralType(type, allowFunctionOrConstructorTypeLiteral) { + var resolved = resolveObjectTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writer.write("{}"); + return; + } + if (allowFunctionOrConstructorTypeLiteral) { + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + writeSignature(resolved.callSignatures[0], true); + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + writer.write("new "); + writeSignature(resolved.constructSignatures[0], true); + return; + } + } + } + writer.write("{"); + writer.writeLine(); + writer.increaseIndent(); + for (var i = 0; i < resolved.callSignatures.length; i++) { + writeSignature(resolved.callSignatures[i]); + writer.write(";"); + writer.writeLine(); + } + for (var i = 0; i < resolved.constructSignatures.length; i++) { + writer.write("new "); + writeSignature(resolved.constructSignatures[i]); + writer.write(";"); + writer.writeLine(); + } + if (resolved.stringIndexType) { + writer.write("[x: string]: "); + writeType(resolved.stringIndexType, true); + writer.write(";"); + writer.writeLine(); + } + if (resolved.numberIndexType) { + writer.write("[x: number]: "); + writeType(resolved.numberIndexType, true); + writer.write(";"); + writer.writeLine(); + } + for (var i = 0; i < resolved.properties.length; i++) { + var p = resolved.properties[i]; + var t = getTypeOfSymbol(p); + if (p.flags & (8 /* Function */ | 2048 /* Method */) && !getPropertiesOfType(t).length) { + var signatures = getSignaturesOfType(t, 0 /* Call */); + for (var j = 0; j < signatures.length; j++) { + writer.write(symbolToString(p)); + if (isOptionalProperty(p)) { + writer.write("?"); + } + writeSignature(signatures[j]); + writer.write(";"); + writer.writeLine(); + } + } + else { + writer.write(symbolToString(p)); + if (isOptionalProperty(p)) { + writer.write("?"); + } + writer.write(": "); + writeType(t, true); + writer.write(";"); + writer.writeLine(); + } + } + writer.decreaseIndent(); + writer.write("}"); + } + function writeSignature(signature, arrowStyle) { + if (signature.typeParameters) { + writer.write("<"); + for (var i = 0; i < signature.typeParameters.length; i++) { + if (i > 0) { + writer.write(", "); + } + var tp = signature.typeParameters[i]; + writer.write(symbolToString(tp.symbol)); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writer.write(" extends "); + writeType(constraint, true); + } + } + writer.write(">"); + } + writer.write("("); + for (var i = 0; i < signature.parameters.length; i++) { + if (i > 0) { + writer.write(", "); + } + var p = signature.parameters[i]; + if (getDeclarationFlagsFromSymbol(p) & 8 /* Rest */) { + writer.write("..."); + } + writer.write(symbolToString(p)); + if (p.valueDeclaration.flags & 4 /* QuestionMark */ || p.valueDeclaration.initializer) { + writer.write("?"); + } + writer.write(": "); + writeType(getTypeOfSymbol(p), true); + } + writer.write(arrowStyle ? ") => " : "): "); + writeType(getReturnTypeOfSignature(signature), true); + } + } + function isDeclarationVisible(node) { + function getContainingExternalModule(node) { + for (; node; node = node.parent) { + if (node.kind === 172 /* ModuleDeclaration */) { + if (node.name.kind === 3 /* StringLiteral */) { + return node; + } + } + else if (node.kind === 177 /* SourceFile */) { + return ts.isExternalModule(node) ? node : undefined; + } + } + ts.Debug.fail("getContainingModule cant reach here"); + } + function isUsedInExportAssignment(node) { + var externalModule = getContainingExternalModule(node); + if (externalModule) { + var externalModuleSymbol = getSymbolOfNode(externalModule); + var exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); + var symbolOfNode = getSymbolOfNode(node); + if (exportAssignmentSymbol === symbolOfNode) { + return true; + } + if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 4194304 /* Import */)) { + var resolvedExportSymbol = resolveImport(exportAssignmentSymbol); + if (resolvedExportSymbol === symbolOfNode) { + return true; + } + return ts.forEach(resolvedExportSymbol.declarations, function (declaration) { + while (declaration) { + if (declaration === node) { + return true; + } + declaration = declaration.parent; + } + }); + } + } + } + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 166 /* VariableDeclaration */: + if (!(node.flags & 1 /* Export */)) { + return isGlobalSourceFile(node.parent.parent) || isUsedInExportAssignment(node); + } + return isDeclarationVisible(node.parent.parent); + case 172 /* ModuleDeclaration */: + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + case 167 /* FunctionDeclaration */: + case 171 /* EnumDeclaration */: + case 174 /* ImportDeclaration */: + if (!(node.flags & 1 /* Export */)) { + return isGlobalSourceFile(node.parent) || isUsedInExportAssignment(node); + } + return isDeclarationVisible(node.parent); + case 115 /* Property */: + case 116 /* Method */: + if (node.flags & 32 /* Private */) { + return false; + } + case 117 /* Constructor */: + case 121 /* ConstructSignature */: + case 120 /* CallSignature */: + case 122 /* IndexSignature */: + case 114 /* Parameter */: + case 173 /* ModuleBlock */: + return isDeclarationVisible(node.parent); + case 177 /* SourceFile */: + return true; + default: + ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + ts.SyntaxKind[node.kind]); + } + } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + } + function getApparentType(type) { + if (type.flags & 512 /* TypeParameter */) { + do { + type = getConstraintOfTypeParameter(type); + } while (type && type.flags & 512 /* TypeParameter */); + if (!type) + type = emptyObjectType; + } + if (type.flags & ts.TypeFlags.StringLike) { + type = globalStringType; + } + else if (type.flags & ts.TypeFlags.NumberLike) { + type = globalNumberType; + } + else if (type.flags & 8 /* Boolean */) { + type = globalBooleanType; + } + return type; + } + function getTypeOfPrototypeProperty(prototype) { + var classType = getDeclaredTypeOfSymbol(prototype.parent); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + function getTypeOfVariableDeclaration(declaration) { + var type; + if (declaration.parent.kind === 163 /* CatchBlock */ || declaration.parent.kind === 151 /* ForInStatement */) { + type = anyType; + } + else if (declaration.type) { + type = getTypeFromTypeNode(declaration.type); + } + else { + if (declaration.kind === 114 /* Parameter */ && declaration.parent.kind === 119 /* SetAccessor */) { + var getter = getDeclarationOfKind(declaration.parent.symbol, 118 /* GetAccessor */); + if (getter) { + type = getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); + } + } + var unwidenedType; + if (!type) { + if (declaration.initializer) { + unwidenedType = checkAndMarkExpression(declaration.initializer); + type = getWidenedType(unwidenedType); + } + else if (declaration.flags & 8 /* Rest */) { + type = createArrayType(anyType); + } + else { + type = anyType; + } + } + if (program.getCompilerOptions().noImplicitAny && shouldReportNoImplicitAnyOnVariableOrParameterOrProperty(declaration, type, unwidenedType)) { + reportNoImplicitAnyOnVariableOrParameterOrProperty(declaration, type); + } + } + return type; + function shouldReportNoImplicitAnyOnVariableOrParameterOrProperty(declaration, type, unwidenedType) { + if (type === unwidenedType) { + return false; + } + if (getInnermostTypeOfNestedArrayTypes(type) !== anyType) { + return false; + } + if (isPrivateWithinAmbient(declaration) || (declaration.kind === 114 /* Parameter */ && isPrivateWithinAmbient(declaration.parent))) { + return false; + } + return true; + } + function reportNoImplicitAnyOnVariableOrParameterOrProperty(declaration, type) { + var varName = ts.identifierToString(declaration.name); + var typeName = typeToString(type); + switch (declaration.kind) { + case 166 /* VariableDeclaration */: + error(declaration, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, varName, typeName); + break; + case 115 /* Property */: + error(declaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, varName, typeName); + break; + case 114 /* Parameter */: + var funcDeclaration = declaration.parent; + if (declaration.flags & 8 /* Rest */) { + error(declaration, ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type, varName); + } + else { + error(declaration, ts.Diagnostics.Parameter_0_implicitly_has_an_1_type, varName, typeName); + } + break; + default: + ts.Debug.fail("Received a '" + ts.SyntaxKind[declaration.kind] + "', but expected '" + ts.SyntaxKind[166 /* VariableDeclaration */] + "', '" + ts.SyntaxKind[115 /* Property */] + "', or '" + ts.SyntaxKind[114 /* Parameter */] + "'.\r\n"); + } + } + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 67108864 /* Prototype */) { + links.type = getTypeOfPrototypeProperty(symbol); + } + else { + links.type = resolvingType; + var type = getTypeOfVariableDeclaration(symbol.valueDeclaration); + if (links.type === resolvingType) { + links.type = type; + } + } + } + else if (links.type === resolvingType) { + links.type = anyType; + } + return links.type; + } + function getSetAccessorTypeAnnotationNode(accessor) { + return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 118 /* GetAccessor */) { + return accessor.type && getTypeFromTypeNode(accessor.type); + } + else { + var setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + checkAndStoreTypeOfAccessors(symbol, links); + return links.type; + } + function checkAndStoreTypeOfAccessors(symbol, links) { + links = links || getSymbolLinks(symbol); + if (!links.type) { + links.type = resolvingType; + var getter = getDeclarationOfKind(symbol, 118 /* GetAccessor */); + var setter = getDeclarationOfKind(symbol, 119 /* SetAccessor */); + var type; + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + if (getter) { + type = getReturnTypeFromBody(getter); + } + else { + if (program.getCompilerOptions().noImplicitAny) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbol.name); + } + type = anyType; + } + } + } + if (links.type === resolvingType) { + links.type = type; + } + } + else if (links.type === resolvingType) { + links.type = anyType; + } + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var type = links.type = createObjectType(8192 /* Anonymous */, symbol); + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + } + return links.type; + } + function getTypeOfImport(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getTypeOfSymbol(resolveImport(symbol)); + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + } + return links.type; + } + function getTypeOfSymbol(symbol) { + if (symbol.flags & (1 /* Variable */ | 2 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (8 /* Function */ | 2048 /* Method */ | 16 /* Class */ | 64 /* Enum */ | 128 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 4 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & ts.SymbolFlags.Accessor) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 4194304 /* Import */) { + return getTypeOfImport(symbol); + } + if (symbol.flags & 8388608 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + return unknownType; + } + function getTargetType(type) { + return type.flags & 4096 /* Reference */ ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(target.baseTypes, check); + } + } + function getTypeParametersOfClassOrInterface(symbol) { + var result; + ts.forEach(symbol.declarations, function (node) { + if (node.kind === 170 /* InterfaceDeclaration */ || node.kind === 169 /* ClassDeclaration */) { + var declaration = node; + if (declaration.typeParameters && declaration.typeParameters.length) { + ts.forEach(declaration.typeParameters, function (node) { + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!result) { + result = [tp]; + } + else if (!ts.contains(result, tp)) { + result.push(tp); + } + }); + } + } + }); + return result; + } + function getDeclaredTypeOfClass(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = links.declaredType = createObjectType(1024 /* Class */, symbol); + var typeParameters = getTypeParametersOfClassOrInterface(symbol); + if (typeParameters) { + type.flags |= 4096 /* Reference */; + type.typeParameters = typeParameters; + type.instantiations = {}; + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + } + type.baseTypes = []; + var declaration = getDeclarationOfKind(symbol, 169 /* ClassDeclaration */); + if (declaration.baseType) { + var baseType = getTypeFromTypeReferenceNode(declaration.baseType); + if (baseType !== unknownType) { + if (getTargetType(baseType).flags & 1024 /* Class */) { + if (type !== baseType && !hasBaseType(baseType, type)) { + type.baseTypes.push(baseType); + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); + } + } + else { + error(declaration.baseType, ts.Diagnostics.A_class_may_only_extend_another_class); + } + } + } + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + } + return links.declaredType; + } + function getDeclaredTypeOfInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = links.declaredType = createObjectType(2048 /* Interface */, symbol); + var typeParameters = getTypeParametersOfClassOrInterface(symbol); + if (typeParameters) { + type.flags |= 4096 /* Reference */; + type.typeParameters = typeParameters; + type.instantiations = {}; + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + } + type.baseTypes = []; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 170 /* InterfaceDeclaration */ && declaration.baseTypes) { + ts.forEach(declaration.baseTypes, function (node) { + var baseType = getTypeFromTypeReferenceNode(node); + if (baseType !== unknownType) { + if (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + type.baseTypes.push(baseType); + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + }); + } + }); + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); + type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + } + return links.declaredType; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(128 /* Enum */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(512 /* TypeParameter */); + type.symbol = symbol; + if (!getDeclarationOfKind(symbol, 113 /* TypeParameter */).constraint) { + type.constraint = noConstraintType; + } + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfImport(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveImport(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & 16 /* Class */) { + return getDeclaredTypeOfClass(symbol); + } + if (symbol.flags & 32 /* Interface */) { + return getDeclaredTypeOfInterface(symbol); + } + if (symbol.flags & 64 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 4194304 /* Import */) { + return getDeclaredTypeOfImport(symbol); + } + ts.Debug.assert((symbol.flags & 8388608 /* Instantiated */) === 0); + return unknownType; + } + function createSymbolTable(symbols) { + var result = {}; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; + result[symbol.name] = symbol; + } + return result; + } + function createInstantiatedSymbolTable(symbols, mapper) { + var result = {}; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; + result[symbol.name] = instantiateSymbol(symbol, mapper); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var i = 0; i < baseSymbols.length; i++) { + var s = baseSymbols[i]; + if (!ts.hasProperty(symbols, s.name)) { + symbols[s.name] = s; + } + } + } + function addInheritedSignatures(signatures, baseSignatures) { + if (baseSignatures) { + for (var i = 0; i < baseSignatures.length; i++) { + signatures.push(baseSignatures[i]); + } + } + } + function resolveClassOrInterfaceMembers(type) { + var members = type.symbol.members; + var callSignatures = type.declaredCallSignatures; + var constructSignatures = type.declaredConstructSignatures; + var stringIndexType = type.declaredStringIndexType; + var numberIndexType = type.declaredNumberIndexType; + if (type.baseTypes.length) { + members = createSymbolTable(type.declaredProperties); + ts.forEach(type.baseTypes, function (baseType) { + addInheritedMembers(members, getPropertiesOfType(baseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(baseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(baseType, 1 /* Construct */)); + stringIndexType = stringIndexType || getIndexTypeOfType(baseType, 0 /* String */); + numberIndexType = numberIndexType || getIndexTypeOfType(baseType, 1 /* Number */); + }); + } + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function resolveTypeReferenceMembers(type) { + var target = type.target; + var mapper = createTypeMapper(target.typeParameters, type.typeArguments); + var members = createInstantiatedSymbolTable(target.declaredProperties, mapper); + var callSignatures = instantiateList(target.declaredCallSignatures, mapper, instantiateSignature); + var constructSignatures = instantiateList(target.declaredConstructSignatures, mapper, instantiateSignature); + var stringIndexType = target.declaredStringIndexType ? instantiateType(target.declaredStringIndexType, mapper) : undefined; + var numberIndexType = target.declaredNumberIndexType ? instantiateType(target.declaredNumberIndexType, mapper) : undefined; + ts.forEach(target.baseTypes, function (baseType) { + var instantiatedBaseType = instantiateType(baseType, mapper); + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, 0 /* String */); + numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, 1 /* Number */); + }); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.resolvedReturnType = resolvedReturnType; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasStringLiterals = hasStringLiterals; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + } + function getDefaultConstructSignatures(classType) { + if (classType.baseTypes.length) { + var baseType = classType.baseTypes[0]; + var baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), 1 /* Construct */); + return ts.map(baseSignatures, function (baseSignature) { + var signature = baseType.flags & 4096 /* Reference */ ? getSignatureInstantiation(baseSignature, baseType.typeArguments) : cloneSignature(baseSignature); + signature.typeParameters = classType.typeParameters; + signature.resolvedReturnType = classType; + return signature; + }); + } + return [createSignature(undefined, classType.typeParameters, emptyArray, classType, 0, false, false)]; + } + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + var members = emptySymbols; + var callSignatures = emptyArray; + var constructSignatures = emptyArray; + if (symbol.flags & ts.SymbolFlags.HasExports) { + members = symbol.exports; + } + if (symbol.flags & (8 /* Function */ | 2048 /* Method */)) { + callSignatures = getSignaturesOfSymbol(symbol); + } + if (symbol.flags & 16 /* Class */) { + var classType = getDeclaredTypeOfClass(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); + if (!constructSignatures.length) + constructSignatures = getDefaultConstructSignatures(classType); + if (classType.baseTypes.length) { + var members = createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(getTypeOfSymbol(classType.baseTypes[0].symbol))); + } + } + var numberIndexType = (symbol.flags & 64 /* Enum */) ? stringType : undefined; + setObjectTypeMembers(type, members, callSignatures, constructSignatures, undefined, numberIndexType); + } + function resolveObjectTypeMembers(type) { + if (!type.members) { + if (type.flags & (1024 /* Class */ | 2048 /* Interface */)) { + resolveClassOrInterfaceMembers(type); + } + else if (type.flags & 8192 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else { + resolveTypeReferenceMembers(type); + } + } + return type; + } + function getPropertiesOfType(type) { + if (type.flags & ts.TypeFlags.ObjectType) { + return resolveObjectTypeMembers(type).properties; + } + return emptyArray; + } + function getPropertyOfType(type, name) { + if (type.flags & ts.TypeFlags.ObjectType) { + var resolved = resolveObjectTypeMembers(type); + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } + } + } + } + function getPropertyOfApparentType(type, name) { + if (type.flags & ts.TypeFlags.ObjectType) { + var resolved = resolveObjectTypeMembers(type); + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol = getPropertyOfType(globalFunctionType, name); + if (symbol) + return symbol; + } + return getPropertyOfType(globalObjectType, name); + } + } + function getSignaturesOfType(type, kind) { + if (type.flags & ts.TypeFlags.ObjectType) { + var resolved = resolveObjectTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return emptyArray; + } + function getIndexTypeOfType(type, kind) { + if (type.flags & ts.TypeFlags.ObjectType) { + var resolved = resolveObjectTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexType : resolved.numberIndexType; + } + } + function getTypeParametersFromDeclaration(typeParameterDeclarations) { + var result = []; + ts.forEach(typeParameterDeclarations, function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + result.push(tp); + } + }); + return result; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var classType = declaration.kind === 117 /* Constructor */ ? getDeclaredTypeOfClass(declaration.parent.symbol) : undefined; + var typeParameters = classType ? classType.typeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + var parameters = []; + var hasStringLiterals = false; + var minArgumentCount = -1; + for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var param = declaration.parameters[i]; + parameters.push(param.symbol); + if (param.type && param.type.kind === 3 /* StringLiteral */) { + hasStringLiterals = true; + } + if (minArgumentCount < 0) { + if (param.initializer || param.flags & (4 /* QuestionMark */ | 8 /* Rest */)) { + minArgumentCount = i; + } + } + } + if (minArgumentCount < 0) { + minArgumentCount = declaration.parameters.length; + } + var returnType; + if (classType) { + returnType = classType; + } + else if (declaration.type) { + returnType = getTypeFromTypeNode(declaration.type); + } + else { + if (declaration.kind === 118 /* GetAccessor */) { + var setter = getDeclarationOfKind(declaration.symbol, 119 /* SetAccessor */); + returnType = getAnnotatedAccessorType(setter); + } + if (!returnType && !declaration.body) { + returnType = anyType; + } + } + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameters(declaration), hasStringLiterals); + } + return links.resolvedSignature; + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return emptyArray; + var result = []; + for (var i = 0, len = symbol.declarations.length; i < len; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 167 /* FunctionDeclaration */: + case 116 /* Method */: + case 117 /* Constructor */: + case 120 /* CallSignature */: + case 121 /* ConstructSignature */: + case 122 /* IndexSignature */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = resolvingType; + if (signature.target) { + var type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else { + var type = getReturnTypeFromBody(signature.declaration); + } + if (signature.resolvedReturnType === resolvingType) { + signature.resolvedReturnType = type; + } + } + else if (signature.resolvedReturnType === resolvingType) { + signature.resolvedReturnType = anyType; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + if (signature.target) { + signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); + } + else { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 117 /* Constructor */ || signature.declaration.kind === 121 /* ConstructSignature */; + var type = createObjectType(8192 /* Anonymous */ | 16384 /* FromSignature */); + type.members = emptySymbols; + type.properties = emptyArray; + type.callSignatures = !isConstructor ? [signature] : emptyArray; + type.constructSignatures = isConstructor ? [signature] : emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members["__index"]; + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 108 /* NumberKeyword */ : 110 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + var len = indexSymbol.declarations.length; + for (var i = 0; i < len; i++) { + var node = indexSymbol.declarations[i]; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function getIndexTypeOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + return declaration ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; + } + function getConstraintOfTypeParameter(type) { + if (!type.constraint) { + if (type.target) { + var targetConstraint = getConstraintOfTypeParameter(type.target); + type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + } + else { + type.constraint = getTypeFromTypeNode(getDeclarationOfKind(type.symbol, 113 /* TypeParameter */).constraint); + } + } + return type.constraint === noConstraintType ? undefined : type.constraint; + } + function getTypeListId(types) { + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) + result += ","; + result += types[i].id; + } + return result; + } + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations[id]; + if (!type) { + type = target.instantiations[id] = createObjectType(4096 /* Reference */, target.symbol); + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { + var links = getNodeLinks(typeReferenceNode); + if (links.isIllegalTypeReferenceInConstraint !== undefined) { + return links.isIllegalTypeReferenceInConstraint; + } + var currentNode = typeReferenceNode; + while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { + currentNode = currentNode.parent; + } + links.isIllegalTypeReferenceInConstraint = currentNode.kind === 113 /* TypeParameter */; + return links.isIllegalTypeReferenceInConstraint; + } + function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { + var typeParameterSymbol; + function check(n) { + if (n.kind === 123 /* TypeReference */ && n.typeName.kind === 55 /* Identifier */) { + var links = getNodeLinks(n); + if (links.isIllegalTypeReferenceInConstraint === undefined) { + var symbol = resolveName(typeParameter, n.typeName.text, ts.SymbolFlags.Type, undefined, undefined); + if (symbol && (symbol.flags & 262144 /* TypeParameter */)) { + links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent == typeParameter.parent; }); + } + } + if (links.isIllegalTypeReferenceInConstraint) { + error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } + ts.forEachChild(n, check); + } + if (typeParameter.constraint) { + typeParameterSymbol = getSymbolOfNode(typeParameter); + check(typeParameter.constraint); + } + } + function getTypeFromTypeReferenceNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = resolveEntityName(node, node.typeName, ts.SymbolFlags.Type); + if (symbol) { + var type; + if ((symbol.flags & 262144 /* TypeParameter */) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + type = unknownType; + } + else { + type = getDeclaredTypeOfSymbol(symbol); + if (type.flags & (1024 /* Class */ | 2048 /* Interface */) && type.flags & 4096 /* Reference */) { + var typeParameters = type.typeParameters; + if (node.typeArguments && node.typeArguments.length === typeParameters.length) { + type = createTypeReference(type, ts.map(node.typeArguments, function (t) { return getTypeFromTypeNode(t); })); + } + else { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length); + type = undefined; + } + } + else { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + type = undefined; + } + } + } + } + links.resolvedType = type || unknownType; + } + return links.resolvedType; + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getGlobalType(name, arity) { + if (arity === void 0) { arity = 0; } + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var i = 0; i < declarations.length; i++) { + var declaration = declarations[i]; + switch (declaration.kind) { + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + case 171 /* EnumDeclaration */: + case 125 /* TypeLiteral */: + case 167 /* FunctionDeclaration */: + return declaration; + } + } + } + var symbol = resolveName(undefined, name, ts.SymbolFlags.Type, ts.Diagnostics.Cannot_find_global_type_0, name); + if (!symbol) { + return emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & ts.TypeFlags.ObjectType)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, name); + return emptyObjectType; + } + if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, name, arity); + return emptyObjectType; + } + return type; + } + function createArrayType(elementType, arrayType) { + var rootType = globalArrayType || arrayType; + return rootType !== emptyObjectType ? createTypeReference(rootType, [elementType]) : emptyObjectType; + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var arrayType = globalArrayType; + if (!arrayType) { + var arrayTypeSymbol = resolveName(node, "Array", ts.SymbolFlags.Type, undefined, undefined); + ts.Debug.assert(arrayTypeSymbol); + arrayType = getDeclaredTypeOfSymbol(arrayTypeSymbol); + ts.Debug.assert(arrayType); + } + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), arrayType); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = node.symbol; + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + var numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + links.resolvedType = createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + return links.resolvedType; + } + function getStringLiteralType(node) { + if (ts.hasProperty(stringLiteralTypes, node.text)) + return stringLiteralTypes[node.text]; + var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */); + type.text = ts.getSourceTextOfNode(node); + return type; + } + function getTypeFromStringLiteral(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getStringLiteralType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 101 /* AnyKeyword */: + return anyType; + case 110 /* StringKeyword */: + return stringType; + case 108 /* NumberKeyword */: + return numberType; + case 102 /* BooleanKeyword */: + return booleanType; + case 89 /* VoidKeyword */: + return voidType; + case 3 /* StringLiteral */: + return getTypeFromStringLiteral(node); + case 123 /* TypeReference */: + return getTypeFromTypeReferenceNode(node); + case 124 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 126 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 125 /* TypeLiteral */: + return getTypeFromTypeLiteralNode(node); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var i = 0; i < items.length; i++) { + result.push(instantiator(items[i], mapper)); + } + return result; + } + return items; + } + function createUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function createBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function createTypeMapper(sources, targets) { + switch (sources.length) { + case 1: + return createUnaryTypeMapper(sources[0], targets[0]); + case 2: + return createBinaryTypeMapper(sources[0], targets[0], sources[1], targets[1]); + } + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) + return targets[i]; + } + return t; + }; + } + function createUnaryTypeEraser(source) { + return function (t) { return t === source ? anyType : t; }; + } + function createBinaryTypeEraser(source1, source2) { + return function (t) { return t === source1 || t === source2 ? anyType : t; }; + } + function createTypeEraser(sources) { + switch (sources.length) { + case 1: + return createUnaryTypeEraser(sources[0]); + case 2: + return createBinaryTypeEraser(sources[0], sources[1]); + } + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) + return anyType; + } + return t; + }; + } + function createInferenceMapper(context) { + return function (t) { + for (var i = 0; i < context.typeParameters.length; i++) { + if (t === context.typeParameters[i]) { + return getInferredType(context, i); + } + } + return t; + }; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + return function (t) { return mapper2(mapper1(t)); }; + } + function instantiateTypeParameter(typeParameter, mapper) { + var result = createType(512 /* TypeParameter */); + result.symbol = typeParameter.symbol; + if (typeParameter.constraint) { + result.constraint = instantiateType(typeParameter.constraint, mapper); + } + else { + result.target = typeParameter; + result.mapper = mapper; + } + return result; + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + if (signature.typeParameters && !eraseTypeParameters) { + var freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + } + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + if (symbol.flags & 8388608 /* Instantiated */) { + var links = getSymbolLinks(symbol); + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + var result = createSymbol(8388608 /* Instantiated */ | 33554432 /* Transient */, symbol.name); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(8192 /* Anonymous */, type.symbol); + result.properties = instantiateList(getPropertiesOfType(type), mapper, instantiateSymbol); + result.members = createSymbolTable(result.properties); + result.callSignatures = instantiateList(getSignaturesOfType(type, 0 /* Call */), mapper, instantiateSignature); + result.constructSignatures = instantiateList(getSignaturesOfType(type, 1 /* Construct */), mapper, instantiateSignature); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType) + result.stringIndexType = instantiateType(stringIndexType, mapper); + if (numberIndexType) + result.numberIndexType = instantiateType(numberIndexType, mapper); + return result; + } + function instantiateType(type, mapper) { + if (type.flags & 512 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 8192 /* Anonymous */) { + return type.symbol && type.symbol.flags & (8 /* Function */ | 2048 /* Method */ | 512 /* TypeLiteral */ | 1024 /* ObjectLiteral */) ? instantiateAnonymousType(type, mapper) : type; + } + if (type.flags & 4096 /* Reference */) { + return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + } + return type; + } + function isContextSensitiveExpression(node) { + switch (node.kind) { + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + return !node.typeParameters && !ts.forEach(node.parameters, function (p) { return p.type; }); + case 128 /* ObjectLiteral */: + return ts.forEach(node.properties, function (p) { return p.kind === 129 /* PropertyAssignment */ && isContextSensitiveExpression(p.initializer); }); + case 127 /* ArrayLiteral */: + return ts.forEach(node.elements, function (e) { return isContextSensitiveExpression(e); }); + case 141 /* ConditionalExpression */: + return isContextSensitiveExpression(node.whenTrue) || isContextSensitiveExpression(node.whenFalse); + case 140 /* BinaryExpression */: + return node.operator === 40 /* BarBarToken */ && (isContextSensitiveExpression(node.left) || isContextSensitiveExpression(node.right)); + } + return false; + } + function getTypeWithoutConstructors(type) { + if (type.flags & ts.TypeFlags.ObjectType) { + var resolved = resolveObjectTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(8192 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = resolved.callSignatures; + result.constructSignatures = emptyArray; + type = result; + } + } + return type; + } + var subtypeRelation = {}; + var assignableRelation = {}; + var identityRelation = {}; + function isTypeIdenticalTo(source, target) { + return checkTypeRelatedTo(source, target, identityRelation, undefined, undefined, undefined); + } + function isTypeSubtypeOf(source, target) { + return checkTypeSubtypeOf(source, target, undefined, undefined, undefined); + } + function checkTypeSubtypeOf(source, target, errorNode, chainedMessage, terminalMessage) { + return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, chainedMessage, terminalMessage); + } + function isTypeAssignableTo(source, target) { + return checkTypeAssignableTo(source, target, undefined, undefined, undefined); + } + function checkTypeAssignableTo(source, target, errorNode, chainedMessage, terminalMessage) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, chainedMessage, terminalMessage); + } + function isTypeRelatedTo(source, target, relation) { + return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined); + } + function isSignatureAssignableTo(source, target) { + var sourceType = getOrCreateTypeFromSignature(source); + var targetType = getOrCreateTypeFromSignature(target); + return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined, undefined, undefined); + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return isPropertyIdenticalToRecursive(sourceProp, targetProp, false, function (s, t, _reportErrors) { return isTypeIdenticalTo(s, t); }); + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + if (!type.baseTypes.length || type.baseTypes.length === 1) { + return true; + } + var seen = {}; + ts.forEach(type.declaredProperties, function (p) { + seen[p.name] = { prop: p, containingType: type }; + }); + var ok = true; + for (var i = 0, len = type.baseTypes.length; i < len; ++i) { + var base = type.baseTypes[i]; + var properties = getPropertiesOfType(base); + for (var j = 0, proplen = properties.length; j < proplen; ++j) { + var prop = properties[j]; + if (!ts.hasProperty(seen, prop.name)) { + seen[prop.name] = { prop: prop, containingType: base }; + } + else { + var existing = seen[prop.name]; + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + 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); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); + } + } + } + } + return ok; + } + function isPropertyIdenticalToRecursive(sourceProp, targetProp, reportErrors, relate) { + ts.Debug.assert(sourceProp); + if (!targetProp) { + return false; + } + var sourcePropIsPrivate = getDeclarationFlagsFromSymbol(sourceProp) & 32 /* Private */; + var targetPropIsPrivate = getDeclarationFlagsFromSymbol(targetProp) & 32 /* Private */; + if (sourcePropIsPrivate !== targetPropIsPrivate) { + return false; + } + if (sourcePropIsPrivate) { + return (getTargetSymbol(sourceProp).parent === getTargetSymbol(targetProp).parent) && relate(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + } + else { + return isOptionalProperty(sourceProp) === isOptionalProperty(targetProp) && relate(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + } + } + function checkTypeRelatedTo(source, target, relation, errorNode, chainedMessage, terminalMessage) { + var errorInfo; + var sourceStack; + var targetStack; + var expandingFlags; + 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); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); + } + return result; + function reportError(message, arg0, arg1) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1); + } + function isRelatedTo(source, target, reportErrors) { + return isRelatedToWithCustomErrors(source, target, reportErrors, undefined, undefined); + } + function isRelatedToWithCustomErrors(source, target, reportErrors, chainedMessage, terminalMessage) { + if (relation === identityRelation) { + if (source === target) + return true; + } + else { + if (source === target) + return true; + if (target.flags & 1 /* Any */) + return true; + if (source === undefinedType) + return true; + if (source === nullType && target !== undefinedType) + return true; + if (source.flags & 128 /* Enum */ && target === numberType) + return true; + if (source.flags & 256 /* StringLiteral */ && target === stringType) + return true; + if (relation === assignableRelation) { + if (source.flags & 1 /* Any */) + return true; + if (source === numberType && target.flags & 128 /* Enum */) + return true; + } + } + if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { + if (typeParameterRelatedTo(source, target, reportErrors)) { + return true; + } + } + else { + var saveErrorInfo = errorInfo; + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + if (typesRelatedTo(source.typeArguments, target.typeArguments, reportErrors)) { + return true; + } + } + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; + var sourceOrApparentType = relation === identityRelation ? source : getApparentType(source); + if (sourceOrApparentType.flags & ts.TypeFlags.ObjectType && target.flags & ts.TypeFlags.ObjectType && objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors)) { + errorInfo = saveErrorInfo; + return true; + } + } + 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)); + } + return false; + } + function typesRelatedTo(sources, targets, reportErrors) { + for (var i = 0, len = sources.length; i < len; i++) { + if (!isRelatedTo(sources[i], targets[i], reportErrors)) + return false; + } + return true; + } + function typeParameterRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + if (source.symbol.name !== target.symbol.name) { + return false; + } + if (source.constraint === target.constraint) { + return true; + } + if (source.constraint === noConstraintType || target.constraint === noConstraintType) { + return false; + } + return isRelatedTo(source.constraint, target.constraint, reportErrors); + } + else { + while (true) { + var constraint = getConstraintOfTypeParameter(source); + if (constraint === target) + return true; + if (!(constraint && constraint.flags & 512 /* TypeParameter */)) + break; + source = constraint; + } + return false; + } + } + function objectTypeRelatedTo(source, target, reportErrors) { + if (overflow) + return false; + var result; + var id = source.id + "," + target.id; + if ((result = relation[id]) !== undefined) + return result; + if (depth > 0) { + for (var i = 0; i < depth; i++) { + if (source === sourceStack[i] && target === targetStack[i]) + return true; + } + if (depth === 100) { + overflow = true; + return false; + } + } + else { + sourceStack = []; + targetStack = []; + expandingFlags = 0; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) + expandingFlags |= 2; + result = expandingFlags === 3 || propertiesRelatedTo(source, target, reportErrors) && signaturesRelatedTo(source, target, 0 /* Call */, reportErrors) && signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors) && stringIndexTypesRelatedTo(source, target, reportErrors) && numberIndexTypesRelatedTo(source, target, reportErrors); + expandingFlags = saveExpandingFlags; + depth--; + if (depth === 0) { + relation[id] = result; + } + return result; + } + function isDeeplyNestedGeneric(type, stack) { + if (type.flags & 4096 /* Reference */ && depth >= 10) { + var target = type.target; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 4096 /* Reference */ && t.target === target) { + count++; + if (count >= 10) + return true; + } + } + } + return false; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesAreIdenticalTo(source, target, reportErrors); + } + else { + return propertiesAreSubtypeOrAssignableTo(source, target, reportErrors); + } + } + function propertiesAreIdenticalTo(source, target, reportErrors) { + if (source === target) { + return true; + } + var sourceProperties = getPropertiesOfType(source); + var targetProperties = getPropertiesOfType(target); + if (sourceProperties.length !== targetProperties.length) { + return false; + } + for (var i = 0, len = sourceProperties.length; i < len; ++i) { + var sourceProp = sourceProperties[i]; + var targetProp = getPropertyOfType(target, sourceProp.name); + if (!isPropertyIdenticalToRecursive(sourceProp, targetProp, reportErrors, isRelatedTo)) { + return false; + } + } + return true; + } + function propertiesAreSubtypeOrAssignableTo(source, target, reportErrors) { + var properties = getPropertiesOfType(target); + for (var i = 0; i < properties.length; i++) { + var targetProp = properties[i]; + var sourceProp = getPropertyOfApparentType(source, targetProp.name); + if (sourceProp === targetProp) { + continue; + } + var targetPropIsOptional = isOptionalProperty(targetProp); + if (!sourceProp) { + if (!targetPropIsOptional) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return false; + } + } + else if (sourceProp !== targetProp) { + if (targetProp.flags & 67108864 /* Prototype */) { + continue; + } + if (getDeclarationFlagsFromSymbol(sourceProp) & 32 /* Private */ || getDeclarationFlagsFromSymbol(targetProp) & 32 /* Private */) { + if (reportErrors) { + reportError(ts.Diagnostics.Private_property_0_cannot_be_reimplemented, symbolToString(targetProp)); + } + return false; + } + if (!isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible_Colon, symbolToString(targetProp)); + } + return false; + } + else if (isOptionalProperty(sourceProp) && !targetPropIsOptional) { + if (reportErrors) { + reportError(ts.Diagnostics.Required_property_0_cannot_be_reimplemented_with_optional_property_in_1, targetProp.name, typeToString(source)); + } + return false; + } + } + } + return true; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return areSignaturesIdenticalTo(source, target, kind, reportErrors); + } + else { + return areSignaturesSubtypeOrAssignableTo(source, target, kind, reportErrors); + } + } + function areSignaturesIdenticalTo(source, target, kind, reportErrors) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return false; + } + for (var i = 0, len = sourceSignatures.length; i < len; ++i) { + if (!isSignatureIdenticalTo(sourceSignatures[i], targetSignatures[i], reportErrors)) { + return false; + } + } + return true; + } + function isSignatureIdenticalTo(source, target, reportErrors) { + if (source === target) { + return true; + } + if (source.hasRestParameter !== target.hasRestParameter) { + return false; + } + if (source.parameters.length !== target.parameters.length) { + return false; + } + if (source.minArgumentCount !== target.minArgumentCount) { + return false; + } + if (source.typeParameters && target.typeParameters) { + if (source.typeParameters.length !== target.typeParameters.length) { + return false; + } + for (var i = 0, len = source.typeParameters.length; i < len; ++i) { + if (!isRelatedTo(source.typeParameters[i], target.typeParameters[i], reportErrors)) { + return false; + } + } + } + else if (source.typeParameters || source.typeParameters) { + return false; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + for (var i = 0, len = source.parameters.length; i < len; i++) { + var s = source.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); + var t = target.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); + if (!isRelatedTo(s, t, reportErrors)) { + return false; + } + } + var t = getReturnTypeOfSignature(target); + var s = getReturnTypeOfSignature(source); + return isRelatedTo(s, t, reportErrors); + } + function areSignaturesSubtypeOrAssignableTo(source, target, kind, reportErrors) { + if (target === anyFunctionType || source === anyFunctionType) + return true; + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var saveErrorInfo = errorInfo; + outer: for (var i = 0; i < targetSignatures.length; i++) { + var t = targetSignatures[i]; + if (!t.hasStringLiterals || target.flags & 16384 /* FromSignature */) { + var localErrors = reportErrors; + for (var j = 0; j < sourceSignatures.length; j++) { + var s = sourceSignatures[j]; + if (!s.hasStringLiterals || source.flags & 16384 /* FromSignature */) { + if (isSignatureSubtypeOrAssignableTo(s, t, localErrors)) { + errorInfo = saveErrorInfo; + continue outer; + } + localErrors = false; + } + } + return false; + } + } + return true; + } + function isSignatureSubtypeOrAssignableTo(source, target, reportErrors) { + if (source === target) { + return true; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return false; + } + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var checkCount; + if (source.hasRestParameter && target.hasRestParameter) { + checkCount = sourceMax > targetMax ? sourceMax : targetMax; + sourceMax--; + targetMax--; + } + else if (source.hasRestParameter) { + sourceMax--; + checkCount = targetMax; + } + else if (target.hasRestParameter) { + targetMax--; + checkCount = sourceMax; + } + else { + checkCount = sourceMax < targetMax ? sourceMax : targetMax; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var saveErrorInfo = errorInfo; + 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); + } + return false; + } + errorInfo = saveErrorInfo; + } + } + var t = getReturnTypeOfSignature(target); + if (t === voidType) + return true; + var s = getReturnTypeOfSignature(source); + return isRelatedTo(s, t, reportErrors); + } + function stringIndexTypesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return areIndexTypesIdenticalTo(0 /* String */, source, target, reportErrors); + } + else { + var targetType = getIndexTypeOfType(target, 0 /* String */); + if (targetType) { + var sourceType = getIndexTypeOfType(source, 0 /* String */); + if (!sourceType) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return false; + } + if (!isRelatedTo(sourceType, targetType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible_Colon); + } + return false; + } + } + return true; + } + } + function numberIndexTypesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return areIndexTypesIdenticalTo(1 /* Number */, source, target, reportErrors); + } + else { + var targetType = getIndexTypeOfType(target, 1 /* Number */); + if (targetType) { + var sourceStringType = getIndexTypeOfType(source, 0 /* String */); + var sourceNumberType = getIndexTypeOfType(source, 1 /* Number */); + if (!(sourceStringType || sourceNumberType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return false; + } + if (sourceStringType && sourceNumberType) { + var compatible = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); + } + else { + var compatible = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); + } + if (!compatible) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible_Colon); + } + return false; + } + } + return true; + } + } + function areIndexTypesIdenticalTo(indexKind, source, target, reportErrors) { + var targetType = getIndexTypeOfType(target, indexKind); + var sourceType = getIndexTypeOfType(source, indexKind); + return (!sourceType && !targetType) || (sourceType && targetType && isRelatedTo(sourceType, targetType, reportErrors)); + } + } + function isSupertypeOfEach(candidate, types) { + for (var i = 0, len = types.length; i < len; i++) { + if (candidate !== types[i] && !isTypeSubtypeOf(types[i], candidate)) + return false; + } + return true; + } + function getBestCommonType(types, contextualType, candidatesOnly) { + if (contextualType && isSupertypeOfEach(contextualType, types)) + return contextualType; + return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }) || (candidatesOnly ? undefined : emptyObjectType); + } + function isTypeOfObjectLiteral(type) { + return (type.flags & 8192 /* Anonymous */) && type.symbol && (type.symbol.flags & 1024 /* ObjectLiteral */) ? true : false; + } + function getWidenedTypeOfObjectLiteral(type) { + var properties = getPropertiesOfType(type); + if (properties.length) { + var widenedTypes = []; + var propTypeWasWidened = false; + ts.forEach(properties, function (p) { + var propType = getTypeOfSymbol(p); + var widenedType = getWidenedType(propType); + if (propType !== widenedType) { + propTypeWasWidened = true; + if (program.getCompilerOptions().noImplicitAny && getInnermostTypeOfNestedArrayTypes(widenedType) === anyType) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(widenedType)); + } + } + widenedTypes.push(widenedType); + }); + if (propTypeWasWidened) { + var members = {}; + var index = 0; + ts.forEach(properties, function (p) { + var symbol = createSymbol(2 /* Property */ | 33554432 /* Transient */, p.name); + symbol.declarations = p.declarations; + symbol.parent = p.parent; + symbol.type = widenedTypes[index++]; + if (p.valueDeclaration) + symbol.valueDeclaration = p.valueDeclaration; + members[symbol.name] = symbol; + }); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType) + stringIndexType = getWidenedType(stringIndexType); + if (numberIndexType) + numberIndexType = getWidenedType(numberIndexType); + type = createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + } + } + return type; + } + function isArrayType(type) { + return type.flags & 4096 /* Reference */ && type.target === globalArrayType; + } + function getInnermostTypeOfNestedArrayTypes(type) { + while (isArrayType(type)) { + type = type.typeArguments[0]; + } + return type; + } + function getWidenedTypeOfArrayLiteral(type) { + var elementType = type.typeArguments[0]; + var widenedType = getWidenedType(elementType); + type = elementType !== widenedType ? createArrayType(widenedType) : type; + return type; + } + function getWidenedType(type) { + if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { + return anyType; + } + if (isTypeOfObjectLiteral(type)) { + return getWidenedTypeOfObjectLiteral(type); + } + if (isArrayType(type)) { + return getWidenedTypeOfArrayLiteral(type); + } + return type; + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = sourceMax > targetMax ? sourceMax : targetMax; + sourceMax--; + targetMax--; + } + else if (source.hasRestParameter) { + sourceMax--; + count = targetMax; + } + else if (target.hasRestParameter) { + targetMax--; + count = sourceMax; + } + else { + count = sourceMax < targetMax ? sourceMax : targetMax; + } + for (var i = 0; i < count; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + callback(s, t); + } + } + function createInferenceContext(typeParameters) { + var inferences = []; + for (var i = 0; i < typeParameters.length; i++) + inferences.push([]); + return { + typeParameters: typeParameters, + inferences: inferences, + inferredTypes: new Array(typeParameters.length) + }; + } + function inferTypes(context, source, target) { + var sourceStack; + var targetStack; + var depth = 0; + inferFromTypes(source, target); + function isInProcess(source, target) { + for (var i = 0; i < depth; i++) { + if (source === sourceStack[i] && target === targetStack[i]) + return true; + } + return false; + } + function isWithinDepthLimit(type, stack) { + if (depth >= 5) { + var target = type.target; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 4096 /* Reference */ && t.target === target) + count++; + } + return count < 5; + } + return true; + } + function inferFromTypes(source, target) { + if (target.flags & 512 /* TypeParameter */) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (target === typeParameters[i]) { + var inferences = context.inferences[i]; + if (!ts.contains(inferences, source)) + inferences.push(source); + break; + } + } + } + else if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + var sourceTypes = source.typeArguments; + var targetTypes = target.typeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (source.flags & ts.TypeFlags.ObjectType && (target.flags & 4096 /* Reference */ || (target.flags & 8192 /* Anonymous */) && target.symbol && target.symbol.flags & (2048 /* Method */ | 512 /* TypeLiteral */))) { + if (!isInProcess(source, target) && isWithinDepthLimit(source, sourceStack) && isWithinDepthLimit(target, targetStack)) { + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); + inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); + inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); + depth--; + } + } + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfType(target); + for (var i = 0; i < properties.length; i++) { + var targetProp = properties[i]; + var sourceProp = getPropertyOfType(source, targetProp.name); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + function inferFromIndexTypes(source, target, sourceKind, targetKind) { + var targetIndexType = getIndexTypeOfType(target, targetKind); + if (targetIndexType) { + var sourceIndexType = getIndexTypeOfType(source, sourceKind); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetIndexType); + } + } + } + } + function getInferredType(context, index) { + var result = context.inferredTypes[index]; + if (!result) { + var commonType = getWidenedType(getBestCommonType(context.inferences[index])); + var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + var result = constraint && !isTypeAssignableTo(commonType, constraint) ? constraint : commonType; + context.inferredTypes[index] = result; + } + return result; + } + 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) { + return getAncestor(node, kind) !== undefined; + } + function getAncestor(node, kind) { + switch (kind) { + case 169 /* ClassDeclaration */: + while (node) { + switch (node.kind) { + case 169 /* ClassDeclaration */: + return node; + case 171 /* EnumDeclaration */: + case 170 /* InterfaceDeclaration */: + case 172 /* ModuleDeclaration */: + case 174 /* ImportDeclaration */: + return undefined; + default: + node = node.parent; + continue; + } + } + break; + default: + while (node) { + if (node.kind === kind) { + return node; + } + else { + node = node.parent; + } + } + break; + } + return undefined; + } + function checkIdentifier(node) { + function isInTypeQuery(node) { + while (node) { + switch (node.kind) { + case 124 /* TypeQuery */: + return true; + case 55 /* Identifier */: + case 112 /* QualifiedName */: + node = node.parent; + continue; + default: + return false; + } + } + ts.Debug.fail("should not get here"); + } + var symbol = resolveName(node, node.text, ts.SymbolFlags.Value | 524288 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, ts.identifierToString(node)); + if (!symbol) { + symbol = unknownSymbol; + } + if (symbol.flags & 4194304 /* Import */) { + getSymbolLinks(symbol).referenced = !isInTypeQuery(node); + } + getNodeLinks(node).resolvedSymbol = symbol; + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkCollisionWithIndexVariableInGeneratedCode(node, node); + return getTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol)); + } + function getThisContainer(node) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 172 /* ModuleDeclaration */: + case 115 /* Property */: + case 116 /* Method */: + case 117 /* Constructor */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 171 /* EnumDeclaration */: + case 177 /* SourceFile */: + case 137 /* ArrowFunction */: + return node; + } + } + } + function captureLexicalThis(node, container) { + var classNode = container.parent && container.parent.kind === 169 /* ClassDeclaration */ ? container.parent : undefined; + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 115 /* Property */ || container.kind === 117 /* Constructor */) { + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function checkThisExpression(node) { + var container = getThisContainer(node); + var needToCaptureLexicalThis = false; + while (container.kind === 137 /* ArrowFunction */) { + container = getThisContainer(container); + needToCaptureLexicalThis = true; + } + switch (container.kind) { + case 172 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_body); + break; + case 171 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + break; + case 117 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + } + break; + case 115 /* Property */: + if (container.flags & 64 /* Static */) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + } + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + var classNode = container.parent && container.parent.kind === 169 /* ClassDeclaration */ ? container.parent : undefined; + if (classNode) { + var symbol = getSymbolOfNode(classNode); + return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); + } + return anyType; + } + function getSuperContainer(node) { + while (true) { + node = node.parent; + if (!node) + return node; + switch (node.kind) { + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + case 115 /* Property */: + case 116 /* Method */: + case 117 /* Constructor */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + return node; + } + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + for (var n = node; n && n !== constructorDecl; n = n.parent) { + if (n.kind === 114 /* Parameter */) { + return true; + } + } + return false; + } + function checkSuperExpression(node, isCallExpression) { + var enclosingClass = getAncestor(node, 169 /* ClassDeclaration */); + var baseClass; + if (enclosingClass && enclosingClass.baseType) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); + baseClass = classType.baseTypes.length && classType.baseTypes[0]; + } + if (!baseClass) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + return unknownType; + } + var container = getSuperContainer(node); + if (container) { + var canUseSuperExpression = false; + if (isCallExpression) { + canUseSuperExpression = container.kind === 117 /* Constructor */; + } + else { + var needToCaptureLexicalThis = false; + while (container && container.kind === 137 /* ArrowFunction */) { + container = getSuperContainer(container); + needToCaptureLexicalThis = true; + } + if (container && container.parent && container.parent.kind === 169 /* ClassDeclaration */) { + if (container.flags & 64 /* Static */) { + canUseSuperExpression = container.kind === 116 /* Method */ || container.kind === 118 /* GetAccessor */ || container.kind === 119 /* SetAccessor */; + } + else { + canUseSuperExpression = container.kind === 116 /* Method */ || container.kind === 118 /* GetAccessor */ || container.kind === 119 /* SetAccessor */ || container.kind === 115 /* Property */ || container.kind === 117 /* Constructor */; + } + } + } + if (canUseSuperExpression) { + var returnType; + if ((container.flags & 64 /* Static */) || isCallExpression) { + getNodeLinks(node).flags |= 32 /* SuperStatic */; + returnType = getTypeOfSymbol(baseClass.symbol); + } + else { + getNodeLinks(node).flags |= 16 /* SuperInstance */; + returnType = baseClass; + } + if (container.kind === 117 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + returnType = unknownType; + } + if (!isCallExpression && needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + return returnType; + } + } + if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; + } + function isInferentialContext(mapper) { + return mapper && mapper !== identityMapper; + } + function checkArrayLiteral(node, contextualType, contextualMapper) { + var contextualElementType = contextualType && getIndexTypeOfType(contextualType, 1 /* Number */); + var elementTypes = []; + ts.forEach(node.elements, function (element) { + if (element.kind !== 142 /* OmittedExpression */) { + var type = checkExpression(element, contextualElementType, contextualMapper); + if (!ts.contains(elementTypes, type)) + elementTypes.push(type); + } + }); + var elementType = getBestCommonType(elementTypes, isInferentialContext(contextualMapper) ? undefined : contextualElementType, true); + if (!elementType) + elementType = elementTypes.length ? emptyObjectType : undefinedType; + return createArrayType(elementType); + } + function isNumericName(name) { + return !isNaN(name); + } + function getContextualTypeForProperty(type, name) { + var prop = getPropertyOfType(type, name); + if (prop) + return getTypeOfSymbol(prop); + return isNumericName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */); + } + function checkObjectLiteral(node, contextualType, contextualMapper) { + var members = node.symbol.members; + var properties = {}; + for (var id in members) { + if (ts.hasProperty(members, id)) { + var member = members[id]; + if (member.flags & 2 /* Property */) { + var contextualPropType = contextualType && getContextualTypeForProperty(contextualType, member.name); + var type = checkExpression(member.declarations[0].initializer, contextualPropType, contextualMapper); + var prop = createSymbol(2 /* Property */ | 33554432 /* Transient */, member.name); + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) + prop.valueDeclaration = member.valueDeclaration; + prop.type = type; + member = prop; + } + else { + var getAccessor = getDeclarationOfKind(member, 118 /* GetAccessor */); + if (getAccessor) { + checkAccessorDeclaration(getAccessor); + } + var setAccessor = getDeclarationOfKind(member, 119 /* SetAccessor */); + if (setAccessor) { + checkAccessorDeclaration(setAccessor); + } + } + properties[member.name] = member; + } + } + var stringIndexType = getIndexType(properties, 0 /* String */); + var numberIndexType = getIndexType(properties, 1 /* Number */); + return createAnonymousType(node.symbol, properties, emptyArray, emptyArray, stringIndexType, numberIndexType); + function getIndexType(properties, kind) { + if (contextualType) { + var indexType = getIndexTypeOfType(contextualType, kind); + if (indexType) { + var propTypes = []; + for (var id in properties) { + if (ts.hasProperty(properties, id)) { + if (kind === 0 /* String */ || isNumericName(id)) { + var type = getTypeOfSymbol(properties[id]); + if (!ts.contains(propTypes, type)) + propTypes.push(type); + } + } + } + return getBestCommonType(propTypes, isInferentialContext(contextualMapper) ? undefined : indexType); + } + } + } + } + function getDeclarationKindFromSymbol(s) { + return s.flags & 67108864 /* Prototype */ ? 115 /* Property */ : s.valueDeclaration.kind; + } + function getDeclarationFlagsFromSymbol(s) { + return s.flags & 67108864 /* Prototype */ ? 16 /* Public */ | 64 /* Static */ : s.valueDeclaration.flags; + } + function checkPropertyAccess(node) { + var type = checkExpression(node.left); + if (type === unknownType) + return type; + if (type !== anyType) { + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + return unknownType; + } + var prop = getPropertyOfApparentType(apparentType, node.right.text); + if (!prop) { + if (node.right.text) { + error(node.right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.identifierToString(node.right), typeToString(type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & 16 /* Class */) { + if (node.left.kind === 81 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 116 /* Method */) { + error(node.right, ts.Diagnostics.Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + else if (getDeclarationFlagsFromSymbol(prop) & 32 /* Private */) { + var classDeclaration = getAncestor(node, 169 /* ClassDeclaration */); + if (!classDeclaration || !ts.contains(prop.parent.declarations, classDeclaration)) { + error(node, ts.Diagnostics.Property_0_is_inaccessible, getFullyQualifiedName(prop)); + } + } + } + return getTypeOfSymbol(prop); + } + return anyType; + } + function checkIndexedAccess(node) { + var objectType = checkExpression(node.object); + var indexType = checkExpression(node.index); + if (objectType === unknownType) + return unknownType; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) { + return unknownType; + } + if (node.index.kind === 3 /* StringLiteral */ || node.index.kind === 2 /* NumericLiteral */) { + var name = node.index.text; + var prop = getPropertyOfApparentType(apparentType, name); + if (prop) { + return getTypeOfSymbol(prop); + } + } + if (indexType.flags & (1 /* Any */ | ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike)) { + if (indexType.flags & (1 /* Any */ | ts.TypeFlags.NumberLike)) { + var numberIndexType = getIndexTypeOfType(apparentType, 1 /* Number */); + if (numberIndexType) { + return numberIndexType; + } + } + var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); + if (stringIndexType) { + return stringIndexType; + } + if (program.getCompilerOptions().noImplicitAny && objectType !== anyType) { + error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + } + return anyType; + } + error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_or_any); + return unknownType; + } + function checkUntypedCall(node) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + return anyType; + } + function checkErrorCall(node) { + checkUntypedCall(node); + return unknownType; + } + function isCandidateSignature(node, signature) { + var args = node.arguments || emptyArray; + return args.length >= signature.minArgumentCount && (signature.hasRestParameter || args.length <= signature.parameters.length) && (!node.typeArguments || signature.typeParameters && node.typeArguments.length === signature.typeParameters.length); + } + function collectCandidates(node, signatures) { + var result = []; + var lastParent; + var pos; + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (isCandidateSignature(node, signature)) { + var parent = signature.declaration ? signature.declaration.parent : undefined; + if (lastParent && parent === lastParent) { + pos++; + } + else { + lastParent = parent; + pos = 0; + } + for (var j = result.length; j > pos; j--) { + result[j] = result[j - 1]; + } + result[pos] = signature; + } + } + return result; + } + function getSingleCallSignature(type) { + if (type.flags & ts.TypeFlags.ObjectType) { + var resolved = resolveObjectTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature.typeParameters); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + inferTypes(context, instantiateType(source, contextualMapper), target); + }); + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferentiallyTypeExpession(expr, contextualType, contextualMapper) { + var type = checkExpression(expr, contextualType, contextualMapper); + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualSignature = getSingleCallSignature(contextualType); + if (contextualSignature && !contextualSignature.typeParameters) { + type = getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper)); + } + } + return type; + } + function inferTypeArguments(signature, args, excludeArgument) { + var typeParameters = signature.typeParameters; + var context = createInferenceContext(typeParameters); + var mapper = createInferenceMapper(context); + for (var i = 0; i < args.length; i++) { + if (!excludeArgument || excludeArgument[i] === undefined) { + var parameterType = getTypeAtPosition(signature, i); + inferTypes(context, inferentiallyTypeExpession(args[i], parameterType, mapper), parameterType); + } + } + if (excludeArgument) { + for (var i = 0; i < args.length; i++) { + if (excludeArgument[i] === false) { + var parameterType = getTypeAtPosition(signature, i); + inferTypes(context, inferentiallyTypeExpession(args[i], parameterType, mapper), parameterType); + } + } + } + return getInferredTypes(context); + } + function checkTypeArguments(signature, typeArguments) { + var typeParameters = signature.typeParameters; + var result = []; + for (var i = 0; i < typeParameters.length; i++) { + var typeArgNode = typeArguments[i]; + var typeArgument = getTypeFromTypeNode(typeArgNode); + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + 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); + } + result.push(typeArgument); + } + return result; + } + function checkApplicableSignature(node, signature, relation, excludeArgument, reportErrors) { + if (node.arguments) { + for (var i = 0; i < node.arguments.length; i++) { + var arg = node.arguments[i]; + var paramType = getTypeAtPosition(signature, i); + var argType = arg.kind === 3 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) : checkExpression(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); + if (!isValidArgument) { + return false; + } + } + } + return true; + } + function checkCall(node, signatures) { + ts.forEach(node.typeArguments, checkSourceElement); + var candidates = collectCandidates(node, signatures); + if (!candidates.length) { + error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + return checkErrorCall(node); + } + var args = node.arguments || emptyArray; + var excludeArgument; + for (var i = 0; i < args.length; i++) { + if (isContextSensitiveExpression(args[i])) { + if (!excludeArgument) + excludeArgument = new Array(args.length); + excludeArgument[i] = true; + } + } + var relation = candidates.length === 1 ? assignableRelation : subtypeRelation; + while (true) { + for (var i = 0; i < candidates.length; i++) { + while (true) { + var candidate = candidates[i]; + if (candidate.typeParameters) { + var typeArguments = node.typeArguments ? checkTypeArguments(candidate, node.typeArguments) : inferTypeArguments(candidate, args, excludeArgument); + candidate = getSignatureInstantiation(candidate, typeArguments); + } + if (!checkApplicableSignature(node, candidate, relation, excludeArgument, false)) { + break; + } + var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; + if (index < 0) { + return getReturnTypeOfSignature(candidate); + } + excludeArgument[index] = false; + } + } + if (relation === assignableRelation) { + break; + } + relation = assignableRelation; + } + checkApplicableSignature(node, candidate, relation, undefined, true); + return checkErrorCall(node); + } + function checkCallExpression(node) { + if (node.func.kind === 81 /* SuperKeyword */) { + var superType = checkSuperExpression(node.func, true); + if (superType !== unknownType) { + checkCall(node, getSignaturesOfType(superType, 1 /* Construct */)); + } + else { + checkUntypedCall(node); + } + return voidType; + } + var funcType = checkExpression(node.func); + if (funcType === unknownType) { + return checkErrorCall(node); + } + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return checkErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if ((funcType === anyType) || (!callSignatures.length && !constructSignatures.length && isTypeAssignableTo(funcType, globalFunctionType))) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return checkUntypedCall(node); + } + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + } + return checkErrorCall(node); + } + return checkCall(node, callSignatures); + } + function checkNewExpression(node) { + var expressionType = checkExpression(node.func); + if (expressionType === unknownType) { + return checkErrorCall(node); + } + if (expressionType === anyType) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return checkUntypedCall(node); + } + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + return checkErrorCall(node); + } + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + return checkCall(node, constructSignatures); + } + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var type = checkCall(node, callSignatures); + if (type !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (program.getCompilerOptions().noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return checkErrorCall(node); + } + function checkTypeAssertion(node) { + var targetType = getTypeFromTypeNode(node.type); + if (targetType === unknownType) + return unknownType; + var exprType = checkExpression(node.operand, targetType); + var widenedType = getWidenedType(exprType); + if (!(isTypeAssignableTo(exprType, targetType) || isTypeAssignableTo(targetType, widenedType))) { + checkTypeAssignableTo(targetType, widenedType, 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); + } + return targetType; + } + function getContextualSignature(contextualType) { + if (contextualType) { + var signatures = getSignaturesOfType(contextualType, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!signature.typeParameters) { + return signature; + } + } + } + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? pos < signature.parameters.length - 1 ? getTypeOfSymbol(signature.parameters[pos]) : getRestTypeOfSignature(signature) : pos < signature.parameters.length ? getTypeOfSymbol(signature.parameters[pos]) : anyType; + } + function assignContextualParameterTypes(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = instantiateType(getTypeAtPosition(context, i), mapper); + } + } + if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { + var parameter = signature.parameters[signature.parameters.length - 1]; + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper); + } + } + } + function getReturnTypeFromBody(func, contextualType, contextualMapper) { + if (func.body.kind !== 168 /* FunctionBlock */) { + var unwidenedType = checkAndMarkExpression(func.body, contextualType, contextualMapper); + var widenedType = getWidenedType(unwidenedType); + if (program.getCompilerOptions().noImplicitAny && widenedType !== unwidenedType && getInnermostTypeOfNestedArrayTypes(widenedType) === anyType) { + error(func, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeToString(widenedType)); + } + return widenedType; + } + var types = checkAndAggregateReturnExpressionTypes(func.body, contextualType, contextualMapper); + if (types.length > 0) { + var commonType = getBestCommonType(types, undefined, true); + if (!commonType) { + error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + var widenedType = getWidenedType(commonType); + if (program.getCompilerOptions().noImplicitAny && widenedType !== commonType && getInnermostTypeOfNestedArrayTypes(widenedType) === anyType) { + var typeName = typeToString(widenedType); + if (func.name) { + error(func, ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type, ts.identifierToString(func.name), typeName); + } + else { + error(func, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeName); + } + } + return widenedType; + } + return voidType; + } + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 154 /* ReturnStatement */: + return visitor(node); + case 143 /* Block */: + case 168 /* FunctionBlock */: + case 147 /* IfStatement */: + case 148 /* DoStatement */: + case 149 /* WhileStatement */: + case 150 /* ForStatement */: + case 151 /* ForInStatement */: + case 155 /* WithStatement */: + case 156 /* SwitchStatement */: + case 157 /* CaseClause */: + case 158 /* DefaultClause */: + case 159 /* LabelledStatement */: + case 161 /* TryStatement */: + case 162 /* TryBlock */: + case 163 /* CatchBlock */: + case 164 /* FinallyBlock */: + return ts.forEachChild(node, traverse); + } + } + } + function checkAndAggregateReturnExpressionTypes(body, contextualType, contextualMapper) { + var aggregatedTypes = []; + forEachReturnStatement(body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkAndMarkExpression(expr, contextualType, contextualMapper); + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function bodyContainsAReturnStatement(funcBody) { + return forEachReturnStatement(funcBody, function (returnStatement) { + return true; + }); + } + function bodyContainsSingleThrowStatement(body) { + return (body.statements.length === 1) && (body.statements[0].kind === 160 /* ThrowStatement */); + } + function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { + if (returnType === voidType || returnType === anyType) { + return; + } + if (!func.body || func.body.kind !== 168 /* FunctionBlock */) { + return; + } + var bodyBlock = func.body; + if (bodyContainsAReturnStatement(bodyBlock)) { + return; + } + if (bodyContainsSingleThrowStatement(bodyBlock)) { + return; + } + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); + } + function checkFunctionExpression(node, contextualType, contextualMapper) { + if (contextualMapper === identityMapper) { + return anyFunctionType; + } + var type = getTypeOfSymbol(node.symbol); + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + var contextualSignature = getContextualSignature(contextualType); + if (contextualSignature) { + if (!node.typeParameters && !ts.forEach(node.parameters, function (p) { return p.type; })) { + assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); + } + if (!node.type) { + signature.resolvedReturnType = resolvingType; + var returnType = getReturnTypeFromBody(node, getReturnTypeOfSignature(contextualSignature), contextualMapper); + if (signature.resolvedReturnType === resolvingType) { + signature.resolvedReturnType = returnType; + } + } + else { + checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); + } + } + checkSignatureDeclaration(node); + if (node.body.kind === 168 /* FunctionBlock */) { + checkSourceElement(node.body); + } + else { + var returnType = getReturnTypeOfSignature(signature); + if (node.type) { + checkTypeAssignableTo(checkExpression(node.body, returnType), returnType, node.body, undefined, undefined); + } + } + links.flags |= 1 /* TypeChecked */; + } + return type; + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!(type.flags & (1 /* Any */ | ts.TypeFlags.NumberLike))) { + error(operand, diagnostic); + return false; + } + return true; + } + function checkReferenceExpression(n, message) { + function findSymbol(n) { + var symbol = getNodeLinks(n).resolvedSymbol; + return symbol && getExportSymbolOfValueSymbolIfExported(symbol); + } + function isReferenceOrErrorExpression(n) { + switch (n.kind) { + case 55 /* Identifier */: + var symbol = findSymbol(n); + return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 1 /* Variable */) !== 0; + case 130 /* PropertyAccess */: + var symbol = findSymbol(n); + return !symbol || symbol === unknownSymbol || (symbol.flags & ~4 /* EnumMember */) !== 0; + case 131 /* IndexedAccess */: + return true; + case 135 /* ParenExpression */: + return isReferenceOrErrorExpression(n.expression); + default: + return false; + } + } + if (!isReferenceOrErrorExpression(n)) { + error(n, message); + return false; + } + return true; + } + function checkPrefixExpression(node) { + var operandType = checkExpression(node.operand); + switch (node.operator) { + case 24 /* PlusToken */: + case 25 /* MinusToken */: + case 38 /* TildeToken */: + return numberType; + case 37 /* ExclamationToken */: + case 64 /* DeleteKeyword */: + return booleanType; + case 87 /* TypeOfKeyword */: + return stringType; + case 89 /* VoidKeyword */: + return undefinedType; + case 29 /* PlusPlusToken */: + case 30 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer); + } + return numberType; + } + return unknownType; + } + function checkPostfixExpression(node) { + var operandType = checkExpression(node.operand); + var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer); + } + return numberType; + } + function isTypeAnyTypeObjectTypeOrTypeParameter(type) { + return type === anyType || ((type.flags & (ts.TypeFlags.ObjectType | 512 /* TypeParameter */)) !== 0); + } + function checkInstanceOfExpression(node, leftType, rightType) { + if (!isTypeAnyTypeObjectTypeOrTypeParameter(leftType)) { + error(node.left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + if (rightType !== anyType && !isTypeSubtypeOf(rightType, globalFunctionType)) { + error(node.right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(node, leftType, rightType) { + if (leftType !== anyType && leftType !== stringType && leftType !== numberType) { + error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number); + } + if (!isTypeAnyTypeObjectTypeOrTypeParameter(rightType)) { + error(node.right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkBinaryExpression(node, contextualType, contextualMapper) { + var operator = node.operator; + var leftContextualType = operator === 40 /* BarBarToken */ ? contextualType : undefined; + var leftType = checkExpression(node.left, leftContextualType, contextualMapper); + var rightContextualType = operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment ? leftType : operator === 40 /* BarBarToken */ ? contextualType || leftType : undefined; + var rightType = checkExpression(node.right, rightContextualType, contextualMapper); + switch (operator) { + case 26 /* AsteriskToken */: + case 46 /* AsteriskEqualsToken */: + case 27 /* SlashToken */: + case 47 /* SlashEqualsToken */: + case 28 /* PercentToken */: + case 48 /* PercentEqualsToken */: + case 25 /* MinusToken */: + case 45 /* MinusEqualsToken */: + case 31 /* LessThanLessThanToken */: + case 49 /* LessThanLessThanEqualsToken */: + case 32 /* GreaterThanGreaterThanToken */: + case 50 /* GreaterThanGreaterThanEqualsToken */: + case 33 /* GreaterThanGreaterThanGreaterThanToken */: + case 51 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 35 /* BarToken */: + case 53 /* BarEqualsToken */: + case 36 /* CaretToken */: + case 54 /* CaretEqualsToken */: + case 34 /* AmpersandToken */: + case 52 /* AmpersandEqualsToken */: + if (leftType.flags & (32 /* Undefined */ | 64 /* Null */)) + leftType = rightType; + if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) + rightType = leftType; + var leftOk = checkArithmeticOperandType(node.left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(node.right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + return numberType; + case 24 /* PlusToken */: + case 44 /* PlusEqualsToken */: + if (leftType.flags & (32 /* Undefined */ | 64 /* Null */)) + leftType = rightType; + if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) + rightType = leftType; + var resultType; + if (leftType.flags & ts.TypeFlags.NumberLike && rightType.flags & ts.TypeFlags.NumberLike) { + resultType = numberType; + } + else if (leftType.flags & ts.TypeFlags.StringLike || rightType.flags & ts.TypeFlags.StringLike) { + resultType = stringType; + } + else if (leftType.flags & 1 /* Any */ || leftType === unknownType || rightType.flags & 1 /* Any */ || rightType === unknownType) { + resultType = anyType; + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 44 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 19 /* EqualsEqualsToken */: + case 20 /* ExclamationEqualsToken */: + case 21 /* EqualsEqualsEqualsToken */: + case 22 /* ExclamationEqualsEqualsToken */: + case 15 /* LessThanToken */: + case 16 /* GreaterThanToken */: + case 17 /* LessThanEqualsToken */: + case 18 /* GreaterThanEqualsToken */: + if (!isTypeSubtypeOf(leftType, rightType) && !isTypeSubtypeOf(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 77 /* InstanceOfKeyword */: + return checkInstanceOfExpression(node, leftType, rightType); + case 76 /* InKeyword */: + return checkInExpression(node, leftType, rightType); + case 39 /* AmpersandAmpersandToken */: + return rightType; + case 40 /* BarBarToken */: + return getBestCommonType([leftType, rightType], isInferentialContext(contextualMapper) ? undefined : contextualType); + case 43 /* EqualsToken */: + checkAssignmentOperator(rightType); + return rightType; + case 14 /* CommaToken */: + return rightType; + } + function checkAssignmentOperator(valueType) { + if (operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment) { + var ok = checkReferenceExpression(node.left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression); + if (ok) { + checkTypeAssignableTo(valueType, leftType, node.left, undefined, undefined); + } + } + } + function reportOperatorError() { + error(node, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(node.operator), typeToString(leftType), typeToString(rightType)); + } + } + function checkConditionalExpression(node, contextualType, contextualMapper) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, contextualType, contextualMapper); + var type2 = checkExpression(node.whenFalse, contextualType, contextualMapper); + var resultType = getBestCommonType([type1, type2], isInferentialContext(contextualMapper) ? undefined : contextualType, true); + if (!resultType) { + if (contextualType && !isInferentialContext(contextualMapper)) { + error(node, ts.Diagnostics.No_best_common_type_exists_between_0_1_and_2, typeToString(contextualType), typeToString(type1), typeToString(type2)); + } + else { + error(node, ts.Diagnostics.No_best_common_type_exists_between_0_and_1, typeToString(type1), typeToString(type2)); + } + resultType = emptyObjectType; + } + return resultType; + } + function checkAndMarkExpression(node, contextualType, contextualMapper) { + var result = checkExpression(node, contextualType, contextualMapper); + getNodeLinks(node).flags |= 1 /* TypeChecked */; + return result; + } + function checkExpression(node, contextualType, contextualMapper) { + switch (node.kind) { + case 55 /* Identifier */: + return checkIdentifier(node); + case 83 /* ThisKeyword */: + return checkThisExpression(node); + case 81 /* SuperKeyword */: + return checkSuperExpression(node, false); + case 79 /* NullKeyword */: + return nullType; + case 85 /* TrueKeyword */: + case 70 /* FalseKeyword */: + return booleanType; + case 2 /* NumericLiteral */: + return numberType; + case 3 /* StringLiteral */: + return stringType; + case 4 /* RegularExpressionLiteral */: + return globalRegExpType; + case 112 /* QualifiedName */: + return checkPropertyAccess(node); + case 127 /* ArrayLiteral */: + return checkArrayLiteral(node, contextualType, contextualMapper); + case 128 /* ObjectLiteral */: + return checkObjectLiteral(node, contextualType, contextualMapper); + case 130 /* PropertyAccess */: + return checkPropertyAccess(node); + case 131 /* IndexedAccess */: + return checkIndexedAccess(node); + case 132 /* CallExpression */: + return checkCallExpression(node); + case 133 /* NewExpression */: + return checkNewExpression(node); + case 134 /* TypeAssertion */: + return checkTypeAssertion(node); + case 135 /* ParenExpression */: + return checkExpression(node.expression); + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + return checkFunctionExpression(node, contextualType, contextualMapper); + case 138 /* PrefixOperator */: + return checkPrefixExpression(node); + case 139 /* PostfixOperator */: + return checkPostfixExpression(node); + case 140 /* BinaryExpression */: + return checkBinaryExpression(node, contextualType, contextualMapper); + case 141 /* ConditionalExpression */: + return checkConditionalExpression(node, contextualType, contextualMapper); + } + return unknownType; + } + function checkTypeParameter(node) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + checkSourceElement(node.constraint); + checkTypeParameterHasIllegalReferencesInConstraint(node); + } + function checkParameter(parameterDeclaration) { + checkVariableDeclaration(parameterDeclaration); + checkCollisionWithIndexVariableInGeneratedCode(parameterDeclaration, parameterDeclaration.name); + if (parameterDeclaration.flags & (16 /* Public */ | 32 /* Private */) && !(parameterDeclaration.parent.kind === 117 /* Constructor */ && parameterDeclaration.parent.body)) { + error(parameterDeclaration, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + if (parameterDeclaration.flags & 8 /* Rest */) { + if (!isArrayType(getTypeOfSymbol(parameterDeclaration.symbol))) { + error(parameterDeclaration, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + else { + if (parameterDeclaration.initializer && !parameterDeclaration.parent.body) { + error(parameterDeclaration, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + } + } + function checkReferencesInInitializer(n) { + if (n.kind === 55 /* Identifier */) { + var referencedSymbol = getNodeLinks(n).resolvedSymbol; + if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(parameterDeclaration.parent.locals, referencedSymbol.name, ts.SymbolFlags.Value) === referencedSymbol) { + if (referencedSymbol.valueDeclaration.kind === 114 /* Parameter */) { + if (referencedSymbol.valueDeclaration === parameterDeclaration) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.identifierToString(parameterDeclaration.name)); + return; + } + var enclosingOrReferencedParameter = ts.forEach(parameterDeclaration.parent.parameters, function (p) { return p === parameterDeclaration || p === referencedSymbol.valueDeclaration ? p : undefined; }); + if (enclosingOrReferencedParameter === referencedSymbol.valueDeclaration) { + return; + } + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.identifierToString(parameterDeclaration.name), ts.identifierToString(n)); + } + } + else { + ts.forEachChild(n, checkReferencesInInitializer); + } + } + if (parameterDeclaration.initializer) { + checkReferencesInInitializer(parameterDeclaration.initializer); + } + } + function checkSignatureDeclaration(node) { + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + if (node.type) { + checkSourceElement(node.type); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithArgumentsInGeneratedCode(node); + if (program.getCompilerOptions().noImplicitAny && !node.type) { + switch (node.kind) { + case 121 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 120 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + checkSpecializedSignatureDeclaration(node); + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 170 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var i = 0, len = indexSymbol.declarations.length; i < len; ++i) { + var declaration = indexSymbol.declarations[i]; + if (declaration.parameters.length == 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 110 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 108 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + checkVariableDeclaration(node); + } + function checkMethodDeclaration(node) { + checkFunctionDeclaration(node); + } + function checkConstructorDeclaration(node) { + checkSignatureDeclaration(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = getDeclarationOfKind(symbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + if (!node.body) { + return; + } + function isSuperCallExpression(n) { + return n.kind === 132 /* CallExpression */ && n.func.kind === 81 /* SuperKeyword */; + } + function containsSuperCall(n) { + if (isSuperCallExpression(n)) { + return true; + } + switch (n.kind) { + case 136 /* FunctionExpression */: + case 167 /* FunctionDeclaration */: + case 137 /* ArrowFunction */: + case 128 /* ObjectLiteral */: + return false; + default: + return ts.forEachChild(n, containsSuperCall); + } + } + function markThisReferencesAsErrors(n) { + if (n.kind === 83 /* ThisKeyword */) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 136 /* FunctionExpression */ && n.kind !== 167 /* FunctionDeclaration */) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 115 /* Property */ && !(n.flags & 64 /* Static */) && !!n.initializer; + } + if (node.parent.baseType) { + if (containsSuperCall(node.body)) { + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */); }); + if (superCallShouldBeFirst) { + var statements = node.body.statements; + if (!statements.length || statements[0].kind !== 146 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + else { + markThisReferencesAsErrors(statements[0].expression); + } + } + } + else { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (node.kind === 118 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && node.body && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + } + } + var otherKind = node.kind === 118 /* GetAccessor */ ? 119 /* SetAccessor */ : 118 /* GetAccessor */; + var otherAccessor = getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + var visibilityFlags = 32 /* Private */ | 16 /* Public */; + if (((node.flags & visibilityFlags) !== (otherAccessor.flags & visibilityFlags))) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + var thisType = getAnnotatedAccessorType(node); + var otherType = getAnnotatedAccessorType(otherAccessor); + if (thisType && otherType) { + if (!isTypeIdenticalTo(thisType, otherType)) { + error(node, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + } + } + } + checkFunctionDeclaration(node); + checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); + } + function checkTypeReference(node) { + var type = getTypeFromTypeReferenceNode(node); + if (type !== unknownType && node.typeArguments) { + var len = node.typeArguments.length; + for (var i = 0; i < len; i++) { + checkSourceElement(node.typeArguments[i]); + var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); + if (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); + } + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + var type = getTypeFromTypeLiteralNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + function checkArrayType(node) { + getTypeFromArrayTypeNode(node); + } + function isPrivateWithinAmbient(node) { + return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); + } + function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { + var signature = getSignatureFromDeclaration(signatureDeclarationNode); + if (!signature.hasStringLiterals) { + return; + } + if (signatureDeclarationNode.body) { + error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); + return; + } + var signaturesOfSymbol = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); + for (var i = 0; i < signaturesOfSymbol.length; i++) { + var otherSignature = signaturesOfSymbol[i]; + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + return; + } + } + error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = n.flags; + if (n.parent.kind !== 170 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { + if (!(flags & 2 /* Ambient */)) { + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + var canonicalFlags = implementationSharesContainerWithFirstOverload ? getEffectiveDeclarationFlags(implementation, flagsToCheck) : getEffectiveDeclarationFlags(overloads[0], flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; + if (deviation & 1 /* Export */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + } + else if (deviation & 2 /* Ambient */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & 32 /* Private */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_or_private); + } + else if (deviation & 4 /* QuestionMark */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 32 /* Private */ | 4 /* QuestionMark */; + var someNodeFlags = 0; + var allNodeFlags = flagsToCheck; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 4096 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode) { + if (subsequentNode.kind === node.kind) { + var errorNode = subsequentNode.name || subsequentNode; + if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { + ts.Debug.assert(node.kind === 116 /* Method */); + ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode, diagnostic); + return; + } + else if (subsequentNode.body) { + error(errorNode, ts.Diagnostics.Function_implementation_name_must_be_0, ts.identifierToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & ts.SymbolFlags.Module; + for (var i = 0; i < declarations.length; i++) { + var node = declarations[i]; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 170 /* InterfaceDeclaration */ || node.parent.kind === 125 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } + if (node.kind === 167 /* FunctionDeclaration */ || node.kind === 116 /* Method */ || node.kind === 117 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + if (node.body && bodyDeclaration) { + if (isConstructor) { + error(node, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + } + else { + error(node, ts.Diagnostics.Duplicate_function_implementation); + } + } + else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (node.body) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + if (!bodySignature.hasStringLiterals) { + for (var i = 0, len = signatures.length; i < len; ++i) { + if (!signatures[i].hasStringLiterals && !isSignatureAssignableTo(bodySignature, signatures[i])) { + error(signatures[i].declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + var symbol; + var symbol = node.localSymbol; + if (!symbol) { + symbol = getSymbolOfNode(node); + if (!(symbol.flags & ts.SymbolFlags.Export)) { + return; + } + } + if (getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0; + var nonExportedDeclarationSpaces = 0; + ts.forEach(symbol.declarations, function (d) { + var declarationSpaces = getDeclarationSpaces(d); + if (getEffectiveDeclarationFlags(d, 1 /* Export */)) { + exportedDeclarationSpaces |= declarationSpaces; + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + }); + var commonDeclarationSpace = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + if (commonDeclarationSpace) { + ts.forEach(symbol.declarations, function (d) { + if (getDeclarationSpaces(d) & commonDeclarationSpace) { + error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.identifierToString(d.name)); + } + }); + } + function getDeclarationSpaces(d) { + switch (d.kind) { + case 170 /* InterfaceDeclaration */: + return 1048576 /* ExportType */; + case 172 /* ModuleDeclaration */: + return d.name.kind === 3 /* StringLiteral */ || ts.isInstantiated(d) ? 2097152 /* ExportNamespace */ | 524288 /* ExportValue */ : 2097152 /* ExportNamespace */; + case 169 /* ClassDeclaration */: + case 171 /* EnumDeclaration */: + return 1048576 /* ExportType */ | 524288 /* ExportValue */; + case 174 /* ImportDeclaration */: + var result = 0; + var target = resolveImport(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { + result |= getDeclarationSpaces(d); + }); + return result; + default: + return 524288 /* ExportValue */; + } + } + } + function checkFunctionDeclaration(node) { + checkSignatureDeclaration(node); + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + var firstDeclaration = getDeclarationOfKind(localSymbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + if (getDeclarationOfKind(symbol, node.kind) === node) { + checkFunctionOrConstructorSymbol(symbol); + } + } + checkSourceElement(node.body); + if (node.type && !isAccessor(node.kind)) { + checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); + } + if (program.getCompilerOptions().noImplicitAny && !node.body && !node.type) { + if (!isPrivateWithinAmbient(node)) { + var typeName = typeToString(anyType); + if (node.name) { + error(node, ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type, ts.identifierToString(node.name), typeName); + } + else { + error(node, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeName); + } + } + } + } + function checkBlock(node) { + ts.forEach(node.statements, checkSourceElement); + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || !node.body) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && p.name.text === argumentsSymbol.name) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function checkCollisionWithIndexVariableInGeneratedCode(node, name) { + if (!(name && name.text === "_i")) { + return; + } + if (node.kind === 114 /* Parameter */) { + if (node.parent.body && ts.hasRestParameters(node.parent) && !ts.isInAmbientContext(node)) { + error(node, ts.Diagnostics.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter); + } + return; + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol === unknownSymbol) { + return; + } + var current = node; + while (current) { + var definedOnCurrentLevel = ts.forEach(symbol.declarations, function (d) { return d.parent === current ? d : undefined; }); + if (definedOnCurrentLevel) { + return; + } + switch (current.kind) { + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 116 /* Method */: + case 137 /* ArrowFunction */: + case 117 /* Constructor */: + if (ts.hasRestParameters(current)) { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter); + return; + } + break; + } + current = current.parent; + } + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.text === name)) { + return false; + } + if (node.kind === 115 /* Property */ || node.kind === 116 /* Method */ || node.kind === 118 /* GetAccessor */ || node.kind === 119 /* SetAccessor */) { + return false; + } + if (ts.isInAmbientContext(node)) { + return false; + } + if (node.kind === 114 /* Parameter */ && !node.parent.body) { + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_this")) { + return; + } + potentialThisCollisions.push(node); + } + function checkIfThisIsCapturedInEnclosingScope(node) { + var current = node; + while (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration = node.kind !== 55 /* Identifier */; + if (isDeclaration) { + error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return; + } + current = current.parent; + } + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + var enclosingClass = getAncestor(node, 169 /* ClassDeclaration */); + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (enclosingClass.baseType) { + var isDeclaration = node.kind !== 55 /* Identifier */; + if (isDeclaration) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkVariableDeclaration(node) { + checkSourceElement(node.type); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var typeOfValueDeclaration = getTypeOfVariableOrParameterOrProperty(symbol); + var type; + var useTypeFromValueDeclaration = node === symbol.valueDeclaration; + if (useTypeFromValueDeclaration) { + type = typeOfValueDeclaration; + } + else { + type = getTypeOfVariableDeclaration(node); + } + if (node.initializer) { + if (!(getNodeLinks(node.initializer).flags & 1 /* TypeChecked */)) { + checkTypeAssignableTo(checkAndMarkExpression(node.initializer, type), type, node, undefined, undefined); + } + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + if (!useTypeFromValueDeclaration) { + if (typeOfValueDeclaration !== unknownType && type !== unknownType && !isTypeIdenticalTo(typeOfValueDeclaration, type)) { + error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.identifierToString(node.name), typeToString(typeOfValueDeclaration), typeToString(type)); + } + } + } + function checkVariableStatement(node) { + ts.forEach(node.declarations, checkVariableDeclaration); + } + function checkExpressionStatement(node) { + checkExpression(node.expression); + } + function checkIfStatement(node) { + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + if (node.declarations) + ts.forEach(node.declarations, checkVariableDeclaration); + if (node.initializer) + checkExpression(node.initializer); + if (node.condition) + checkExpression(node.condition); + if (node.iterator) + checkExpression(node.iterator); + checkSourceElement(node.statement); + } + function checkForInStatement(node) { + if (node.declaration) { + checkVariableDeclaration(node.declaration); + if (node.declaration.type) { + error(node.declaration, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation); + } + } + if (node.variable) { + var exprType = checkExpression(node.variable); + if (exprType !== anyType && exprType !== stringType) { + error(node.variable, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + checkReferenceExpression(node.variable, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement); + } + } + var exprType = checkExpression(node.expression); + if (!isTypeAnyTypeObjectTypeOrTypeParameter(exprType) && exprType !== unknownType) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + } + function checkBreakOrContinueStatement(node) { + } + function getContainingFunction(node) { + while (true) { + node = node.parent; + if (!node || node.kind === 167 /* FunctionDeclaration */ || node.kind === 136 /* FunctionExpression */ || node.kind === 137 /* ArrowFunction */ || node.kind === 116 /* Method */ || node.kind === 117 /* Constructor */ || node.kind === 118 /* GetAccessor */ || node.kind === 119 /* SetAccessor */) { + return node; + } + } + } + function checkReturnStatement(node) { + if (node.expression && !(getNodeLinks(node.expression).flags & 1 /* TypeChecked */)) { + var func = getContainingFunction(node); + if (func) { + if (func.kind === 119 /* SetAccessor */) { + if (node.expression) { + error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else { + var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + var checkAssignability = func.type || (func.kind === 118 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(func.symbol, 119 /* SetAccessor */))); + if (checkAssignability) { + checkTypeAssignableTo(checkExpression(node.expression, returnType), returnType, node.expression, undefined, undefined); + } + else if (func.kind == 117 /* Constructor */) { + if (!isTypeAssignableTo(checkExpression(node.expression, returnType), returnType)) { + error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + } + } + } + } + function checkWithStatement(node) { + checkExpression(node.expression); + error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + } + function checkSwitchStatement(node) { + var expressionType = checkExpression(node.expression); + ts.forEach(node.clauses, function (clause) { + if (clause.expression) { + var caseType = checkExpression(clause.expression); + if (!isTypeAssignableTo(expressionType, caseType)) { + checkTypeAssignableTo(caseType, expressionType, clause.expression, undefined, undefined); + } + } + checkBlock(clause); + }); + } + function checkLabelledStatement(node) { + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + checkExpression(node.expression); + } + function checkTryStatement(node) { + checkBlock(node.tryBlock); + if (node.catchBlock) + checkBlock(node.catchBlock); + if (node.finallyBlock) + checkBlock(node.finallyBlock); + } + function checkIndexConstraints(type) { + function checkIndexConstraintForProperty(prop, propertyType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + if (indexKind === 1 /* Number */ && !isNumericName(prop.name)) { + return; + } + var errorNode; + if (prop.parent === type.symbol) { + errorNode = prop.valueDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (type.flags & 2048 /* Interface */) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(type.baseTypes, function (base) { return getPropertyOfType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : type.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + if (!errorNode && (type.flags & 2048 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(type.baseTypes, function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + } + function checkTypeNameIsReserved(name, message) { + switch (name.text) { + case "any": + case "number": + case "boolean": + case "string": + case "void": + error(name, message, name.text); + } + } + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.identifierToString(node.name)); + } + } + } + } + } + function checkClassDeclaration(node) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkCollisionWithCapturedThisVariable(node, node.name); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var staticType = getTypeOfSymbol(symbol); + if (node.baseType) { + emitExtends = emitExtends || !ts.isInAmbientContext(node); + checkTypeReference(node.baseType); + } + if (type.baseTypes.length) { + 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); + 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); + 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)); + } + checkExpression(node.baseType.typeName); + checkKindsOfPropertyMemberOverrides(type, baseType); + } + if (node.implementedTypes) { + ts.forEach(node.implementedTypes, function (typeRefNode) { + checkTypeReference(typeRefNode); + var t = getTypeFromTypeReferenceNode(typeRefNode); + 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); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + }); + } + checkIndexConstraints(type); + ts.forEach(node.members, checkSourceElement); + checkTypeForDuplicateIndexSignatures(node); + } + function getTargetSymbol(s) { + return s.flags & 8388608 /* Instantiated */ ? getSymbolLinks(s).target : s; + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + var baseProperties = getPropertiesOfType(baseType); + for (var i = 0, len = baseProperties.length; i < len; ++i) { + var base = getTargetSymbol(baseProperties[i]); + if (base.flags & 67108864 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfType(type, base.name)); + if (derived) { + var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + if ((baseDeclarationFlags & 32 /* Private */) || (derivedDeclarationFlags & 32 /* Private */)) { + continue; + } + if ((baseDeclarationFlags & 64 /* Static */) !== (derivedDeclarationFlags & 64 /* Static */)) { + continue; + } + if ((base.flags & derived.flags & 2048 /* Method */) || ((base.flags & ts.SymbolFlags.PropertyOrAccessor) && (derived.flags & ts.SymbolFlags.PropertyOrAccessor))) { + continue; + } + var errorMessage; + if (base.flags & 2048 /* Method */) { + if (derived.flags & ts.SymbolFlags.Accessor) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + ts.Debug.assert(derived.flags & 2 /* Property */); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 2 /* Property */) { + ts.Debug.assert(derived.flags & 2048 /* Method */); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + ts.Debug.assert(base.flags & ts.SymbolFlags.Accessor); + ts.Debug.assert(derived.flags & 2048 /* Method */); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(derived.valueDeclaration.name, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + function isAccessor(kind) { + return kind === 118 /* GetAccessor */ || kind === 119 /* SetAccessor */; + } + function areTypeParametersIdentical(list1, list2) { + if (!list1 && !list2) { + return true; + } + if (!list1 || !list2 || list1.length !== list2.length) { + return false; + } + for (var i = 0, len = list1.length; i < len; i++) { + var tp1 = list1[i]; + var tp2 = list2[i]; + if (tp1.name.text !== tp2.name.text) { + return false; + } + if (!tp1.constraint && !tp2.constraint) { + continue; + } + if (!tp1.constraint || !tp2.constraint) { + return false; + } + if (!isTypeIdenticalTo(getTypeFromTypeNode(tp1.constraint), getTypeFromTypeNode(tp2.constraint))) { + return false; + } + } + return true; + } + function checkInterfaceDeclaration(node) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var firstInterfaceDecl = getDeclarationOfKind(symbol, 170 /* InterfaceDeclaration */); + if (symbol.declarations.length > 1) { + if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { + error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + } + if (node === firstInterfaceDecl) { + 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); + }); + checkIndexConstraints(type); + } + } + ts.forEach(node.baseTypes, checkTypeReference); + ts.forEach(node.members, checkSourceElement); + checkTypeForDuplicateIndexSignatures(node); + } + function getConstantValue(node) { + var isNegative = false; + if (node.kind === 138 /* PrefixOperator */) { + var unaryExpression = node; + if (unaryExpression.operator === 25 /* MinusToken */ || unaryExpression.operator === 24 /* PlusToken */) { + node = unaryExpression.operand; + isNegative = unaryExpression.operator === 25 /* MinusToken */; + } + } + if (node.kind === 2 /* NumericLiteral */) { + var literalText = node.text; + return isNegative ? -literalText : +literalText; + } + return undefined; + } + function checkEnumDeclaration(node) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkExportsOnMergedDeclarations(node); + var enumSymbol = getSymbolOfNode(node); + var enumType = getDeclaredTypeOfSymbol(enumSymbol); + var autoValue = 0; + var ambient = ts.isInAmbientContext(node); + ts.forEach(node.members, function (member) { + var initializer = member.initializer; + if (initializer) { + autoValue = getConstantValue(initializer); + if (autoValue === undefined && !ambient) { + checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, undefined, undefined); + } + } + else if (ambient) { + autoValue = undefined; + } + if (autoValue !== undefined) { + getNodeLinks(member).enumMemberValue = autoValue++; + } + }); + var firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + var seenEnumMissingInitialInitializer = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + if (declaration.kind !== 171 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var i = 0; i < declarations.length; i++) { + var declaration = declarations[i]; + if ((declaration.kind === 169 /* ClassDeclaration */ || (declaration.kind === 167 /* FunctionDeclaration */ && declaration.body)) && !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function checkModuleDeclaration(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + if (symbol.flags & 128 /* ValueModule */ && symbol.declarations.length > 1 && !ts.isInAmbientContext(node)) { + var classOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (classOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(classOrFunc)) { + error(node.name, ts.Diagnostics.A_module_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < classOrFunc.pos) { + error(node.name, ts.Diagnostics.A_module_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + } + if (node.name.kind === 3 /* StringLiteral */) { + if (!isGlobalSourceFile(node.parent)) { + error(node.name, ts.Diagnostics.Ambient_external_modules_cannot_be_nested_in_other_modules); + } + if (isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_external_module_declaration_cannot_specify_relative_module_name); + } + } + checkSourceElement(node.body); + } + function getFirstIdentifier(node) { + while (node.kind === 112 /* QualifiedName */) { + node = node.left; + } + return node; + } + function checkImportDeclaration(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + var symbol = getSymbolOfNode(node); + var target; + if (node.entityName) { + target = resolveImport(symbol); + if (target !== unknownSymbol) { + if (target.flags & ts.SymbolFlags.Value) { + var moduleName = getFirstIdentifier(node.entityName); + if (resolveEntityName(node, moduleName, ts.SymbolFlags.Value | ts.SymbolFlags.Namespace).flags & ts.SymbolFlags.Namespace) { + checkExpression(node.entityName); + } + else { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.identifierToString(moduleName)); + } + } + if (target.flags & ts.SymbolFlags.Type) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (node.parent.kind === 177 /* SourceFile */) { + target = resolveImport(symbol); + } + else if (node.parent.kind === 173 /* ModuleBlock */ && node.parent.parent.name.kind === 3 /* StringLiteral */) { + if (isExternalModuleNameRelative(node.externalModuleName.text)) { + error(node, ts.Diagnostics.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name); + target = unknownSymbol; + } + else { + target = resolveImport(symbol); + } + } + else { + target = unknownSymbol; + } + } + if (target !== unknownSymbol) { + var excludedMeanings = (symbol.flags & ts.SymbolFlags.Value ? ts.SymbolFlags.Value : 0) | (symbol.flags & ts.SymbolFlags.Type ? ts.SymbolFlags.Type : 0) | (symbol.flags & ts.SymbolFlags.Namespace ? ts.SymbolFlags.Namespace : 0); + if (target.flags & excludedMeanings) { + error(node, ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0, symbolToString(symbol)); + } + } + } + function checkExportAssignment(node) { + var container = node.parent; + if (container.kind !== 177 /* SourceFile */) { + container = container.parent; + } + checkTypeOfExportAssignmentSymbol(getSymbolOfNode(container)); + } + function checkSourceElement(node) { + if (!node) + return; + switch (node.kind) { + case 113 /* TypeParameter */: + return checkTypeParameter(node); + case 114 /* Parameter */: + return checkParameter(node); + case 115 /* Property */: + return checkPropertyDeclaration(node); + case 120 /* CallSignature */: + case 121 /* ConstructSignature */: + case 122 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 116 /* Method */: + return checkMethodDeclaration(node); + case 117 /* Constructor */: + return checkConstructorDeclaration(node); + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 123 /* TypeReference */: + return checkTypeReference(node); + case 124 /* TypeQuery */: + return checkTypeQuery(node); + case 125 /* TypeLiteral */: + return checkTypeLiteral(node); + case 126 /* ArrayType */: + return checkArrayType(node); + case 167 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 143 /* Block */: + case 168 /* FunctionBlock */: + case 173 /* ModuleBlock */: + return checkBlock(node); + case 144 /* VariableStatement */: + return checkVariableStatement(node); + case 146 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 147 /* IfStatement */: + return checkIfStatement(node); + case 148 /* DoStatement */: + return checkDoStatement(node); + case 149 /* WhileStatement */: + return checkWhileStatement(node); + case 150 /* ForStatement */: + return checkForStatement(node); + case 151 /* ForInStatement */: + return checkForInStatement(node); + case 152 /* ContinueStatement */: + case 153 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 154 /* ReturnStatement */: + return checkReturnStatement(node); + case 155 /* WithStatement */: + return checkWithStatement(node); + case 156 /* SwitchStatement */: + return checkSwitchStatement(node); + case 159 /* LabelledStatement */: + return checkLabelledStatement(node); + case 160 /* ThrowStatement */: + return checkThrowStatement(node); + case 161 /* TryStatement */: + return checkTryStatement(node); + case 166 /* VariableDeclaration */: + return ts.Debug.fail("Checker encountered variable declaration"); + case 169 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 170 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 171 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 172 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 174 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 175 /* ExportAssignment */: + return checkExportAssignment(node); + } + } + function checkSourceFile(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + emitExtends = false; + potentialThisCollisions.length = 0; + ts.forEach(node.statements, checkSourceElement); + if (ts.isExternalModule(node)) { + var symbol = getExportAssignmentSymbol(node.symbol); + if (symbol && symbol.flags & 4194304 /* Import */) { + getSymbolLinks(symbol).referenced = true; + } + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + potentialThisCollisions.length = 0; + } + if (emitExtends) + links.flags |= 8 /* EmitExtends */; + links.flags |= 1 /* TypeChecked */; + } + } + function checkProgram() { + ts.forEach(program.getSourceFiles(), checkSourceFile); + } + function getSortedDiagnostics() { + if (diagnosticsModified) { + diagnostics.sort(ts.compareDiagnostics); + diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); + diagnosticsModified = false; + } + return diagnostics; + } + function getDiagnostics(sourceFile) { + if (sourceFile) { + checkSourceFile(sourceFile); + return ts.filter(getSortedDiagnostics(), function (d) { return d.file === sourceFile; }); + } + checkProgram(); + return getSortedDiagnostics(); + } + function getGlobalDiagnostics() { + return ts.filter(getSortedDiagnostics(), function (d) { return !d.file; }); + } + function getNodeAtPosition(sourceFile, position) { + function findChildAtPosition(parent) { + var child = ts.forEachChild(parent, function (node) { + if (position >= node.pos && position <= node.end && position >= ts.getTokenPosOfNode(node)) { + return findChildAtPosition(node); + } + }); + return child || parent; + } + if (position < sourceFile.pos) + position = sourceFile.pos; + if (position > sourceFile.end) + position = sourceFile.end; + return findChildAtPosition(sourceFile); + } + function getSymbolsInScope(location, meaning) { + var symbols = {}; + var memberFlags = 0; + function copySymbol(symbol, meaning) { + if (symbol.flags & meaning) { + var id = symbol.name; + if (!isReservedMemberName(id) && !ts.hasProperty(symbols, id)) { + symbols[id] = symbol; + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + copySymbol(source[id], meaning); + } + } + } + } + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 177 /* SourceFile */: + if (!ts.isExternalModule(location)) + break; + case 172 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & ts.SymbolFlags.ModuleMember); + break; + case 171 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 4 /* EnumMember */); + break; + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + if (!(memberFlags & 64 /* Static */)) { + copySymbols(getSymbolOfNode(location).members, meaning & ts.SymbolFlags.Type); + } + break; + case 136 /* FunctionExpression */: + if (location.name) { + copySymbol(location.symbol, meaning); + } + break; + case 163 /* CatchBlock */: + if (location.variable.text) { + copySymbol(location.symbol, meaning); + } + break; + } + memberFlags = location.flags; + location = location.parent; + } + copySymbols(globals, meaning); + return ts.mapToArray(symbols); + } + function isDeclarationIdentifier(identifier) { + if (identifier.parent) { + switch (identifier.parent.kind) { + case 113 /* TypeParameter */: + case 114 /* Parameter */: + case 166 /* VariableDeclaration */: + case 115 /* Property */: + case 129 /* PropertyAssignment */: + case 176 /* EnumMember */: + case 116 /* Method */: + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + case 171 /* EnumDeclaration */: + case 172 /* ModuleDeclaration */: + case 174 /* ImportDeclaration */: + return identifier.parent.name === identifier; + case 163 /* CatchBlock */: + return identifier.parent.variable === identifier; + } + } + return false; + } + function isTypeReferenceIdentifier(identifier) { + var node = identifier; + if (node.parent && node.parent.kind === 112 /* QualifiedName */) + node = node.parent; + return node.parent && node.parent.kind === 123 /* TypeReference */; + } + function isExpression(node) { + switch (node.kind) { + case 83 /* ThisKeyword */: + case 81 /* SuperKeyword */: + case 79 /* NullKeyword */: + case 85 /* TrueKeyword */: + case 70 /* FalseKeyword */: + case 4 /* RegularExpressionLiteral */: + case 127 /* ArrayLiteral */: + case 128 /* ObjectLiteral */: + case 130 /* PropertyAccess */: + case 131 /* IndexedAccess */: + case 132 /* CallExpression */: + case 133 /* NewExpression */: + case 134 /* TypeAssertion */: + case 135 /* ParenExpression */: + case 136 /* FunctionExpression */: + case 137 /* ArrowFunction */: + case 138 /* PrefixOperator */: + case 139 /* PostfixOperator */: + case 140 /* BinaryExpression */: + case 141 /* ConditionalExpression */: + return true; + case 112 /* QualifiedName */: + while (node.parent && node.parent.kind === 112 /* QualifiedName */) + node = node.parent; + return node.parent && node.parent.kind === 124 /* TypeQuery */; + case 55 /* Identifier */: + case 2 /* NumericLiteral */: + case 3 /* StringLiteral */: + var parent = node.parent; + if (parent) { + if (isExpression(parent)) + return true; + switch (parent.kind) { + case 166 /* VariableDeclaration */: + case 114 /* Parameter */: + case 115 /* Property */: + case 176 /* EnumMember */: + return parent.initializer === node; + case 146 /* ExpressionStatement */: + case 147 /* IfStatement */: + case 148 /* DoStatement */: + case 149 /* WhileStatement */: + case 154 /* ReturnStatement */: + case 155 /* WithStatement */: + case 156 /* SwitchStatement */: + case 157 /* CaseClause */: + case 160 /* ThrowStatement */: + case 156 /* SwitchStatement */: + return parent.expression === node; + case 150 /* ForStatement */: + return parent.initializer === node || parent.condition === node || parent.iterator === node; + case 151 /* ForInStatement */: + return parent.variable === node || parent.expression === node; + } + } + } + return false; + } + function isRightSideOfQualifiedName(node) { + return (node.parent.kind === 112 /* QualifiedName */ || node.parent.kind === 130 /* PropertyAccess */) && node.parent.right === node; + } + function getSymbolOfIdentifier(identifier) { + if (isExpression(identifier)) { + if (isRightSideOfQualifiedName(identifier)) { + var node = identifier.parent; + var symbol = getNodeLinks(node).resolvedSymbol; + if (!symbol) { + checkPropertyAccess(node); + } + return getNodeLinks(node).resolvedSymbol; + } + return resolveEntityName(identifier, identifier, ts.SymbolFlags.Value); + } + if (isDeclarationIdentifier(identifier)) { + return getSymbolOfNode(identifier.parent); + } + if (isTypeReferenceIdentifier(identifier)) { + var entityName = isRightSideOfQualifiedName(identifier) ? identifier.parent : identifier; + var meaning = entityName.parent.kind === 123 /* TypeReference */ ? ts.SymbolFlags.Type : ts.SymbolFlags.Namespace; + return resolveEntityName(entityName, entityName, meaning); + } + } + function getTypeOfExpression(node) { + if (isExpression(node)) { + while (isRightSideOfQualifiedName(node)) { + node = node.parent; + } + return getApparentType(checkExpression(node)); + } + return unknownType; + } + function getAugmentedPropertiesOfApparentType(type) { + var apparentType = getApparentType(type); + if (apparentType.flags & ts.TypeFlags.ObjectType) { + var propertiesByName = {}; + var results = []; + ts.forEach(getPropertiesOfType(apparentType), function (s) { + propertiesByName[s.name] = s; + results.push(s); + }); + var resolved = resolveObjectTypeMembers(type); + ts.forEachValue(resolved.members, function (s) { + if (symbolIsValue(s) && !propertiesByName[s.name]) { + propertiesByName[s.name] = s; + results.push(s); + } + }); + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (s) { + if (!propertiesByName[s.name]) { + propertiesByName[s.name] = s; + results.push(s); + } + }); + } + return results; + } + else { + return getPropertiesOfType(apparentType); + } + } + function isExternalModuleSymbol(symbol) { + return symbol.flags & 128 /* ValueModule */ && symbol.declarations.length === 1 && symbol.declarations[0].kind === 177 /* SourceFile */; + } + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + function isUniqueLocalName(name, container) { + for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name) && node.locals[name].flags & (ts.SymbolFlags.Value | 524288 /* ExportValue */)) { + return false; + } + } + return true; + } + function getLocalNameOfContainer(container) { + var links = getNodeLinks(container); + if (!links.localModuleName) { + var prefix = ""; + var name = ts.unescapeIdentifier(container.name.text); + while (!isUniqueLocalName(ts.escapeIdentifier(prefix + name), container)) { + prefix += "_"; + } + links.localModuleName = prefix + ts.getSourceTextOfNode(container.name); + } + return links.localModuleName; + } + function getLocalNameForSymbol(symbol, location) { + var node = location; + while (node) { + if ((node.kind === 172 /* ModuleDeclaration */ || node.kind === 171 /* EnumDeclaration */) && getSymbolOfNode(node) === symbol) { + return getLocalNameOfContainer(node); + } + node = node.parent; + } + ts.Debug.fail("getLocalNameForSymbol failed"); + } + function getExpressionNamePrefix(node) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol) { + var exportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + if (symbol !== exportSymbol && !(exportSymbol.flags & ts.SymbolFlags.ExportHasLocal)) { + symbol = exportSymbol; + } + if (symbol.parent) { + return isExternalModuleSymbol(symbol.parent) ? "exports" : getLocalNameForSymbol(getParentOfSymbol(symbol), node.parent); + } + } + } + function getPropertyAccessSubstitution(node) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 4 /* EnumMember */)) { + var declaration = symbol.valueDeclaration; + var constantValue; + if (declaration.kind === 176 /* EnumMember */ && (constantValue = getNodeLinks(declaration).enumMemberValue) !== undefined) { + return constantValue.toString() + " /* " + ts.identifierToString(declaration.name) + " */"; + } + } + } + function getExportAssignmentName(node) { + var symbol = getExportAssignmentSymbol(getSymbolOfNode(node)); + return symbol && symbolIsValue(symbol) ? symbolToString(symbol) : undefined; + } + function isTopLevelValueImportedViaEntityName(node) { + if (node.parent.kind !== 177 /* SourceFile */ || !node.entityName) { + return false; + } + var symbol = getSymbolOfNode(node); + var target = resolveImport(symbol); + return target !== unknownSymbol && ((target.flags & ts.SymbolFlags.Value) !== 0); + } + function shouldEmitDeclarations() { + return program.getCompilerOptions().declaration && !program.getDiagnostics().length && !getDiagnostics().length; + } + function isReferencedImportDeclaration(node) { + var symbol = getSymbolOfNode(node); + if (getSymbolLinks(symbol).referenced) { + return true; + } + if (node.flags & 1 /* Export */) { + var target = resolveImport(symbol); + if (target !== unknownSymbol && target.flags & ts.SymbolFlags.Value) { + return true; + } + } + return false; + } + function isImplementationOfOverload(node) { + if (node.body) { + var symbol = getSymbolOfNode(node); + return getSignaturesOfSymbol(symbol).length > 1; + } + return false; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + return getNodeLinks(node).enumMemberValue; + } + function writeTypeAtLocation(location, enclosingDeclaration, flags, writer) { + var symbol = getSymbolOfNode(location); + var type = symbol && !(symbol.flags & 512 /* TypeLiteral */) ? getTypeOfSymbol(symbol) : getTypeFromTypeNode(location); + writeTypeToTextWriter(type, enclosingDeclaration, flags, writer); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + writeTypeToTextWriter(getReturnTypeOfSignature(signature), enclosingDeclaration, flags, writer); + } + function invokeEmitter() { + var resolver = { + getProgram: function () { return program; }, + getLocalNameOfContainer: getLocalNameOfContainer, + getExpressionNamePrefix: getExpressionNamePrefix, + getPropertyAccessSubstitution: getPropertyAccessSubstitution, + getExportAssignmentName: getExportAssignmentName, + isReferencedImportDeclaration: isReferencedImportDeclaration, + getNodeCheckFlags: getNodeCheckFlags, + getEnumMemberValue: getEnumMemberValue, + isTopLevelValueImportedViaEntityName: isTopLevelValueImportedViaEntityName, + shouldEmitDeclarations: shouldEmitDeclarations, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + writeTypeAtLocation: writeTypeAtLocation, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration + }; + checkProgram(); + return ts.emitFiles(resolver); + } + function initializeTypeChecker() { + ts.forEach(program.getSourceFiles(), function (file) { + ts.bindSourceFile(file); + ts.forEach(file.semanticErrors, addDiagnostic); + }); + ts.forEach(program.getSourceFiles(), function (file) { + if (!ts.isExternalModule(file)) { + extendSymbolTable(globals, file.locals); + } + }); + getSymbolLinks(undefinedSymbol).type = undefinedType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); + getSymbolLinks(unknownSymbol).type = unknownType; + globals[undefinedSymbol.name] = undefinedSymbol; + globalArrayType = getGlobalType("Array", 1); + globalObjectType = getGlobalType("Object"); + globalFunctionType = getGlobalType("Function"); + globalStringType = getGlobalType("String"); + globalNumberType = getGlobalType("Number"); + globalBooleanType = getGlobalType("Boolean"); + globalRegExpType = getGlobalType("RegExp"); + } + initializeTypeChecker(); + return checker; + } + ts.createTypeChecker = createTypeChecker; +})(ts || (ts = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.DiagnosticCode = { + error_TS_0_1: "error TS{0}: {1}", + warning_TS_0_1: "warning TS{0}: {1}", + Unrecognized_escape_sequence: "Unrecognized escape sequence.", + Unexpected_character_0: "Unexpected character {0}.", + Missing_close_quote_character: "Missing close quote character.", + Identifier_expected: "Identifier expected.", + _0_keyword_expected: "'{0}' keyword expected.", + _0_expected: "'{0}' expected.", + Identifier_expected_0_is_a_keyword: "Identifier expected; '{0}' is a keyword.", + Automatic_semicolon_insertion_not_allowed: "Automatic semicolon insertion not allowed.", + Unexpected_token_0_expected: "Unexpected token; '{0}' expected.", + Trailing_comma_not_allowed: "Trailing comma not allowed.", + AsteriskSlash_expected: "'*/' expected.", + public_or_private_modifier_must_precede_static: "'public' or 'private' modifier must precede 'static'.", + Unexpected_token: "Unexpected token.", + Catch_clause_parameter_cannot_have_a_type_annotation: "Catch clause parameter cannot have a type annotation.", + A_rest_parameter_must_be_last_in_a_parameter_list: "A rest parameter must be last in a parameter list.", + Parameter_cannot_have_question_mark_and_initializer: "Parameter cannot have question mark and initializer.", + A_required_parameter_cannot_follow_an_optional_parameter: "A required parameter cannot follow an optional parameter.", + Index_signatures_cannot_have_rest_parameters: "Index signatures cannot have rest parameters.", + Index_signature_parameter_cannot_have_accessibility_modifiers: "Index signature parameter cannot have accessibility modifiers.", + Index_signature_parameter_cannot_have_a_question_mark: "Index signature parameter cannot have a question mark.", + Index_signature_parameter_cannot_have_an_initializer: "Index signature parameter cannot have an initializer.", + Index_signature_must_have_a_type_annotation: "Index signature must have a type annotation.", + Index_signature_parameter_must_have_a_type_annotation: "Index signature parameter must have a type annotation.", + Index_signature_parameter_type_must_be_string_or_number: "Index signature parameter type must be 'string' or 'number'.", + extends_clause_already_seen: "'extends' clause already seen.", + extends_clause_must_precede_implements_clause: "'extends' clause must precede 'implements' clause.", + Classes_can_only_extend_a_single_class: "Classes can only extend a single class.", + implements_clause_already_seen: "'implements' clause already seen.", + Accessibility_modifier_already_seen: "Accessibility modifier already seen.", + _0_modifier_must_precede_1_modifier: "'{0}' modifier must precede '{1}' modifier.", + _0_modifier_already_seen: "'{0}' modifier already seen.", + _0_modifier_cannot_appear_on_a_class_element: "'{0}' modifier cannot appear on a class element.", + Interface_declaration_cannot_have_implements_clause: "Interface declaration cannot have 'implements' clause.", + super_invocation_cannot_have_type_arguments: "'super' invocation cannot have type arguments.", + Only_ambient_modules_can_use_quoted_names: "Only ambient modules can use quoted names.", + Statements_are_not_allowed_in_ambient_contexts: "Statements are not allowed in ambient contexts.", + A_function_implementation_cannot_be_declared_in_an_ambient_context: "A function implementation cannot be declared in an ambient context.", + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: "A 'declare' modifier cannot be used in an already ambient context.", + Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", + _0_modifier_cannot_appear_on_a_module_element: "'{0}' modifier cannot appear on a module element.", + A_declare_modifier_cannot_be_used_with_an_interface_declaration: "A 'declare' modifier cannot be used with an interface declaration.", + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: "A 'declare' modifier is required for a top level declaration in a .d.ts file.", + A_rest_parameter_cannot_be_optional: "A rest parameter cannot be optional.", + A_rest_parameter_cannot_have_an_initializer: "A rest parameter cannot have an initializer.", + set_accessor_must_have_exactly_one_parameter: "'set' accessor must have exactly one parameter.", + set_accessor_parameter_cannot_be_optional: "'set' accessor parameter cannot be optional.", + set_accessor_parameter_cannot_have_an_initializer: "'set' accessor parameter cannot have an initializer.", + set_accessor_cannot_have_rest_parameter: "'set' accessor cannot have rest parameter.", + get_accessor_cannot_have_parameters: "'get' accessor cannot have parameters.", + Modifiers_cannot_appear_here: "Modifiers cannot appear here.", + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: "Accessors are only available when targeting ECMAScript 5 and higher.", + Enum_member_must_have_initializer: "Enum member must have initializer.", + Export_assignment_cannot_be_used_in_internal_modules: "Export assignment cannot be used in internal modules.", + Ambient_enum_elements_can_only_have_integer_literal_initializers: "Ambient enum elements can only have integer literal initializers.", + module_class_interface_enum_import_or_statement: "module, class, interface, enum, import or statement", + constructor_function_accessor_or_variable: "constructor, function, accessor or variable", + statement: "statement", + case_or_default_clause: "case or default clause", + identifier: "identifier", + call_construct_index_property_or_function_signature: "call, construct, index, property or function signature", + expression: "expression", + type_name: "type name", + property_or_accessor: "property or accessor", + parameter: "parameter", + type: "type", + type_parameter: "type parameter", + A_declare_modifier_cannot_be_used_with_an_import_declaration: "A 'declare' modifier cannot be used with an import declaration.", + Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", + Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", + _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", + _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", + Type_parameters_cannot_appear_on_an_accessor: "Type parameters cannot appear on an accessor.", + Type_annotation_cannot_appear_on_a_set_accessor: "Type annotation cannot appear on a 'set' accessor.", + Index_signature_must_have_exactly_one_parameter: "Index signature must have exactly one parameter.", + _0_list_cannot_be_empty: "'{0}' list cannot be empty.", + variable_declaration: "variable declaration", + type_argument: "type argument", + Invalid_use_of_0_in_strict_mode: "Invalid use of '{0}' in strict mode.", + with_statements_are_not_allowed_in_strict_mode: "'with' statements are not allowed in strict mode.", + delete_cannot_be_called_on_an_identifier_in_strict_mode: "'delete' cannot be called on an identifier in strict mode.", + Invalid_left_hand_side_in_for_in_statement: "Invalid left-hand side in 'for...in' statement.", + continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: "'continue' statement can only be used within an enclosing iteration statement.", + break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: "'break' statement can only be used within an enclosing iteration or switch statement.", + Jump_target_not_found: "Jump target not found.", + Jump_target_cannot_cross_function_boundary: "Jump target cannot cross function boundary.", + return_statement_must_be_contained_within_a_function_body: "'return' statement must be contained within a function body.", + Expression_expected: "Expression expected.", + Type_expected: "Type expected.", + Duplicate_identifier_0: "Duplicate identifier '{0}'.", + The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", + The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", + super_can_only_be_used_inside_a_class_instance_method: "'super' can only be used inside a class instance method.", + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_property_or_indexer: "The left-hand side of an assignment expression must be a variable, property or indexer.", + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + Value_of_type_0_is_not_callable: "Value of type '{0}' is not callable.", + Value_of_type_0_is_not_newable: "Value of type '{0}' is not newable.", + An_index_expression_argument_must_be_string_number_or_any: "An index expression argument must be 'string', 'number', or 'any'.", + Operator_0_cannot_be_applied_to_types_1_and_2: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + Type_0_is_not_assignable_to_type_1: "Type '{0}' is not assignable to type '{1}'.", + Type_0_is_not_assignable_to_type_1_NL_2: "Type '{0}' is not assignable to type '{1}':{NL}{2}", + Expected_var_class_interface_or_module: "Expected var, class, interface, or module.", + Getter_0_already_declared: "Getter '{0}' already declared.", + Setter_0_already_declared: "Setter '{0}' already declared.", + Exported_class_0_extends_private_class_1: "Exported class '{0}' extends private class '{1}'.", + Exported_class_0_implements_private_interface_1: "Exported class '{0}' implements private interface '{1}'.", + Exported_interface_0_extends_private_interface_1: "Exported interface '{0}' extends private interface '{1}'.", + Exported_class_0_extends_class_from_inaccessible_module_1: "Exported class '{0}' extends class from inaccessible module {1}.", + Exported_class_0_implements_interface_from_inaccessible_module_1: "Exported class '{0}' implements interface from inaccessible module {1}.", + Exported_interface_0_extends_interface_from_inaccessible_module_1: "Exported interface '{0}' extends interface from inaccessible module {1}.", + Public_static_property_0_of_exported_class_has_or_is_using_private_type_1: "Public static property '{0}' of exported class has or is using private type '{1}'.", + Public_property_0_of_exported_class_has_or_is_using_private_type_1: "Public property '{0}' of exported class has or is using private type '{1}'.", + Property_0_of_exported_interface_has_or_is_using_private_type_1: "Property '{0}' of exported interface has or is using private type '{1}'.", + Exported_variable_0_has_or_is_using_private_type_1: "Exported variable '{0}' has or is using private type '{1}'.", + Public_static_property_0_of_exported_class_is_using_inaccessible_module_1: "Public static property '{0}' of exported class is using inaccessible module {1}.", + Public_property_0_of_exported_class_is_using_inaccessible_module_1: "Public property '{0}' of exported class is using inaccessible module {1}.", + Property_0_of_exported_interface_is_using_inaccessible_module_1: "Property '{0}' of exported interface is using inaccessible module {1}.", + Exported_variable_0_is_using_inaccessible_module_1: "Exported variable '{0}' is using inaccessible module {1}.", + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + Parameter_0_of_exported_function_has_or_is_using_private_type_1: "Parameter '{0}' of exported function has or is using private type '{1}'.", + Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + Parameter_0_of_exported_function_is_using_inaccessible_module_1: "Parameter '{0}' of exported function is using inaccessible module {1}.", + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public static property getter from exported class has or is using private type '{0}'.", + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public property getter from exported class has or is using private type '{0}'.", + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of call signature from exported interface has or is using private type '{0}'.", + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of index signature from exported interface has or is using private type '{0}'.", + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public static method from exported class has or is using private type '{0}'.", + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public method from exported class has or is using private type '{0}'.", + Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0: "Return type of method from exported interface has or is using private type '{0}'.", + Return_type_of_exported_function_has_or_is_using_private_type_0: "Return type of exported function has or is using private type '{0}'.", + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public static property getter from exported class is using inaccessible module {0}.", + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public property getter from exported class is using inaccessible module {0}.", + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of call signature from exported interface is using inaccessible module {0}.", + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of index signature from exported interface is using inaccessible module {0}.", + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public static method from exported class is using inaccessible module {0}.", + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public method from exported class is using inaccessible module {0}.", + Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0: "Return type of method from exported interface is using inaccessible module {0}.", + Return_type_of_exported_function_is_using_inaccessible_module_0: "Return type of exported function is using inaccessible module {0}.", + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + A_parameter_list_must_follow_a_generic_type_argument_list_expected: "A parameter list must follow a generic type argument list. '(' expected.", + Multiple_constructor_implementations_are_not_allowed: "Multiple constructor implementations are not allowed.", + Cannot_find_external_module_0: "Cannot find external module '{0}'.", + Module_cannot_be_aliased_to_a_non_module_type: "Module cannot be aliased to a non-module type.", + A_class_may_only_extend_another_class: "A class may only extend another class.", + A_class_may_only_implement_another_class_or_interface: "A class may only implement another class or interface.", + An_interface_may_only_extend_a_class_or_another_interface: "An interface may only extend a class or another interface.", + Unable_to_resolve_type: "Unable to resolve type.", + Unable_to_resolve_type_of_0: "Unable to resolve type of '{0}'.", + Unable_to_resolve_type_parameter_constraint: "Unable to resolve type parameter constraint.", + Type_parameter_constraint_cannot_be_a_primitive_type: "Type parameter constraint cannot be a primitive type.", + Supplied_parameters_do_not_match_any_signature_of_call_target: "Supplied parameters do not match any signature of call target.", + Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0: "Supplied parameters do not match any signature of call target:{NL}{0}", + Cannot_use_new_with_an_expression_whose_type_lacks_a_signature: "Cannot use 'new' with an expression whose type lacks a signature.", + Only_a_void_function_can_be_called_with_the_new_keyword: "Only a void function can be called with the 'new' keyword.", + Could_not_select_overload_for_new_expression: "Could not select overload for 'new' expression.", + Type_0_does_not_satisfy_the_constraint_1: "Type '{0}' does not satisfy the constraint '{1}'.", + Could_not_select_overload_for_call_expression: "Could not select overload for 'call' expression.", + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: "Cannot invoke an expression whose type lacks a call signature.", + Calls_to_super_are_only_valid_inside_a_class: "Calls to 'super' are only valid inside a class.", + Generic_type_0_requires_1_type_argument_s: "Generic type '{0}' requires {1} type argument(s).", + Type_of_array_literal_cannot_be_determined_Best_common_type_could_not_be_found_for_array_elements: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + Could_not_find_enclosing_symbol_for_dotted_name_0: "Could not find enclosing symbol for dotted name '{0}'.", + Property_0_does_not_exist_on_value_of_type_1: "Property '{0}' does not exist on value of type '{1}'.", + Cannot_find_name_0: "Cannot find name '{0}'.", + get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", + this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", + Type_0_recursively_references_itself_as_a_base_type: "Type '{0}' recursively references itself as a base type.", + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", + super_can_only_be_referenced_in_a_derived_class: "'super' can only be referenced in a derived class.", + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + Constructors_for_derived_classes_must_contain_a_super_call: "Constructors for derived classes must contain a 'super' call.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", + _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", + this_cannot_be_referenced_in_a_module_body: "'this' cannot be referenced in a module body.", + Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: "An arithmetic operand must be of type 'any', 'number' or an enum type.", + Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation: "Variable declarations of a 'for' statement cannot use a type annotation.", + Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any: "Variable declarations of a 'for' statement must be of types 'string' or 'any'.", + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", + Setters_cannot_return_a_value: "Setters cannot return a value.", + Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", + Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", + Type_0_is_not_generic: "Type '{0}' is not generic.", + Getters_must_return_a_value: "Getters must return a value.", + Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", + Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", + Function_declared_a_non_void_return_type_but_has_no_return_expression: "Function declared a non-void return type, but has no return expression.", + Cannot_resolve_return_type_reference: "Cannot resolve return type reference.", + Constructors_cannot_have_a_return_type_of_void: "Constructors cannot have a return type of 'void'.", + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.", + All_symbols_within_a_with_block_will_be_resolved_to_any: "All symbols within a with block will be resolved to 'any'.", + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: "Import declarations in an internal module cannot reference an external module.", + Class_0_declares_interface_1_but_does_not_implement_it_NL_2: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + Class_0_declares_class_1_as_an_interface_but_does_not_implement_it_NL_2: "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}", + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: "The operand of an increment or decrement operator must be a variable, property or indexer.", + this_cannot_be_referenced_in_a_static_property_initializer: "'this' cannot be referenced in a static property initializer.", + Class_0_cannot_extend_class_1_NL_2: "Class '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_class_1_NL_2: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_interface_1_NL_2: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + Overload_signature_is_not_compatible_with_function_definition: "Overload signature is not compatible with function definition.", + Overload_signature_is_not_compatible_with_function_definition_NL_0: "Overload signature is not compatible with function definition:{NL}{0}", + Overload_signatures_must_all_be_public_or_private: "Overload signatures must all be public or private.", + Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", + Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", + Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", + this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", + Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", + Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", + Non_generic_functions_may_not_accept_type_arguments: "Non-generic functions may not accept type arguments.", + A_generic_type_may_not_reference_itself_with_a_wrapped_form_of_its_own_type_parameters: "A generic type may not reference itself with a wrapped form of its own type parameters.", + A_rest_parameter_must_be_of_an_array_type: "A rest parameter must be of an array type.", + Overload_signature_implementation_cannot_use_specialized_type: "Overload signature implementation cannot use specialized type.", + Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", + Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: "A parameter initializer is only allowed in a function or constructor implementation.", + Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", + Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", + Module_0_has_no_exported_member_1: "Module '{0}' has no exported member '{1}'.", + Unable_to_resolve_module_reference_0: "Unable to resolve module reference '{0}'.", + Could_not_find_module_0_in_module_1: "Could not find module '{0}' in module '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", + Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", + Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", + Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.", + Ambient_external_module_declaration_cannot_be_reopened: "Ambient external module declaration cannot be reopened.", + All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported: "All declarations of merged declaration '{0}' must be exported or not exported.", + super_cannot_be_referenced_in_constructor_arguments: "'super' cannot be referenced in constructor arguments.", + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: "Return type of constructor signature must be assignable to the instance type of the class.", + Ambient_external_module_declaration_must_be_defined_in_global_context: "Ambient external module declaration must be defined in global context.", + Ambient_external_module_declaration_cannot_specify_relative_module_name: "Ambient external module declaration cannot specify relative module name.", + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.", + No_best_common_type_exists_among_return_expressions: "No best common type exists among return expressions.", + Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set: "Import declaration cannot refer to external module reference when --noResolve option is set.", + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.", + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.", + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.", + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: "Expression resolves to '_super' that compiler uses to capture base class reference.", + TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_function_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported function has or is using private type '{1}'.", + TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}", + TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_exported_function_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported function is using inaccessible module {1}.", + TypeParameter_0_of_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported class has or is using private type '{1}'.", + TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported class is using inaccessible module {1}.", + TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported interface is using inaccessible module {1}.", + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.", + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.", + No_best_common_type_exists_between_0_and_1: "No best common type exists between '{0}' and '{1}'.", + No_best_common_type_exists_between_0_1_and_2: "No best common type exists between '{0}', '{1}', and '{2}'.", + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", + Neither_type_0_nor_type_1_is_assignable_to_the_other: "Neither type '{0}' nor type '{1}' is assignable to the other.", + Neither_type_0_nor_type_1_is_assignable_to_the_other_NL_2: "Neither type '{0}' nor type '{1}' is assignable to the other:{NL}{2}", + Duplicate_function_implementation: "Duplicate function implementation.", + Function_implementation_expected: "Function implementation expected.", + Function_overload_name_must_be_0: "Function overload name must be '{0}'.", + Constructor_implementation_expected: "Constructor implementation expected.", + Class_name_cannot_be_0: "Class name cannot be '{0}'.", + Interface_name_cannot_be_0: "Interface name cannot be '{0}'.", + Enum_name_cannot_be_0: "Enum name cannot be '{0}'.", + A_module_cannot_have_multiple_export_assignments: "A module cannot have multiple export assignments.", + Export_assignment_not_allowed_in_module_with_exported_element: "Export assignment not allowed in module with exported element.", + A_parameter_property_is_only_allowed_in_a_constructor_implementation: "A parameter property is only allowed in a constructor implementation.", + Function_overload_must_be_static: "Function overload must be static.", + Function_overload_must_not_be_static: "Function overload must not be static.", + Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", + Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_property_2_as_private: "Types '{0}' and '{1}' define property '{2}' as private.", + Call_signatures_of_types_0_and_1_are_incompatible: "Call signatures of types '{0}' and '{1}' are incompatible.", + Call_signatures_of_types_0_and_1_are_incompatible_NL_2: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_call_signature_but_type_1_lacks_one: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + Construct_signatures_of_types_0_and_1_are_incompatible: "Construct signatures of types '{0}' and '{1}' are incompatible.", + Construct_signatures_of_types_0_and_1_are_incompatible_NL_2: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_construct_signature_but_type_1_lacks_one: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + Index_signatures_of_types_0_and_1_are_incompatible: "Index signatures of types '{0}' and '{1}' are incompatible.", + Index_signatures_of_types_0_and_1_are_incompatible_NL_2: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Call_signature_expects_0_or_fewer_parameters: "Call signature expects {0} or fewer parameters.", + Could_not_apply_type_0_to_argument_1_which_is_of_type_2: "Could not apply type '{0}' to argument {1} which is of type '{2}'.", + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + 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 accessor.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", + Type_reference_must_refer_to_type: "Type reference must refer to type.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", + _0_overload_s: " (+ {0} overload(s))", + Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", + Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", + Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", + Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", + Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", + Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", + ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", + Argument_for_0_option_must_be_1_or_2: "Argument for '{0}' option must be '{1}' or '{2}'", + Could_not_find_file_0: "Could not find file: '{0}'.", + A_file_cannot_have_a_reference_to_itself: "A file cannot have a reference to itself.", + Cannot_resolve_referenced_file_0: "Cannot resolve referenced file: '{0}'.", + Cannot_find_the_common_subdirectory_path_for_the_input_files: "Cannot find the common subdirectory path for the input files.", + Emit_Error_0: "Emit Error: {0}.", + Cannot_read_file_0_1: "Cannot read file '{0}': {1}", + Unsupported_file_encoding: "Unsupported file encoding.", + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: "Locale must be of the form or -. For example '{0}' or '{1}'.", + Unsupported_locale_0: "Unsupported locale: '{0}'.", + Execution_Failed_NL: "Execution Failed.{NL}", + Invalid_call_to_up: "Invalid call to 'up'", + Invalid_call_to_down: "Invalid call to 'down'", + Base64_value_0_finished_with_a_continuation_bit: "Base64 value '{0}' finished with a continuation bit.", + Unknown_compiler_option_0: "Unknown compiler option '{0}'", + Expected_0_arguments_to_message_got_1_instead: "Expected {0} arguments to message, got {1} instead.", + Expected_the_message_0_to_have_1_arguments_but_it_had_2: "Expected the message '{0}' to have {1} arguments, but it had {2}", + Could_not_delete_file_0: "Could not delete file '{0}'", + Could_not_create_directory_0: "Could not create directory '{0}'", + Error_while_executing_file_0: "Error while executing file '{0}': ", + Cannot_compile_external_modules_unless_the_module_flag_is_provided: "Cannot compile external modules unless the '--module' flag is provided.", + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option mapRoot cannot be specified without specifying sourcemap option.", + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option sourceRoot cannot be specified without specifying sourcemap option.", + Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.", + Option_0_specified_without_1: "Option '{0}' specified without '{1}'", + codepage_option_not_supported_on_current_platform: "'codepage' option not supported on current platform.", + Concatenate_and_emit_output_to_single_file: "Concatenate and emit output to single file.", + Generates_corresponding_0_file: "Generates corresponding {0} file.", + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: "Specifies the location where debugger should locate map files instead of generated locations.", + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: "Specifies the location where debugger should locate TypeScript files instead of source locations.", + Watch_input_files: "Watch input files.", + Redirect_output_structure_to_the_directory: "Redirect output structure to the directory.", + Do_not_emit_comments_to_output: "Do not emit comments to output.", + Skip_resolution_and_preprocessing: "Skip resolution and preprocessing.", + Specify_ECMAScript_target_version_0_default_or_1: "Specify ECMAScript target version: '{0}' (default), or '{1}'", + Specify_module_code_generation_0_or_1: "Specify module code generation: '{0}' or '{1}'", + Print_this_message: "Print this message.", + Print_the_compiler_s_version_0: "Print the compiler's version: {0}", + Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: "Allow use of deprecated '{0}' keyword when referencing an external module.", + Specify_locale_for_errors_and_messages_For_example_0_or_1: "Specify locale for errors and messages. For example '{0}' or '{1}'", + Syntax_0: "Syntax: {0}", + options: "options", + file1: "file", + Examples: "Examples:", + Options: "Options:", + Insert_command_line_options_and_files_from_a_file: "Insert command line options and files from a file.", + Version_0: "Version {0}", + Use_the_0_flag_to_see_options: "Use the '{0}' flag to see options.", + NL_Recompiling_0: "{NL}Recompiling ({0}):", + STRING: "STRING", + KIND: "KIND", + file2: "FILE", + VERSION: "VERSION", + LOCATION: "LOCATION", + DIRECTORY: "DIRECTORY", + NUMBER: "NUMBER", + Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", + This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", + Unknown_rule: "Unknown rule.", + Invalid_line_number_0: "Invalid line number ({0})", + Warn_on_expressions_and_declarations_with_an_implied_any_type: "Warn on expressions and declarations with an implied 'any' type.", + Variable_0_implicitly_has_an_any_type: "Variable '{0}' implicitly has an 'any' type.", + Parameter_0_of_1_implicitly_has_an_any_type: "Parameter '{0}' of '{1}' implicitly has an 'any' type.", + Parameter_0_of_function_type_implicitly_has_an_any_type: "Parameter '{0}' of function type implicitly has an 'any' type.", + Member_0_of_object_type_implicitly_has_an_any_type: "Member '{0}' of object type implicitly has an 'any' type.", + new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type: "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.", + _0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.", + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.", + Parameter_0_of_lambda_function_implicitly_has_an_any_type: "Parameter '{0}' of lambda function implicitly has an 'any' type.", + Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", + Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", + Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticInformationMap = { + "error TS{0}: {1}": { "code": 0, "category": 3 /* NoPrefix */ }, + "warning TS{0}: {1}": { "code": 1, "category": 3 /* NoPrefix */ }, + "Unrecognized escape sequence.": { "code": 1000, "category": 1 /* Error */ }, + "Unexpected character {0}.": { "code": 1001, "category": 1 /* Error */ }, + "Missing close quote character.": { "code": 1002, "category": 1 /* Error */ }, + "Identifier expected.": { "code": 1003, "category": 1 /* Error */ }, + "'{0}' keyword expected.": { "code": 1004, "category": 1 /* Error */ }, + "'{0}' expected.": { "code": 1005, "category": 1 /* Error */ }, + "Identifier expected; '{0}' is a keyword.": { "code": 1006, "category": 1 /* Error */ }, + "Automatic semicolon insertion not allowed.": { "code": 1007, "category": 1 /* Error */ }, + "Unexpected token; '{0}' expected.": { "code": 1008, "category": 1 /* Error */ }, + "Trailing comma not allowed.": { "code": 1009, "category": 1 /* Error */ }, + "'*/' expected.": { "code": 1010, "category": 1 /* Error */ }, + "'public' or 'private' modifier must precede 'static'.": { "code": 1011, "category": 1 /* Error */ }, + "Unexpected token.": { "code": 1012, "category": 1 /* Error */ }, + "Catch clause parameter cannot have a type annotation.": { "code": 1013, "category": 1 /* Error */ }, + "A rest parameter must be last in a parameter list.": { "code": 1014, "category": 1 /* Error */ }, + "Parameter cannot have question mark and initializer.": { "code": 1015, "category": 1 /* Error */ }, + "A required parameter cannot follow an optional parameter.": { "code": 1016, "category": 1 /* Error */ }, + "Index signatures cannot have rest parameters.": { "code": 1017, "category": 1 /* Error */ }, + "Index signature parameter cannot have accessibility modifiers.": { "code": 1018, "category": 1 /* Error */ }, + "Index signature parameter cannot have a question mark.": { "code": 1019, "category": 1 /* Error */ }, + "Index signature parameter cannot have an initializer.": { "code": 1020, "category": 1 /* Error */ }, + "Index signature must have a type annotation.": { "code": 1021, "category": 1 /* Error */ }, + "Index signature parameter must have a type annotation.": { "code": 1022, "category": 1 /* Error */ }, + "Index signature parameter type must be 'string' or 'number'.": { "code": 1023, "category": 1 /* Error */ }, + "'extends' clause already seen.": { "code": 1024, "category": 1 /* Error */ }, + "'extends' clause must precede 'implements' clause.": { "code": 1025, "category": 1 /* Error */ }, + "Classes can only extend a single class.": { "code": 1026, "category": 1 /* Error */ }, + "'implements' clause already seen.": { "code": 1027, "category": 1 /* Error */ }, + "Accessibility modifier already seen.": { "code": 1028, "category": 1 /* Error */ }, + "'{0}' modifier must precede '{1}' modifier.": { "code": 1029, "category": 1 /* Error */ }, + "'{0}' modifier already seen.": { "code": 1030, "category": 1 /* Error */ }, + "'{0}' modifier cannot appear on a class element.": { "code": 1031, "category": 1 /* Error */ }, + "Interface declaration cannot have 'implements' clause.": { "code": 1032, "category": 1 /* Error */ }, + "'super' invocation cannot have type arguments.": { "code": 1034, "category": 1 /* Error */ }, + "Only ambient modules can use quoted names.": { "code": 1035, "category": 1 /* Error */ }, + "Statements are not allowed in ambient contexts.": { "code": 1036, "category": 1 /* Error */ }, + "A function implementation cannot be declared in an ambient context.": { "code": 1037, "category": 1 /* Error */ }, + "A 'declare' modifier cannot be used in an already ambient context.": { "code": 1038, "category": 1 /* Error */ }, + "Initializers are not allowed in ambient contexts.": { "code": 1039, "category": 1 /* Error */ }, + "'{0}' modifier cannot appear on a module element.": { "code": 1044, "category": 1 /* Error */ }, + "A 'declare' modifier cannot be used with an interface declaration.": { "code": 1045, "category": 1 /* Error */ }, + "A 'declare' modifier is required for a top level declaration in a .d.ts file.": { "code": 1046, "category": 1 /* Error */ }, + "A rest parameter cannot be optional.": { "code": 1047, "category": 1 /* Error */ }, + "A rest parameter cannot have an initializer.": { "code": 1048, "category": 1 /* Error */ }, + "'set' accessor must have exactly one parameter.": { "code": 1049, "category": 1 /* Error */ }, + "'set' accessor parameter cannot be optional.": { "code": 1051, "category": 1 /* Error */ }, + "'set' accessor parameter cannot have an initializer.": { "code": 1052, "category": 1 /* Error */ }, + "'set' accessor cannot have rest parameter.": { "code": 1053, "category": 1 /* Error */ }, + "'get' accessor cannot have parameters.": { "code": 1054, "category": 1 /* Error */ }, + "Modifiers cannot appear here.": { "code": 1055, "category": 1 /* Error */ }, + "Accessors are only available when targeting ECMAScript 5 and higher.": { "code": 1056, "category": 1 /* Error */ }, + "Enum member must have initializer.": { "code": 1061, "category": 1 /* Error */ }, + "Export assignment cannot be used in internal modules.": { "code": 1063, "category": 1 /* Error */ }, + "Ambient enum elements can only have integer literal initializers.": { "code": 1066, "category": 1 /* Error */ }, + "module, class, interface, enum, import or statement": { "code": 1067, "category": 3 /* NoPrefix */ }, + "constructor, function, accessor or variable": { "code": 1068, "category": 3 /* NoPrefix */ }, + "statement": { "code": 1069, "category": 3 /* NoPrefix */ }, + "case or default clause": { "code": 1070, "category": 3 /* NoPrefix */ }, + "identifier": { "code": 1071, "category": 3 /* NoPrefix */ }, + "call, construct, index, property or function signature": { "code": 1072, "category": 3 /* NoPrefix */ }, + "expression": { "code": 1073, "category": 3 /* NoPrefix */ }, + "type name": { "code": 1074, "category": 3 /* NoPrefix */ }, + "property or accessor": { "code": 1075, "category": 3 /* NoPrefix */ }, + "parameter": { "code": 1076, "category": 3 /* NoPrefix */ }, + "type": { "code": 1077, "category": 3 /* NoPrefix */ }, + "type parameter": { "code": 1078, "category": 3 /* NoPrefix */ }, + "A 'declare' modifier cannot be used with an import declaration.": { "code": 1079, "category": 1 /* Error */ }, + "Invalid 'reference' directive syntax.": { "code": 1084, "category": 1 /* Error */ }, + "Octal literals are not available when targeting ECMAScript 5 and higher.": { "code": 1085, "category": 1 /* Error */ }, + "Accessors are not allowed in ambient contexts.": { "code": 1086, "category": 1 /* Error */ }, + "'{0}' modifier cannot appear on a constructor declaration.": { "code": 1089, "category": 1 /* Error */ }, + "'{0}' modifier cannot appear on a parameter.": { "code": 1090, "category": 1 /* Error */ }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { "code": 1091, "category": 1 /* Error */ }, + "Type parameters cannot appear on a constructor declaration.": { "code": 1092, "category": 1 /* Error */ }, + "Type annotation cannot appear on a constructor declaration.": { "code": 1093, "category": 1 /* Error */ }, + "Type parameters cannot appear on an accessor.": { "code": 1094, "category": 1 /* Error */ }, + "Type annotation cannot appear on a 'set' accessor.": { "code": 1095, "category": 1 /* Error */ }, + "Index signature must have exactly one parameter.": { "code": 1096, "category": 1 /* Error */ }, + "'{0}' list cannot be empty.": { "code": 1097, "category": 1 /* Error */ }, + "variable declaration": { "code": 1098, "category": 3 /* NoPrefix */ }, + "type argument": { "code": 1099, "category": 3 /* NoPrefix */ }, + "Invalid use of '{0}' in strict mode.": { "code": 1100, "category": 1 /* Error */ }, + "'with' statements are not allowed in strict mode.": { "code": 1101, "category": 1 /* Error */ }, + "'delete' cannot be called on an identifier in strict mode.": { "code": 1102, "category": 1 /* Error */ }, + "Invalid left-hand side in 'for...in' statement.": { "code": 1103, "category": 1 /* Error */ }, + "'continue' statement can only be used within an enclosing iteration statement.": { "code": 1104, "category": 1 /* Error */ }, + "'break' statement can only be used within an enclosing iteration or switch statement.": { "code": 1105, "category": 1 /* Error */ }, + "Jump target not found.": { "code": 1106, "category": 1 /* Error */ }, + "Jump target cannot cross function boundary.": { "code": 1107, "category": 1 /* Error */ }, + "'return' statement must be contained within a function body.": { "code": 1108, "category": 1 /* Error */ }, + "Expression expected.": { "code": 1109, "category": 1 /* Error */ }, + "Type expected.": { "code": 1110, "category": 1 /* Error */ }, + "Duplicate identifier '{0}'.": { "code": 2000, "category": 1 /* Error */ }, + "The name '{0}' does not exist in the current scope.": { "code": 2001, "category": 1 /* Error */ }, + "The name '{0}' does not refer to a value.": { "code": 2002, "category": 1 /* Error */ }, + "'super' can only be used inside a class instance method.": { "code": 2003, "category": 1 /* Error */ }, + "The left-hand side of an assignment expression must be a variable, property or indexer.": { "code": 2004, "category": 1 /* Error */ }, + "Value of type '{0}' is not callable. Did you mean to include 'new'?": { "code": 2161, "category": 1 /* Error */ }, + "Value of type '{0}' is not callable.": { "code": 2006, "category": 1 /* Error */ }, + "Value of type '{0}' is not newable.": { "code": 2007, "category": 1 /* Error */ }, + "An index expression argument must be 'string', 'number', or 'any'.": { "code": 2008, "category": 1 /* Error */ }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}'.": { "code": 2009, "category": 1 /* Error */ }, + "Type '{0}' is not assignable to type '{1}'.": { "code": 2011, "category": 1 /* Error */ }, + "Type '{0}' is not assignable to type '{1}':{NL}{2}": { "code": 2012, "category": 1 /* Error */ }, + "Expected var, class, interface, or module.": { "code": 2013, "category": 1 /* Error */ }, + "Getter '{0}' already declared.": { "code": 2015, "category": 1 /* Error */ }, + "Setter '{0}' already declared.": { "code": 2016, "category": 1 /* Error */ }, + "Exported class '{0}' extends private class '{1}'.": { "code": 2018, "category": 1 /* Error */ }, + "Exported class '{0}' implements private interface '{1}'.": { "code": 2019, "category": 1 /* Error */ }, + "Exported interface '{0}' extends private interface '{1}'.": { "code": 2020, "category": 1 /* Error */ }, + "Exported class '{0}' extends class from inaccessible module {1}.": { "code": 2021, "category": 1 /* Error */ }, + "Exported class '{0}' implements interface from inaccessible module {1}.": { "code": 2022, "category": 1 /* Error */ }, + "Exported interface '{0}' extends interface from inaccessible module {1}.": { "code": 2023, "category": 1 /* Error */ }, + "Public static property '{0}' of exported class has or is using private type '{1}'.": { "code": 2024, "category": 1 /* Error */ }, + "Public property '{0}' of exported class has or is using private type '{1}'.": { "code": 2025, "category": 1 /* Error */ }, + "Property '{0}' of exported interface has or is using private type '{1}'.": { "code": 2026, "category": 1 /* Error */ }, + "Exported variable '{0}' has or is using private type '{1}'.": { "code": 2027, "category": 1 /* Error */ }, + "Public static property '{0}' of exported class is using inaccessible module {1}.": { "code": 2028, "category": 1 /* Error */ }, + "Public property '{0}' of exported class is using inaccessible module {1}.": { "code": 2029, "category": 1 /* Error */ }, + "Property '{0}' of exported interface is using inaccessible module {1}.": { "code": 2030, "category": 1 /* Error */ }, + "Exported variable '{0}' is using inaccessible module {1}.": { "code": 2031, "category": 1 /* Error */ }, + "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.": { "code": 2032, "category": 1 /* Error */ }, + "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.": { "code": 2033, "category": 1 /* Error */ }, + "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.": { "code": 2034, "category": 1 /* Error */ }, + "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { "code": 2035, "category": 1 /* Error */ }, + "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { "code": 2036, "category": 1 /* Error */ }, + "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.": { "code": 2037, "category": 1 /* Error */ }, + "Parameter '{0}' of public method from exported class has or is using private type '{1}'.": { "code": 2038, "category": 1 /* Error */ }, + "Parameter '{0}' of method from exported interface has or is using private type '{1}'.": { "code": 2039, "category": 1 /* Error */ }, + "Parameter '{0}' of exported function has or is using private type '{1}'.": { "code": 2040, "category": 1 /* Error */ }, + "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.": { "code": 2041, "category": 1 /* Error */ }, + "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.": { "code": 2042, "category": 1 /* Error */ }, + "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.": { "code": 2043, "category": 1 /* Error */ }, + "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { "code": 2044, "category": 1 /* Error */ }, + "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}": { "code": 2045, "category": 1 /* Error */ }, + "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.": { "code": 2046, "category": 1 /* Error */ }, + "Parameter '{0}' of public method from exported class is using inaccessible module {1}.": { "code": 2047, "category": 1 /* Error */ }, + "Parameter '{0}' of method from exported interface is using inaccessible module {1}.": { "code": 2048, "category": 1 /* Error */ }, + "Parameter '{0}' of exported function is using inaccessible module {1}.": { "code": 2049, "category": 1 /* Error */ }, + "Return type of public static property getter from exported class has or is using private type '{0}'.": { "code": 2050, "category": 1 /* Error */ }, + "Return type of public property getter from exported class has or is using private type '{0}'.": { "code": 2051, "category": 1 /* Error */ }, + "Return type of constructor signature from exported interface has or is using private type '{0}'.": { "code": 2052, "category": 1 /* Error */ }, + "Return type of call signature from exported interface has or is using private type '{0}'.": { "code": 2053, "category": 1 /* Error */ }, + "Return type of index signature from exported interface has or is using private type '{0}'.": { "code": 2054, "category": 1 /* Error */ }, + "Return type of public static method from exported class has or is using private type '{0}'.": { "code": 2055, "category": 1 /* Error */ }, + "Return type of public method from exported class has or is using private type '{0}'.": { "code": 2056, "category": 1 /* Error */ }, + "Return type of method from exported interface has or is using private type '{0}'.": { "code": 2057, "category": 1 /* Error */ }, + "Return type of exported function has or is using private type '{0}'.": { "code": 2058, "category": 1 /* Error */ }, + "Return type of public static property getter from exported class is using inaccessible module {0}.": { "code": 2059, "category": 1 /* Error */ }, + "Return type of public property getter from exported class is using inaccessible module {0}.": { "code": 2060, "category": 1 /* Error */ }, + "Return type of constructor signature from exported interface is using inaccessible module {0}.": { "code": 2061, "category": 1 /* Error */ }, + "Return type of call signature from exported interface is using inaccessible module {0}.": { "code": 2062, "category": 1 /* Error */ }, + "Return type of index signature from exported interface is using inaccessible module {0}.": { "code": 2063, "category": 1 /* Error */ }, + "Return type of public static method from exported class is using inaccessible module {0}.": { "code": 2064, "category": 1 /* Error */ }, + "Return type of public method from exported class is using inaccessible module {0}.": { "code": 2065, "category": 1 /* Error */ }, + "Return type of method from exported interface is using inaccessible module {0}.": { "code": 2066, "category": 1 /* Error */ }, + "Return type of exported function is using inaccessible module {0}.": { "code": 2067, "category": 1 /* Error */ }, + "'new T[]' cannot be used to create an array. Use 'new Array()' instead.": { "code": 2068, "category": 1 /* Error */ }, + "A parameter list must follow a generic type argument list. '(' expected.": { "code": 2069, "category": 1 /* Error */ }, + "Multiple constructor implementations are not allowed.": { "code": 2070, "category": 1 /* Error */ }, + "Cannot find external module '{0}'.": { "code": 2071, "category": 1 /* Error */ }, + "Module cannot be aliased to a non-module type.": { "code": 2072, "category": 1 /* Error */ }, + "A class may only extend another class.": { "code": 2073, "category": 1 /* Error */ }, + "A class may only implement another class or interface.": { "code": 2074, "category": 1 /* Error */ }, + "An interface may only extend a class or another interface.": { "code": 2075, "category": 1 /* Error */ }, + "Unable to resolve type.": { "code": 2077, "category": 1 /* Error */ }, + "Unable to resolve type of '{0}'.": { "code": 2078, "category": 1 /* Error */ }, + "Unable to resolve type parameter constraint.": { "code": 2079, "category": 1 /* Error */ }, + "Type parameter constraint cannot be a primitive type.": { "code": 2080, "category": 1 /* Error */ }, + "Supplied parameters do not match any signature of call target.": { "code": 2081, "category": 1 /* Error */ }, + "Supplied parameters do not match any signature of call target:{NL}{0}": { "code": 2082, "category": 1 /* Error */ }, + "Cannot use 'new' with an expression whose type lacks a signature.": { "code": 2083, "category": 1 /* Error */ }, + "Only a void function can be called with the 'new' keyword.": { "code": 2084, "category": 1 /* Error */ }, + "Could not select overload for 'new' expression.": { "code": 2085, "category": 1 /* Error */ }, + "Type '{0}' does not satisfy the constraint '{1}'.": { "code": 2086, "category": 1 /* Error */ }, + "Could not select overload for 'call' expression.": { "code": 2087, "category": 1 /* Error */ }, + "Cannot invoke an expression whose type lacks a call signature.": { "code": 2088, "category": 1 /* Error */ }, + "Calls to 'super' are only valid inside a class.": { "code": 2089, "category": 1 /* Error */ }, + "Generic type '{0}' requires {1} type argument(s).": { "code": 2090, "category": 1 /* Error */ }, + "Type of array literal cannot be determined. Best common type could not be found for array elements.": { "code": 2092, "category": 1 /* Error */ }, + "Could not find enclosing symbol for dotted name '{0}'.": { "code": 2093, "category": 1 /* Error */ }, + "Property '{0}' does not exist on value of type '{1}'.": { "code": 2094, "category": 1 /* Error */ }, + "Cannot find name '{0}'.": { "code": 2095, "category": 1 /* Error */ }, + "'get' and 'set' accessor must have the same type.": { "code": 2096, "category": 1 /* Error */ }, + "'this' cannot be referenced in current location.": { "code": 2097, "category": 1 /* Error */ }, + "Static members cannot reference class type parameters.": { "code": 2099, "category": 1 /* Error */ }, + "Type '{0}' recursively references itself as a base type.": { "code": 2100, "category": 1 /* Error */ }, + "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.": { "code": 2102, "category": 1 /* Error */ }, + "'super' can only be referenced in a derived class.": { "code": 2103, "category": 1 /* Error */ }, + "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.": { "code": 2104, "category": 1 /* Error */ }, + "Constructors for derived classes must contain a 'super' call.": { "code": 2105, "category": 1 /* Error */ }, + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { "code": 2106, "category": 1 /* Error */ }, + "'{0}.{1}' is inaccessible.": { "code": 2107, "category": 1 /* Error */ }, + "'this' cannot be referenced in a module body.": { "code": 2108, "category": 1 /* Error */ }, + "Invalid '+' expression - types not known to support the addition operator.": { "code": 2111, "category": 1 /* Error */ }, + "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { "code": 2112, "category": 1 /* Error */ }, + "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { "code": 2113, "category": 1 /* Error */ }, + "An arithmetic operand must be of type 'any', 'number' or an enum type.": { "code": 2114, "category": 1 /* Error */ }, + "Variable declarations of a 'for' statement cannot use a type annotation.": { "code": 2115, "category": 1 /* Error */ }, + "Variable declarations of a 'for' statement must be of types 'string' or 'any'.": { "code": 2116, "category": 1 /* Error */ }, + "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.": { "code": 2117, "category": 1 /* Error */ }, + "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.": { "code": 2118, "category": 1 /* Error */ }, + "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.": { "code": 2119, "category": 1 /* Error */ }, + "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.": { "code": 2120, "category": 1 /* Error */ }, + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { "code": 2121, "category": 1 /* Error */ }, + "Setters cannot return a value.": { "code": 2122, "category": 1 /* Error */ }, + "Tried to query type of uninitialized module '{0}'.": { "code": 2123, "category": 1 /* Error */ }, + "Tried to set variable type to uninitialized module type '{0}'.": { "code": 2124, "category": 1 /* Error */ }, + "Type '{0}' is not generic.": { "code": 2125, "category": 1 /* Error */ }, + "Getters must return a value.": { "code": 2126, "category": 1 /* Error */ }, + "Getter and setter accessors do not agree in visibility.": { "code": 2127, "category": 1 /* Error */ }, + "Invalid left-hand side of assignment expression.": { "code": 2130, "category": 1 /* Error */ }, + "Function declared a non-void return type, but has no return expression.": { "code": 2131, "category": 1 /* Error */ }, + "Cannot resolve return type reference.": { "code": 2132, "category": 1 /* Error */ }, + "Constructors cannot have a return type of 'void'.": { "code": 2133, "category": 1 /* Error */ }, + "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.": { "code": 2134, "category": 1 /* Error */ }, + "All symbols within a with block will be resolved to 'any'.": { "code": 2135, "category": 1 /* Error */ }, + "Import declarations in an internal module cannot reference an external module.": { "code": 2136, "category": 1 /* Error */ }, + "Class {0} declares interface {1} but does not implement it:{NL}{2}": { "code": 2137, "category": 1 /* Error */ }, + "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}": { "code": 2138, "category": 1 /* Error */ }, + "The operand of an increment or decrement operator must be a variable, property or indexer.": { "code": 2139, "category": 1 /* Error */ }, + "'this' cannot be referenced in a static property initializer.": { "code": 2140, "category": 1 /* Error */ }, + "Class '{0}' cannot extend class '{1}':{NL}{2}": { "code": 2141, "category": 1 /* Error */ }, + "Interface '{0}' cannot extend class '{1}':{NL}{2}": { "code": 2142, "category": 1 /* Error */ }, + "Interface '{0}' cannot extend interface '{1}':{NL}{2}": { "code": 2143, "category": 1 /* Error */ }, + "Overload signature is not compatible with function definition.": { "code": 2148, "category": 1 /* Error */ }, + "Overload signature is not compatible with function definition:{NL}{0}": { "code": 2149, "category": 1 /* Error */ }, + "Overload signatures must all be public or private.": { "code": 2150, "category": 1 /* Error */ }, + "Overload signatures must all be exported or not exported.": { "code": 2151, "category": 1 /* Error */ }, + "Overload signatures must all be ambient or non-ambient.": { "code": 2152, "category": 1 /* Error */ }, + "Overload signatures must all be optional or required.": { "code": 2153, "category": 1 /* Error */ }, + "Specialized overload signature is not assignable to any non-specialized signature.": { "code": 2154, "category": 1 /* Error */ }, + "'this' cannot be referenced in constructor arguments.": { "code": 2155, "category": 1 /* Error */ }, + "Instance member cannot be accessed off a class.": { "code": 2157, "category": 1 /* Error */ }, + "Untyped function calls may not accept type arguments.": { "code": 2158, "category": 1 /* Error */ }, + "Non-generic functions may not accept type arguments.": { "code": 2159, "category": 1 /* Error */ }, + "A generic type may not reference itself with a wrapped form of its own type parameters.": { "code": 2160, "category": 1 /* Error */ }, + "A rest parameter must be of an array type.": { "code": 2162, "category": 1 /* Error */ }, + "Overload signature implementation cannot use specialized type.": { "code": 2163, "category": 1 /* Error */ }, + "Export assignments may only be used at the top-level of external modules.": { "code": 2164, "category": 1 /* Error */ }, + "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.": { "code": 2165, "category": 1 /* Error */ }, + "Only public methods of the base class are accessible via the 'super' keyword.": { "code": 2166, "category": 1 /* Error */ }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { "code": 2167, "category": 1 /* Error */ }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { "code": 2168, "category": 1 /* Error */ }, + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { "code": 2169, "category": 1 /* Error */ }, + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { "code": 2170, "category": 1 /* Error */ }, + "All named properties must be assignable to string indexer type '{0}'.": { "code": 2171, "category": 1 /* Error */ }, + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { "code": 2172, "category": 1 /* Error */ }, + "A parameter initializer is only allowed in a function or constructor implementation.": { "code": 2174, "category": 1 /* Error */ }, + "Function expression declared a non-void return type, but has no return expression.": { "code": 2176, "category": 1 /* Error */ }, + "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.": { "code": 2177, "category": 1 /* Error */ }, + "Module '{0}' has no exported member '{1}'.": { "code": 2178, "category": 1 /* Error */ }, + "Unable to resolve module reference '{0}'.": { "code": 2179, "category": 1 /* Error */ }, + "Could not find module '{0}' in module '{1}'.": { "code": 2180, "category": 1 /* Error */ }, + "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.": { "code": 2181, "category": 1 /* Error */ }, + "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.": { "code": 2182, "category": 1 /* Error */ }, + "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.": { "code": 2183, "category": 1 /* Error */ }, + "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.": { "code": 2184, "category": 1 /* Error */ }, + "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.": { "code": 2185, "category": 1 /* Error */ }, + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { "code": 2186, "category": 1 /* Error */ }, + "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.": { "code": 2187, "category": 1 /* Error */ }, + "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.": { "code": 2188, "category": 1 /* Error */ }, + "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}": { "code": 2189, "category": 1 /* Error */ }, + "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.": { "code": 2190, "category": 1 /* Error */ }, + "Ambient external module declaration cannot be reopened.": { "code": 2191, "category": 1 /* Error */ }, + "All declarations of merged declaration '{0}' must be exported or not exported.": { "code": 2192, "category": 1 /* Error */ }, + "'super' cannot be referenced in constructor arguments.": { "code": 2193, "category": 1 /* Error */ }, + "Return type of constructor signature must be assignable to the instance type of the class.": { "code": 2194, "category": 1 /* Error */ }, + "Ambient external module declaration must be defined in global context.": { "code": 2195, "category": 1 /* Error */ }, + "Ambient external module declaration cannot specify relative module name.": { "code": 2196, "category": 1 /* Error */ }, + "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.": { "code": 2197, "category": 1 /* Error */ }, + "No best common type exists among return expressions.": { "code": 2198, "category": 1 /* Error */ }, + "Import declaration cannot refer to external module reference when --noResolve option is set.": { "code": 2199, "category": 1 /* Error */ }, + "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": { "code": 2200, "category": 1 /* Error */ }, + "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.": { "code": 2205, "category": 1 /* Error */ }, + "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.": { "code": 2206, "category": 1 /* Error */ }, + "Expression resolves to '_super' that compiler uses to capture base class reference.": { "code": 2207, "category": 1 /* Error */ }, + "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { "code": 2208, "category": 1 /* Error */ }, + "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { "code": 2209, "category": 1 /* Error */ }, + "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.": { "code": 2210, "category": 1 /* Error */ }, + "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.": { "code": 2211, "category": 1 /* Error */ }, + "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.": { "code": 2212, "category": 1 /* Error */ }, + "TypeParameter '{0}' of exported function has or is using private type '{1}'.": { "code": 2213, "category": 1 /* Error */ }, + "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { "code": 2214, "category": 1 /* Error */ }, + "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}": { "code": 2215, "category": 1 /* Error */ }, + "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.": { "code": 2216, "category": 1 /* Error */ }, + "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.": { "code": 2217, "category": 1 /* Error */ }, + "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.": { "code": 2218, "category": 1 /* Error */ }, + "TypeParameter '{0}' of exported function is using inaccessible module {1}.": { "code": 2219, "category": 1 /* Error */ }, + "TypeParameter '{0}' of exported class has or is using private type '{1}'.": { "code": 2220, "category": 1 /* Error */ }, + "TypeParameter '{0}' of exported interface has or is using private type '{1}'.": { "code": 2221, "category": 1 /* Error */ }, + "TypeParameter '{0}' of exported class is using inaccessible module {1}.": { "code": 2222, "category": 1 /* Error */ }, + "TypeParameter '{0}' of exported interface is using inaccessible module {1}.": { "code": 2223, "category": 1 /* Error */ }, + "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.": { "code": 2224, "category": 1 /* Error */ }, + "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.": { "code": 2225, "category": 1 /* Error */ }, + "No best common type exists between '{0}' and '{1}'.": { "code": 2226, "category": 1 /* Error */ }, + "No best common type exists between '{0}', '{1}', and '{2}'.": { "code": 2227, "category": 1 /* Error */ }, + "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.": { "code": 2228, "category": 1 /* Error */ }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { "code": 2229, "category": 1 /* Error */ }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { "code": 2230, "category": 1 /* Error */ }, + "Parameter '{0}' cannot be referenced in its initializer.": { "code": 2231, "category": 1 /* Error */ }, + "Duplicate string index signature.": { "code": 2232, "category": 1 /* Error */ }, + "Duplicate number index signature.": { "code": 2233, "category": 1 /* Error */ }, + "All declarations of an interface must have identical type parameters.": { "code": 2234, "category": 1 /* Error */ }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { "code": 2235, "category": 1 /* Error */ }, + "Neither type '{0}' nor type '{1}' is assignable to the other.": { "code": 2236, "category": 1 /* Error */ }, + "Neither type '{0}' nor type '{1}' is assignable to the other:{NL}{2}": { "code": 2237, "category": 1 /* Error */ }, + "Duplicate function implementation.": { "code": 2237, "category": 1 /* Error */ }, + "Function implementation expected.": { "code": 2238, "category": 1 /* Error */ }, + "Function overload name must be '{0}'.": { "code": 2239, "category": 1 /* Error */ }, + "Constructor implementation expected.": { "code": 2240, "category": 1 /* Error */ }, + "Class name cannot be '{0}'.": { "code": 2241, "category": 1 /* Error */ }, + "Interface name cannot be '{0}'.": { "code": 2242, "category": 1 /* Error */ }, + "Enum name cannot be '{0}'.": { "code": 2243, "category": 1 /* Error */ }, + "A module cannot have multiple export assignments.": { "code": 2244, "category": 1 /* Error */ }, + "Export assignment not allowed in module with exported element.": { "code": 2245, "category": 1 /* Error */ }, + "A parameter property is only allowed in a constructor implementation.": { "code": 2246, "category": 1 /* Error */ }, + "Function overload must be static.": { "code": 2247, "category": 1 /* Error */ }, + "Function overload must not be static.": { "code": 2248, "category": 1 /* Error */ }, + "Type '{0}' is missing property '{1}' from type '{2}'.": { "code": 4000, "category": 3 /* NoPrefix */ }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible.": { "code": 4001, "category": 3 /* NoPrefix */ }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}": { "code": 4002, "category": 3 /* NoPrefix */ }, + "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { "code": 4003, "category": 3 /* NoPrefix */ }, + "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { "code": 4004, "category": 3 /* NoPrefix */ }, + "Types '{0}' and '{1}' define property '{2}' as private.": { "code": 4005, "category": 3 /* NoPrefix */ }, + "Call signatures of types '{0}' and '{1}' are incompatible.": { "code": 4006, "category": 3 /* NoPrefix */ }, + "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { "code": 4007, "category": 3 /* NoPrefix */ }, + "Type '{0}' requires a call signature, but type '{1}' lacks one.": { "code": 4008, "category": 3 /* NoPrefix */ }, + "Construct signatures of types '{0}' and '{1}' are incompatible.": { "code": 4009, "category": 3 /* NoPrefix */ }, + "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { "code": 4010, "category": 3 /* NoPrefix */ }, + "Type '{0}' requires a construct signature, but type '{1}' lacks one.": { "code": 4011, "category": 3 /* NoPrefix */ }, + "Index signatures of types '{0}' and '{1}' are incompatible.": { "code": 4012, "category": 3 /* NoPrefix */ }, + "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { "code": 4013, "category": 3 /* NoPrefix */ }, + "Call signature expects {0} or fewer parameters.": { "code": 4014, "category": 3 /* NoPrefix */ }, + "Could not apply type '{0}' to argument {1} which is of type '{2}'.": { "code": 4015, "category": 3 /* NoPrefix */ }, + "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.": { "code": 4016, "category": 3 /* NoPrefix */ }, + "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": { "code": 4017, "category": 3 /* NoPrefix */ }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.": { "code": 4018, "category": 3 /* NoPrefix */ }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": { "code": 4019, "category": 3 /* NoPrefix */ }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.": { "code": 4020, "category": 3 /* NoPrefix */ }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}": { "code": 4021, "category": 3 /* NoPrefix */ }, + "Type reference cannot refer to container '{0}'.": { "code": 4022, "category": 1 /* Error */ }, + "Type reference must refer to type.": { "code": 4023, "category": 1 /* Error */ }, + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { "code": 4024, "category": 1 /* Error */ }, + " (+ {0} overload(s))": { "code": 4025, "category": 2 /* Message */ }, + "Variable declaration cannot have the same name as an import declaration.": { "code": 4026, "category": 1 /* Error */ }, + "Signature expected {0} type arguments, got {1} instead.": { "code": 4027, "category": 1 /* Error */ }, + "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.": { "code": 4028, "category": 3 /* NoPrefix */ }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { "code": 4029, "category": 3 /* NoPrefix */ }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { "code": 4030, "category": 3 /* NoPrefix */ }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { "code": 4031, "category": 3 /* NoPrefix */ }, + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { "code": 4032, "category": 3 /* NoPrefix */ }, + "Types of string indexer of types '{0}' and '{1}' are not identical.": { "code": 4033, "category": 3 /* NoPrefix */ }, + "Types of number indexer of types '{0}' and '{1}' are not identical.": { "code": 4034, "category": 3 /* NoPrefix */ }, + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { "code": 4035, "category": 3 /* NoPrefix */ }, + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { "code": 4036, "category": 3 /* NoPrefix */ }, + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { "code": 4037, "category": 3 /* NoPrefix */ }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { "code": 4038, "category": 3 /* NoPrefix */ }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { "code": 4039, "category": 3 /* NoPrefix */ }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { "code": 4040, "category": 3 /* NoPrefix */ }, + "Current host does not support '{0}' option.": { "code": 5001, "category": 1 /* Error */ }, + "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'": { "code": 5002, "category": 1 /* Error */ }, + "Argument for '{0}' option must be '{1}' or '{2}'": { "code": 5003, "category": 1 /* Error */ }, + "Could not find file: '{0}'.": { "code": 5004, "category": 1 /* Error */ }, + "A file cannot have a reference to itself.": { "code": 5006, "category": 1 /* Error */ }, + "Cannot resolve referenced file: '{0}'.": { "code": 5007, "category": 1 /* Error */ }, + "Cannot find the common subdirectory path for the input files.": { "code": 5009, "category": 1 /* Error */ }, + "Emit Error: {0}.": { "code": 5011, "category": 1 /* Error */ }, + "Cannot read file '{0}': {1}": { "code": 5012, "category": 1 /* Error */ }, + "Unsupported file encoding.": { "code": 5013, "category": 3 /* NoPrefix */ }, + "Locale must be of the form or -. For example '{0}' or '{1}'.": { "code": 5014, "category": 1 /* Error */ }, + "Unsupported locale: '{0}'.": { "code": 5015, "category": 1 /* Error */ }, + "Execution Failed.{NL}": { "code": 5016, "category": 1 /* Error */ }, + "Invalid call to 'up'": { "code": 5019, "category": 1 /* Error */ }, + "Invalid call to 'down'": { "code": 5020, "category": 1 /* Error */ }, + "Base64 value '{0}' finished with a continuation bit.": { "code": 5021, "category": 1 /* Error */ }, + "Unknown compiler option '{0}'": { "code": 5023, "category": 1 /* Error */ }, + "Expected {0} arguments to message, got {1} instead.": { "code": 5024, "category": 1 /* Error */ }, + "Expected the message '{0}' to have {1} arguments, but it had {2}": { "code": 5025, "category": 1 /* Error */ }, + "Could not delete file '{0}'": { "code": 5034, "category": 1 /* Error */ }, + "Could not create directory '{0}'": { "code": 5035, "category": 1 /* Error */ }, + "Error while executing file '{0}': ": { "code": 5036, "category": 1 /* Error */ }, + "Cannot compile external modules unless the '--module' flag is provided.": { "code": 5037, "category": 1 /* Error */ }, + "Option mapRoot cannot be specified without specifying sourcemap option.": { "code": 5038, "category": 1 /* Error */ }, + "Option sourceRoot cannot be specified without specifying sourcemap option.": { "code": 5039, "category": 1 /* Error */ }, + "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.": { "code": 5040, "category": 1 /* Error */ }, + "Option '{0}' specified without '{1}'": { "code": 5041, "category": 1 /* Error */ }, + "'codepage' option not supported on current platform.": { "code": 5042, "category": 1 /* Error */ }, + "Concatenate and emit output to single file.": { "code": 6001, "category": 2 /* Message */ }, + "Generates corresponding {0} file.": { "code": 6002, "category": 2 /* Message */ }, + "Specifies the location where debugger should locate map files instead of generated locations.": { "code": 6003, "category": 2 /* Message */ }, + "Specifies the location where debugger should locate TypeScript files instead of source locations.": { "code": 6004, "category": 2 /* Message */ }, + "Watch input files.": { "code": 6005, "category": 2 /* Message */ }, + "Redirect output structure to the directory.": { "code": 6006, "category": 2 /* Message */ }, + "Do not emit comments to output.": { "code": 6009, "category": 2 /* Message */ }, + "Skip resolution and preprocessing.": { "code": 6010, "category": 2 /* Message */ }, + "Specify ECMAScript target version: '{0}' (default), or '{1}'": { "code": 6015, "category": 2 /* Message */ }, + "Specify module code generation: '{0}' or '{1}'": { "code": 6016, "category": 2 /* Message */ }, + "Print this message.": { "code": 6017, "category": 2 /* Message */ }, + "Print the compiler's version: {0}": { "code": 6019, "category": 2 /* Message */ }, + "Allow use of deprecated '{0}' keyword when referencing an external module.": { "code": 6021, "category": 2 /* Message */ }, + "Specify locale for errors and messages. For example '{0}' or '{1}'": { "code": 6022, "category": 2 /* Message */ }, + "Syntax: {0}": { "code": 6023, "category": 2 /* Message */ }, + "options": { "code": 6024, "category": 2 /* Message */ }, + "file1": { "code": 6025, "category": 2 /* Message */ }, + "Examples:": { "code": 6026, "category": 2 /* Message */ }, + "Options:": { "code": 6027, "category": 2 /* Message */ }, + "Insert command line options and files from a file.": { "code": 6030, "category": 2 /* Message */ }, + "Version {0}": { "code": 6029, "category": 2 /* Message */ }, + "Use the '{0}' flag to see options.": { "code": 6031, "category": 2 /* Message */ }, + "{NL}Recompiling ({0}):": { "code": 6032, "category": 2 /* Message */ }, + "STRING": { "code": 6033, "category": 2 /* Message */ }, + "KIND": { "code": 6034, "category": 2 /* Message */ }, + "file2": { "code": 6035, "category": 2 /* Message */ }, + "VERSION": { "code": 6036, "category": 2 /* Message */ }, + "LOCATION": { "code": 6037, "category": 2 /* Message */ }, + "DIRECTORY": { "code": 6038, "category": 2 /* Message */ }, + "NUMBER": { "code": 6039, "category": 2 /* Message */ }, + "Specify the codepage to use when opening source files.": { "code": 6040, "category": 2 /* Message */ }, + "Additional locations:": { "code": 6041, "category": 2 /* Message */ }, + "This version of the Javascript runtime does not support the '{0}' function.": { "code": 7000, "category": 1 /* Error */ }, + "Unknown rule.": { "code": 7002, "category": 1 /* Error */ }, + "Invalid line number ({0})": { "code": 7003, "category": 1 /* Error */ }, + "Warn on expressions and declarations with an implied 'any' type.": { "code": 7004, "category": 2 /* Message */ }, + "Variable '{0}' implicitly has an 'any' type.": { "code": 7005, "category": 1 /* Error */ }, + "Parameter '{0}' of '{1}' implicitly has an 'any' type.": { "code": 7006, "category": 1 /* Error */ }, + "Parameter '{0}' of function type implicitly has an 'any' type.": { "code": 7007, "category": 1 /* Error */ }, + "Member '{0}' of object type implicitly has an 'any' type.": { "code": 7008, "category": 1 /* Error */ }, + "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.": { "code": 7009, "category": 1 /* Error */ }, + "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.": { "code": 7010, "category": 1 /* Error */ }, + "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.": { "code": 7011, "category": 1 /* Error */ }, + "Parameter '{0}' of lambda function implicitly has an 'any' type.": { "code": 7012, "category": 1 /* Error */ }, + "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.": { "code": 7013, "category": 1 /* Error */ }, + "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.": { "code": 7014, "category": 1 /* Error */ }, + "Array Literal implicitly has an 'any' type from widening.": { "code": 7015, "category": 1 /* Error */ }, + "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { "code": 7016, "category": 1 /* Error */ }, + "Index signature of object type implicitly has an 'any' type.": { "code": 7017, "category": 1 /* Error */ }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { "code": 7018, "category": 1 /* Error */ } + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + if (array1 === null || array2 === null) { + return false; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + return true; + }; + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + return false; + }; + ArrayUtilities.distinct = function (array, equalsFn) { + var result = []; + for (var i = 0, n = array.length; i < n; i++) { + var current = array[i]; + for (var j = 0; j < result.length; j++) { + if (equalsFn(result[j], current)) { + break; + } + } + if (j === result.length) { + result.push(current); + } + } + return result; + }; + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + return array[array.length - 1]; + }; + ArrayUtilities.lastOrDefault = function (array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var v = array[i]; + if (predicate(v, i)) { + return v; + } + } + return null; + }; + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value, i)) { + return value; + } + } + return null; + }; + ArrayUtilities.first = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (!func || func(value, i)) { + return value; + } + } + throw TypeScript.Errors.invalidOperation(); + }; + ArrayUtilities.sum = function (array, func) { + var result = 0; + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + return result; + }; + ArrayUtilities.select = function (values, func) { + var result = new Array(values.length); + for (var i = 0; i < values.length; i++) { + result[i] = func(values[i]); + } + return result; + }; + ArrayUtilities.where = function (values, func) { + var result = new Array(); + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + return result; + }; + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + return false; + }; + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + return true; + }; + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + if (midValue === value) { + return middle; + } + else if (midValue > value) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + }; + ArrayUtilities.createArray = function (length, defaultValue) { + var result = new Array(length); + for (var i = 0; i < length; i++) { + result[i] = defaultValue; + } + return result; + }; + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + ArrayUtilities.indexOf = function (array, predicate) { + for (var i = 0, n = array.length; i < n; i++) { + if (predicate(array[i])) { + return i; + } + } + return -1; + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(TypeScript.AssertionLevel || (TypeScript.AssertionLevel = {})); + var AssertionLevel = TypeScript.AssertionLevel; + var Debug = (function () { + function Debug() { + } + Debug.shouldAssert = function (level) { + return this.currentAssertionLevel >= level; + }; + Debug.assert = function (expression, message, verboseDebugInfo) { + if (message === void 0) { message = ""; } + if (verboseDebugInfo === void 0) { verboseDebugInfo = null; } + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information:" + verboseDebugInfo(); + } + throw new Error("Debug Failure. False expression: " + message + verboseDebugString); + } + }; + Debug.fail = function (message) { + Debug.assert(false, message); + }; + Debug.currentAssertionLevel = 0 /* None */; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + TypeScript.LocalizedDiagnosticMessages = null; + var Location = (function () { + function Location(fileName, lineMap, start, length) { + this._fileName = fileName; + this._lineMap = lineMap; + this._start = start; + this._length = length; + } + Location.prototype.fileName = function () { + return this._fileName; + }; + Location.prototype.lineMap = function () { + return this._lineMap; + }; + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + Location.prototype.start = function () { + return this._start; + }; + Location.prototype.length = function () { + return this._length; + }; + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (_arguments === void 0) { _arguments = null; } + if (additionalLocations === void 0) { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + result.diagnosticCode = this._diagnosticKey; + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; + } + return result; + }; + Diagnostic.prototype.diagnosticKey = function () { + return this._diagnosticKey; + }; + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + Diagnostic.prototype.text = function () { + return TypeScript.getLocalizedText(this._diagnosticKey, this._arguments); + }; + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticKey, this._arguments); + }; + Diagnostic.prototype.additionalLocations = function () { + return this._additionalLocations || []; + }; + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { return v1 === v2; }); + }; + Diagnostic.prototype.info = function () { + return getDiagnosticInfoFromKey(this.diagnosticKey()); + }; + return Diagnostic; + })(Location); + TypeScript.Diagnostic = Diagnostic; + function newLine() { + return sys.newLine ? sys.newLine : "\r\n"; + } + TypeScript.newLine = newLine; + function getLargestIndex(diagnostic) { + var largest = -1; + var regex = /\{(\d+)\}/g; + var match; + while (match = regex.exec(diagnostic)) { + var val = parseInt(match[1]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + return largest; + } + function getDiagnosticInfoFromKey(diagnosticKey) { + var result = TypeScript.diagnosticInformationMap[diagnosticKey]; + TypeScript.Debug.assert(result); + return result; + } + function getLocalizedText(diagnosticKey, args) { + var diagnosticMessageText = diagnosticKey; + TypeScript.Debug.assert(diagnosticMessageText !== undefined && diagnosticMessageText !== null); + var actualCount = args ? args.length : 0; + var expectedCount = 1 + getLargestIndex(diagnosticKey); + if (expectedCount !== actualCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_0_arguments_to_message_got_1_instead, [expectedCount, actualCount])); + } + var valueCount = 1 + getLargestIndex(diagnosticMessageText); + if (valueCount !== expectedCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_the_message_0_to_have_1_arguments_but_it_had_2, [diagnosticMessageText, expectedCount, valueCount])); + } + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return TypeScript.newLine(); + }); + return diagnosticMessageText; + } + TypeScript.getLocalizedText = getLocalizedText; + function getDiagnosticMessage(diagnosticKey, args) { + var diagnostic = getDiagnosticInfoFromKey(diagnosticKey); + var diagnosticMessageText = getLocalizedText(diagnosticKey, args); + var message; + if (diagnostic.category === 1 /* Error */) { + message = getLocalizedText(TypeScript.DiagnosticCode.error_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } + else if (diagnostic.category === 0 /* Warning */) { + message = getLocalizedText(TypeScript.DiagnosticCode.warning_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } + else { + message = diagnosticMessageText; + } + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + ". " + message); + }; + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument); + }; + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument); + }; + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + Errors.invalidOperation = function (message) { + return new Error("Invalid operation: " + message); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + for (var i = start; i < end; i++) { + hashCode = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(hashCode ^ text[i], Hash.FNV_PRIME); + } + return hashCode; + }; + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + return hash & 0x7FFFFFFF; + }; + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + var start = 0; + var len = key.length; + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + return hash & 0x7FFFFFFF; + }; + Hash.computeMurmur2StringHashCode = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + var k = Math.abs(c1 | (c2 << 16)); + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + index += 2; + numberOfCharsLeft -= 2; + } + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + return h; + }; + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (IntegerUtilities) { + function integerDivide(numerator, denominator) { + return (numerator / denominator) >> 0; + } + IntegerUtilities.integerDivide = integerDivide; + function integerMultiplyLow32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + } + IntegerUtilities.integerMultiplyLow32Bits = integerMultiplyLow32Bits; + function isInteger(text) { + return /^[0-9]+$/.test(text); + } + IntegerUtilities.isInteger = isInteger; + function isHexInteger(text) { + return /^0(x|X)[0-9a-fA-F]+$/.test(text); + } + IntegerUtilities.isHexInteger = isHexInteger; + })(TypeScript.IntegerUtilities || (TypeScript.IntegerUtilities = {})); + var IntegerUtilities = TypeScript.IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_computeLineStarts, length) { + this._computeLineStarts = _computeLineStarts; + this.length = length; + this._lineStarts = null; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this.lineStarts(), length: this.length }; + }; + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { return v1 === v2; }); + }; + LineMap.prototype.lineStarts = function () { + if (this._lineStarts === null) { + this._lineStarts = this._computeLineStarts(); + } + return this._lineStarts; + }; + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + if (position === this.length) { + return this.lineCount() - 1; + } + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + return lineNumber; + }; + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + var lineNumber = this.getLineNumberFromPosition(position); + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + LineMap.empty = new LineMap(function () { return [0]; }, 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + this._lineStartPositions = null; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getLineStartPositions = function () { + if (!this._lineStartPositions) { + this._lineStartPositions = TypeScript.TextUtilities.parseLineStarts(this.text); + } + return this._lineStartPositions; + }; + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LineMap1) { + function fromSimpleText(text) { + return new TypeScript.LineMap(function () { return TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { return text.charCodeAt(index); }, length: text.length() }); }, text.length()); + } + LineMap1.fromSimpleText = fromSimpleText; + function fromScriptSnapshot(scriptSnapshot) { + return new TypeScript.LineMap(function () { return scriptSnapshot.getLineStartPositions(); }, scriptSnapshot.getLength()); + } + LineMap1.fromScriptSnapshot = fromScriptSnapshot; + function fromString(text) { + return new TypeScript.LineMap(function () { return TypeScript.TextUtilities.parseLineStarts(text); }, text.length); + } + LineMap1.fromString = fromString; + })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); + var LineMap1 = TypeScript.LineMap1; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + this._lineMap = null; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + SimpleStringText.prototype.substr = function (start, length) { + return this.value.substr(start, length); + }; + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + SimpleStringText.prototype.lineMap = function () { + if (!this._lineMap) { + this._lineMap = TypeScript.LineMap1.fromString(this.value); + } + return this._lineMap; + }; + return SimpleStringText; + })(); + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + this._lineMap = null; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + SimpleScriptSnapshotText.prototype.substr = function (start, length) { + return this.scriptSnapshot.getText(start, start + length); + }; + SimpleScriptSnapshotText.prototype.lineMap = function () { + var _this = this; + if (this._lineMap === null) { + this._lineMap = new TypeScript.LineMap(function () { return _this.scriptSnapshot.getLineStartPositions(); }, this.length()); + } + return this._lineMap; + }; + return SimpleScriptSnapshotText; + })(); + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length; + if (0 === length) { + var result = new Array(); + result.push(0); + return result; + } + var position = 0; + var index = 0; + var arrayBuilder = new Array(); + var lineNumber = 0; + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } + else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } + else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } + else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + if (0 === lineBreakLength) { + index++; + } + else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + arrayBuilder.push(position); + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } + else if (isAnyLineBreakCharacter(c)) { + return 1; + } + else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + if (length < 0) { + TypeScript.Errors.argument("length"); + } + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + TextSpan.prototype.length = function () { + return this._length; + }; + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = Math.max(this._start, span._start); + var overlapEnd = Math.min(this.end(), span.end()); + return overlapStart < overlapEnd; + }; + TextSpan.prototype.overlap = function (span) { + var overlapStart = Math.max(this._start, span._start); + var overlapEnd = Math.min(this.end(), span.end()); + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + return null; + }; + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + TextSpan.prototype.intersection = function (span) { + var intersectStart = Math.max(this._start, span._start); + var intersectEnd = Math.min(this.end(), span.end()); + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + return null; + }; + TextSpan.fromBounds = function (start, end) { + TypeScript.Debug.assert(start >= 0); + TypeScript.Debug.assert(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + if (changes.length === 1) { + return changes[0]; + } + var change0 = changes[0]; + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterInfo) { + function isDecimalDigit(c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + } + CharacterInfo.isDecimalDigit = isDecimalDigit; + function isOctalDigit(c) { + return c >= 48 /* _0 */ && c <= 55 /* _7 */; + } + CharacterInfo.isOctalDigit = isOctalDigit; + function isHexDigit(c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + } + CharacterInfo.isHexDigit = isHexDigit; + function hexValue(c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + } + CharacterInfo.hexValue = hexValue; + function isWhitespace(ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + return false; + } + CharacterInfo.isWhitespace = isWhitespace; + function isLineTerminator(ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + return false; + } + CharacterInfo.isLineTerminator = isLineTerminator; + })(TypeScript.CharacterInfo || (TypeScript.CharacterInfo = {})); + var CharacterInfo = TypeScript.CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["None"] = 0] = "None"; + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; + })(); + TypeScript.FormattingOptions = FormattingOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 62] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 63] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 64] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 65] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 66] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 67] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 68] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 69] = "StringKeyword"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 70] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 71] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 72] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 73] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 74] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 75] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 76] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 77] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 78] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 79] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 80] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 81] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 82] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 83] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 84] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 85] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 86] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 87] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 88] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 89] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 90] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 91] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 92] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 93] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 94] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 95] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 96] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 98] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 99] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 100] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 101] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 102] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 103] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 104] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 105] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 106] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 107] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 108] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 109] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 110] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 111] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 112] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 113] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 115] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 116] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 117] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 118] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 119] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["SourceUnit"] = 120] = "SourceUnit"; + SyntaxKind[SyntaxKind["QualifiedName"] = 121] = "QualifiedName"; + SyntaxKind[SyntaxKind["ObjectType"] = 122] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 123] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 124] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 125] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 126] = "GenericType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 127] = "TypeQuery"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["IndexMemberDeclaration"] = 138] = "IndexMemberDeclaration"; + SyntaxKind[SyntaxKind["GetAccessor"] = 139] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 140] = "SetAccessor"; + SyntaxKind[SyntaxKind["PropertySignature"] = 141] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 142] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 143] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 144] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 145] = "MethodSignature"; + SyntaxKind[SyntaxKind["Block"] = 146] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 147] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 148] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 149] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 150] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 151] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 152] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 153] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 154] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 155] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 156] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 157] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 158] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 159] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 160] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 161] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 162] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 163] = "WithStatement"; + SyntaxKind[SyntaxKind["PlusExpression"] = 164] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 165] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 166] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 167] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 168] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 169] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 170] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 171] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 172] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 173] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 174] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 175] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 176] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 177] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 178] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 179] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 180] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 181] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 182] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 183] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 184] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 185] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 187] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 188] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 189] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 190] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 191] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 192] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 193] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 194] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 195] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 196] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 197] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 198] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 199] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 200] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 201] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 202] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 203] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 204] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 205] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 206] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 207] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 208] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 209] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 210] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 211] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 212] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 213] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 214] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 215] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 216] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 218] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 219] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 220] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 221] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 222] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 224] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 225] = "VariableDeclarator"; + SyntaxKind[SyntaxKind["ArgumentList"] = 226] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 227] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 228] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 229] = "TypeParameterList"; + SyntaxKind[SyntaxKind["ExtendsHeritageClause"] = 230] = "ExtendsHeritageClause"; + SyntaxKind[SyntaxKind["ImplementsHeritageClause"] = 231] = "ImplementsHeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 232] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 233] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 234] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 235] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 236] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 237] = "FinallyClause"; + SyntaxKind[SyntaxKind["TypeParameter"] = 238] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 239] = "Constraint"; + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 240] = "SimplePropertyAssignment"; + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + SyntaxKind[SyntaxKind["FirstTrivia"] = SyntaxKind.WhitespaceTrivia] = "FirstTrivia"; + SyntaxKind[SyntaxKind["LastTrivia"] = SyntaxKind.SkippedTokenTrivia] = "LastTrivia"; + SyntaxKind[SyntaxKind["FirstNode"] = SyntaxKind.SourceUnit] = "FirstNode"; + SyntaxKind[SyntaxKind["LastNode"] = SyntaxKind.ModuleNameModuleReference] = "LastNode"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 62 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 63 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 64 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 65 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 67 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 66 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 68 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 69 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 70 /* OpenBraceToken */, + "}": 71 /* CloseBraceToken */, + "(": 72 /* OpenParenToken */, + ")": 73 /* CloseParenToken */, + "[": 74 /* OpenBracketToken */, + "]": 75 /* CloseBracketToken */, + ".": 76 /* DotToken */, + "...": 77 /* DotDotDotToken */, + ";": 78 /* SemicolonToken */, + ",": 79 /* CommaToken */, + "<": 80 /* LessThanToken */, + ">": 81 /* GreaterThanToken */, + "<=": 82 /* LessThanEqualsToken */, + ">=": 83 /* GreaterThanEqualsToken */, + "==": 84 /* EqualsEqualsToken */, + "=>": 85 /* EqualsGreaterThanToken */, + "!=": 86 /* ExclamationEqualsToken */, + "===": 87 /* EqualsEqualsEqualsToken */, + "!==": 88 /* ExclamationEqualsEqualsToken */, + "+": 89 /* PlusToken */, + "-": 90 /* MinusToken */, + "*": 91 /* AsteriskToken */, + "%": 92 /* PercentToken */, + "++": 93 /* PlusPlusToken */, + "--": 94 /* MinusMinusToken */, + "<<": 95 /* LessThanLessThanToken */, + ">>": 96 /* GreaterThanGreaterThanToken */, + ">>>": 97 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 98 /* AmpersandToken */, + "|": 99 /* BarToken */, + "^": 100 /* CaretToken */, + "!": 101 /* ExclamationToken */, + "~": 102 /* TildeToken */, + "&&": 103 /* AmpersandAmpersandToken */, + "||": 104 /* BarBarToken */, + "?": 105 /* QuestionToken */, + ":": 106 /* ColonToken */, + "=": 107 /* EqualsToken */, + "+=": 108 /* PlusEqualsToken */, + "-=": 109 /* MinusEqualsToken */, + "*=": 110 /* AsteriskEqualsToken */, + "%=": 111 /* PercentEqualsToken */, + "<<=": 112 /* LessThanLessThanEqualsToken */, + ">>=": 113 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 115 /* AmpersandEqualsToken */, + "|=": 116 /* BarEqualsToken */, + "^=": 117 /* CaretEqualsToken */, + "/": 118 /* SlashToken */, + "/=": 119 /* SlashEqualsToken */ + }; + var kindToText = new Array(); + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + kindToText[62 /* ConstructorKeyword */] = "constructor"; + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + function isAnyKeyword(kind) { + return kind >= TypeScript.SyntaxKind.FirstKeyword && kind <= TypeScript.SyntaxKind.LastKeyword; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + function isAnyPunctuation(kind) { + return kind >= TypeScript.SyntaxKind.FirstPunctuation && kind <= TypeScript.SyntaxKind.LastPunctuation; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 89 /* PlusToken */: + return 164 /* PlusExpression */; + case 90 /* MinusToken */: + return 165 /* NegateExpression */; + case 102 /* TildeToken */: + return 166 /* BitwiseNotExpression */; + case 101 /* ExclamationToken */: + return 167 /* LogicalNotExpression */; + case 93 /* PlusPlusToken */: + return 168 /* PreIncrementExpression */; + case 94 /* MinusMinusToken */: + return 169 /* PreDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 93 /* PlusPlusToken */: + return 210 /* PostIncrementExpression */; + case 94 /* MinusMinusToken */: + return 211 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 91 /* AsteriskToken */: + return 205 /* MultiplyExpression */; + case 118 /* SlashToken */: + return 206 /* DivideExpression */; + case 92 /* PercentToken */: + return 207 /* ModuloExpression */; + case 89 /* PlusToken */: + return 208 /* AddExpression */; + case 90 /* MinusToken */: + return 209 /* SubtractExpression */; + case 95 /* LessThanLessThanToken */: + return 202 /* LeftShiftExpression */; + case 96 /* GreaterThanGreaterThanToken */: + return 203 /* SignedRightShiftExpression */; + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + return 204 /* UnsignedRightShiftExpression */; + case 80 /* LessThanToken */: + return 196 /* LessThanExpression */; + case 81 /* GreaterThanToken */: + return 197 /* GreaterThanExpression */; + case 82 /* LessThanEqualsToken */: + return 198 /* LessThanOrEqualExpression */; + case 83 /* GreaterThanEqualsToken */: + return 199 /* GreaterThanOrEqualExpression */; + case 30 /* InstanceOfKeyword */: + return 200 /* InstanceOfExpression */; + case 29 /* InKeyword */: + return 201 /* InExpression */; + case 84 /* EqualsEqualsToken */: + return 192 /* EqualsWithTypeConversionExpression */; + case 86 /* ExclamationEqualsToken */: + return 193 /* NotEqualsWithTypeConversionExpression */; + case 87 /* EqualsEqualsEqualsToken */: + return 194 /* EqualsExpression */; + case 88 /* ExclamationEqualsEqualsToken */: + return 195 /* NotEqualsExpression */; + case 98 /* AmpersandToken */: + return 191 /* BitwiseAndExpression */; + case 100 /* CaretToken */: + return 190 /* BitwiseExclusiveOrExpression */; + case 99 /* BarToken */: + return 189 /* BitwiseOrExpression */; + case 103 /* AmpersandAmpersandToken */: + return 188 /* LogicalAndExpression */; + case 104 /* BarBarToken */: + return 187 /* LogicalOrExpression */; + case 116 /* BarEqualsToken */: + return 182 /* OrAssignmentExpression */; + case 115 /* AmpersandEqualsToken */: + return 180 /* AndAssignmentExpression */; + case 117 /* CaretEqualsToken */: + return 181 /* ExclusiveOrAssignmentExpression */; + case 112 /* LessThanLessThanEqualsToken */: + return 183 /* LeftShiftAssignmentExpression */; + case 113 /* GreaterThanGreaterThanEqualsToken */: + return 184 /* SignedRightShiftAssignmentExpression */; + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 185 /* UnsignedRightShiftAssignmentExpression */; + case 108 /* PlusEqualsToken */: + return 175 /* AddAssignmentExpression */; + case 109 /* MinusEqualsToken */: + return 176 /* SubtractAssignmentExpression */; + case 110 /* AsteriskEqualsToken */: + return 177 /* MultiplyAssignmentExpression */; + case 119 /* SlashEqualsToken */: + return 178 /* DivideAssignmentExpression */; + case 111 /* PercentEqualsToken */: + return 179 /* ModuloAssignmentExpression */; + case 107 /* EqualsToken */: + return 174 /* AssignmentExpression */; + case 79 /* CommaToken */: + return 173 /* CommaExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + function getOperatorTokenFromBinaryExpression(tokenKind) { + switch (tokenKind) { + case 205 /* MultiplyExpression */: + return 91 /* AsteriskToken */; + case 206 /* DivideExpression */: + return 118 /* SlashToken */; + case 207 /* ModuloExpression */: + return 92 /* PercentToken */; + case 208 /* AddExpression */: + return 89 /* PlusToken */; + case 209 /* SubtractExpression */: + return 90 /* MinusToken */; + case 202 /* LeftShiftExpression */: + return 95 /* LessThanLessThanToken */; + case 203 /* SignedRightShiftExpression */: + return 96 /* GreaterThanGreaterThanToken */; + case 204 /* UnsignedRightShiftExpression */: + return 97 /* GreaterThanGreaterThanGreaterThanToken */; + case 196 /* LessThanExpression */: + return 80 /* LessThanToken */; + case 197 /* GreaterThanExpression */: + return 81 /* GreaterThanToken */; + case 198 /* LessThanOrEqualExpression */: + return 82 /* LessThanEqualsToken */; + case 199 /* GreaterThanOrEqualExpression */: + return 83 /* GreaterThanEqualsToken */; + case 200 /* InstanceOfExpression */: + return 30 /* InstanceOfKeyword */; + case 201 /* InExpression */: + return 29 /* InKeyword */; + case 192 /* EqualsWithTypeConversionExpression */: + return 84 /* EqualsEqualsToken */; + case 193 /* NotEqualsWithTypeConversionExpression */: + return 86 /* ExclamationEqualsToken */; + case 194 /* EqualsExpression */: + return 87 /* EqualsEqualsEqualsToken */; + case 195 /* NotEqualsExpression */: + return 88 /* ExclamationEqualsEqualsToken */; + case 191 /* BitwiseAndExpression */: + return 98 /* AmpersandToken */; + case 190 /* BitwiseExclusiveOrExpression */: + return 100 /* CaretToken */; + case 189 /* BitwiseOrExpression */: + return 99 /* BarToken */; + case 188 /* LogicalAndExpression */: + return 103 /* AmpersandAmpersandToken */; + case 187 /* LogicalOrExpression */: + return 104 /* BarBarToken */; + case 182 /* OrAssignmentExpression */: + return 116 /* BarEqualsToken */; + case 180 /* AndAssignmentExpression */: + return 115 /* AmpersandEqualsToken */; + case 181 /* ExclusiveOrAssignmentExpression */: + return 117 /* CaretEqualsToken */; + case 183 /* LeftShiftAssignmentExpression */: + return 112 /* LessThanLessThanEqualsToken */; + case 184 /* SignedRightShiftAssignmentExpression */: + return 113 /* GreaterThanGreaterThanEqualsToken */; + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + case 175 /* AddAssignmentExpression */: + return 108 /* PlusEqualsToken */; + case 176 /* SubtractAssignmentExpression */: + return 109 /* MinusEqualsToken */; + case 177 /* MultiplyAssignmentExpression */: + return 110 /* AsteriskEqualsToken */; + case 178 /* DivideAssignmentExpression */: + return 119 /* SlashEqualsToken */; + case 179 /* ModuloAssignmentExpression */: + return 111 /* PercentEqualsToken */; + case 174 /* AssignmentExpression */: + return 107 /* EqualsToken */; + case 173 /* CommaExpression */: + return 79 /* CommaToken */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getOperatorTokenFromBinaryExpression = getOperatorTokenFromBinaryExpression; + function isAssignmentOperatorToken(tokenKind) { + switch (tokenKind) { + case 116 /* BarEqualsToken */: + case 115 /* AmpersandEqualsToken */: + case 117 /* CaretEqualsToken */: + case 112 /* LessThanLessThanEqualsToken */: + case 113 /* GreaterThanGreaterThanEqualsToken */: + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 108 /* PlusEqualsToken */: + case 109 /* MinusEqualsToken */: + case 110 /* AsteriskEqualsToken */: + case 119 /* SlashEqualsToken */: + case 111 /* PercentEqualsToken */: + case 107 /* EqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAssignmentOperatorToken = isAssignmentOperatorToken; + function isType(kind) { + switch (kind) { + case 124 /* ArrayType */: + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + case 123 /* FunctionType */: + case 122 /* ObjectType */: + case 125 /* ConstructorType */: + case 127 /* TypeQuery */: + case 126 /* GenericType */: + case 121 /* QualifiedName */: + case 11 /* IdentifierName */: + return true; + } + return false; + } + SyntaxFacts.isType = isType; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Scanner) { + TypeScript.Debug.assert(TypeScript.SyntaxKind.LastToken <= 127); + var ScannerConstants; + (function (ScannerConstants) { + ScannerConstants[ScannerConstants["LargeTokenFullStartShift"] = 2] = "LargeTokenFullStartShift"; + ScannerConstants[ScannerConstants["LargeTokenFullWidthShift"] = 7] = "LargeTokenFullWidthShift"; + ScannerConstants[ScannerConstants["FixedWidthTokenFullStartShift"] = 7] = "FixedWidthTokenFullStartShift"; + ScannerConstants[ScannerConstants["SmallTokenFullWidthShift"] = 7] = "SmallTokenFullWidthShift"; + ScannerConstants[ScannerConstants["SmallTokenFullStartShift"] = 12] = "SmallTokenFullStartShift"; + ScannerConstants[ScannerConstants["KindMask"] = 0x7F] = "KindMask"; + ScannerConstants[ScannerConstants["IsVariableWidthMask"] = 0x80] = "IsVariableWidthMask"; + ScannerConstants[ScannerConstants["LargeTokenLeadingTriviaBitMask"] = 0x01] = "LargeTokenLeadingTriviaBitMask"; + ScannerConstants[ScannerConstants["LargeTokenTrailingTriviaBitMask"] = 0x02] = "LargeTokenTrailingTriviaBitMask"; + ScannerConstants[ScannerConstants["SmallTokenFullWidthMask"] = 0x1F] = "SmallTokenFullWidthMask"; + ScannerConstants[ScannerConstants["FixedWidthTokenMaxFullStart"] = 0x7FFFFF] = "FixedWidthTokenMaxFullStart"; + ScannerConstants[ScannerConstants["SmallTokenMaxFullStart"] = 0x3FFFF] = "SmallTokenMaxFullStart"; + ScannerConstants[ScannerConstants["SmallTokenMaxFullWidth"] = 0x1F] = "SmallTokenMaxFullWidth"; + })(ScannerConstants || (ScannerConstants = {})); + TypeScript.Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(1 << 28, 1, 1)) === (1 << 28)); + TypeScript.Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(3 << 27, 0, 1)) === (3 << 27)); + TypeScript.Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(10 << 25, 1, 0)) === (10 << 25)); + function fixedWidthTokenPackData(fullStart, kind) { + return (fullStart << 7 /* FixedWidthTokenFullStartShift */) | kind; + } + function fixedWidthTokenUnpackFullStart(packedData) { + return packedData >> 7 /* FixedWidthTokenFullStartShift */; + } + function smallTokenPackData(fullStart, fullWidth, kind) { + return (fullStart << 12 /* SmallTokenFullStartShift */) | (fullWidth << 7 /* SmallTokenFullWidthShift */) | kind; + } + function smallTokenUnpackFullWidth(packedData) { + return (packedData >> 7 /* SmallTokenFullWidthShift */) & 31 /* SmallTokenFullWidthMask */; + } + function smallTokenUnpackFullStart(packedData) { + return packedData >> 12 /* SmallTokenFullStartShift */; + } + function largeTokenPackFullStartAndInfo(fullStart, hasLeadingTriviaInfo, hasTrailingTriviaInfo) { + return (fullStart << 2 /* LargeTokenFullStartShift */) | hasLeadingTriviaInfo | hasTrailingTriviaInfo; + } + function largeTokenUnpackFullWidth(packedFullWidthAndKind) { + return packedFullWidthAndKind >> 7 /* LargeTokenFullWidthShift */; + } + function largeTokenUnpackFullStart(packedFullStartAndInfo) { + return packedFullStartAndInfo >> 2 /* LargeTokenFullStartShift */; + } + function largeTokenUnpackHasLeadingTriviaInfo(packed) { + return packed & 1 /* LargeTokenLeadingTriviaBitMask */; + } + function largeTokenUnpackHasTrailingTriviaInfo(packed) { + return packed & 2 /* LargeTokenTrailingTriviaBitMask */; + } + var isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, 0); + var isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if ((character >= 97 /* a */ && character <= 122 /* z */) || (character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } + else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + isIdentifierPartCharacter[character] = true; + } + } + for (var keywordKind = TypeScript.SyntaxKind.FirstKeyword; keywordKind <= TypeScript.SyntaxKind.LastKeyword; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + isKeywordStartCharacter[keyword.charCodeAt(0)] = 1; + } + function isContextualToken(token) { + switch (token.kind()) { + case 12 /* RegularExpressionLiteral */: + case 96 /* GreaterThanGreaterThanToken */: + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + case 83 /* GreaterThanEqualsToken */: + case 113 /* GreaterThanGreaterThanEqualsToken */: + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return true; + default: + return token.isKeywordConvertedToIdentifier(); + } + } + Scanner.isContextualToken = isContextualToken; + var lastTokenInfo = { leadingTriviaWidth: -1, width: -1 }; + var lastTokenInfoTokenID = -1; + var triviaScanner = createScannerInternal(1 /* ES5 */, TypeScript.SimpleText.fromString(""), function () { + }); + function fillSizeInfo(token, text) { + if (lastTokenInfoTokenID !== TypeScript.syntaxID(token)) { + triviaScanner.fillTokenInfo(token, text, lastTokenInfo); + lastTokenInfoTokenID = TypeScript.syntaxID(token); + } + } + function fullText(token, text) { + return text.substr(token.fullStart(), token.fullWidth()); + } + function leadingTrivia(token, text) { + if (!token.hasLeadingTrivia()) { + return TypeScript.Syntax.emptyTriviaList; + } + return triviaScanner.scanTrivia(token, text, false); + } + function trailingTrivia(token, text) { + if (!token.hasTrailingTrivia()) { + return TypeScript.Syntax.emptyTriviaList; + } + return triviaScanner.scanTrivia(token, text, true); + } + function leadingTriviaWidth(token, text) { + if (!token.hasLeadingTrivia()) { + return 0; + } + fillSizeInfo(token, text); + return lastTokenInfo.leadingTriviaWidth; + } + function trailingTriviaWidth(token, text) { + if (!token.hasTrailingTrivia()) { + return 0; + } + fillSizeInfo(token, text); + return token.fullWidth() - lastTokenInfo.leadingTriviaWidth - lastTokenInfo.width; + } + function tokenIsIncrementallyUnusable(token) { + return false; + } + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(_packedData) { + this._packedData = _packedData; + } + FixedWidthTokenWithNoTrivia.prototype.setFullStart = function (fullStart) { + this._packedData = fixedWidthTokenPackData(fullStart, this.kind()); + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isKeywordConvertedToIdentifier = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return TypeScript.SyntaxFacts.getText(this.kind()); + }; + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return this.fullText(); + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return TypeScript.Syntax.emptyTriviaList; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this._packedData & 127 /* KindMask */; + }; + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithNoTrivia.prototype.fullStart = function () { + return fixedWidthTokenUnpackFullStart(this._packedData); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this._packedData); + }; + return FixedWidthTokenWithNoTrivia; + })(); + var LargeScannerToken = (function () { + function LargeScannerToken(_packedFullStartAndInfo, _packedFullWidthAndKind, cachedText) { + this._packedFullStartAndInfo = _packedFullStartAndInfo; + this._packedFullWidthAndKind = _packedFullWidthAndKind; + if (cachedText !== undefined) { + this.cachedText = cachedText; + } + } + LargeScannerToken.prototype.setFullStart = function (fullStart) { + this._packedFullStartAndInfo = largeTokenPackFullStartAndInfo(fullStart, largeTokenUnpackHasLeadingTriviaInfo(this._packedFullStartAndInfo), largeTokenUnpackHasTrailingTriviaInfo(this._packedFullStartAndInfo)); + }; + LargeScannerToken.prototype.syntaxTreeText = function (text) { + var result = text || TypeScript.syntaxTree(this).text; + TypeScript.Debug.assert(result); + return result; + }; + LargeScannerToken.prototype.isIncrementallyUnusable = function () { + return tokenIsIncrementallyUnusable(this); + }; + LargeScannerToken.prototype.isKeywordConvertedToIdentifier = function () { + return false; + }; + LargeScannerToken.prototype.hasSkippedToken = function () { + return false; + }; + LargeScannerToken.prototype.fullText = function (text) { + return fullText(this, this.syntaxTreeText(text)); + }; + LargeScannerToken.prototype.text = function () { + var cachedText = this.cachedText; + return cachedText !== undefined ? cachedText : TypeScript.SyntaxFacts.getText(this.kind()); + }; + LargeScannerToken.prototype.leadingTrivia = function (text) { + return leadingTrivia(this, this.syntaxTreeText(text)); + }; + LargeScannerToken.prototype.trailingTrivia = function (text) { + return trailingTrivia(this, this.syntaxTreeText(text)); + }; + LargeScannerToken.prototype.leadingTriviaWidth = function (text) { + return leadingTriviaWidth(this, this.syntaxTreeText(text)); + }; + LargeScannerToken.prototype.trailingTriviaWidth = function (text) { + return trailingTriviaWidth(this, this.syntaxTreeText(text)); + }; + LargeScannerToken.prototype.kind = function () { + return this._packedFullWidthAndKind & 127 /* KindMask */; + }; + LargeScannerToken.prototype.fullWidth = function () { + return largeTokenUnpackFullWidth(this._packedFullWidthAndKind); + }; + LargeScannerToken.prototype.fullStart = function () { + return largeTokenUnpackFullStart(this._packedFullStartAndInfo); + }; + LargeScannerToken.prototype.hasLeadingTrivia = function () { + return largeTokenUnpackHasLeadingTriviaInfo(this._packedFullStartAndInfo) !== 0; + }; + LargeScannerToken.prototype.hasTrailingTrivia = function () { + return largeTokenUnpackHasTrailingTriviaInfo(this._packedFullStartAndInfo) !== 0; + }; + LargeScannerToken.prototype.clone = function () { + return new LargeScannerToken(this._packedFullStartAndInfo, this._packedFullWidthAndKind, this.cachedText); + }; + return LargeScannerToken; + })(); + function createScanner(languageVersion, text, reportDiagnostic) { + var scanner = createScannerInternal(languageVersion, text, reportDiagnostic); + return { + setIndex: scanner.setIndex, + scan: scanner.scan + }; + } + Scanner.createScanner = createScanner; + function createScannerInternal(languageVersion, text, reportDiagnostic) { + var str; + var index; + var start; + var end; + function setIndex(_index) { + index = _index; + } + function reset(_text, _start, _end) { + TypeScript.Debug.assert(_start <= _text.length()); + TypeScript.Debug.assert(_end <= _text.length()); + if (!str || text !== _text) { + text = _text; + str = _text.substr(0, _text.length()); + } + start = _start; + end = _end; + index = _start; + } + function scan(allowContextualToken) { + var fullStart = index; + var leadingTriviaInfo = scanTriviaInfo(false); + var start = index; + var kindAndIsVariableWidth = scanSyntaxKind(allowContextualToken); + var end = index; + var trailingTriviaInfo = scanTriviaInfo(true); + var fullWidth = index - fullStart; + var kind = kindAndIsVariableWidth & 127 /* KindMask */; + var isFixedWidth = kind >= TypeScript.SyntaxKind.FirstFixedWidth && kind <= TypeScript.SyntaxKind.LastFixedWidth && ((kindAndIsVariableWidth & 128 /* IsVariableWidthMask */) === 0); + if (isFixedWidth && leadingTriviaInfo === 0 && trailingTriviaInfo === 0 && fullStart <= 8388607 /* FixedWidthTokenMaxFullStart */ && (kindAndIsVariableWidth & 128 /* IsVariableWidthMask */) === 0) { + return new FixedWidthTokenWithNoTrivia((fullStart << 7 /* FixedWidthTokenFullStartShift */) | kind); + } + else { + var packedFullStartAndTriviaInfo = (fullStart << 2 /* LargeTokenFullStartShift */) | leadingTriviaInfo | (trailingTriviaInfo << 1); + var packedFullWidthAndKind = (fullWidth << 7 /* LargeTokenFullWidthShift */) | kind; + var cachedText = isFixedWidth ? undefined : text.substr(start, end - start); + return new LargeScannerToken(packedFullStartAndTriviaInfo, packedFullWidthAndKind, cachedText); + } + } + function scanTrivia(parent, text, isTrailing) { + var tokenFullStart = parent.fullStart(); + var tokenStart = tokenFullStart + leadingTriviaWidth(parent, text); + if (isTrailing) { + reset(text, tokenStart + parent.text().length, tokenFullStart + parent.fullWidth()); + } + else { + reset(text, tokenFullStart, tokenStart); + } + var trivia = []; + while (true) { + if (index < end) { + var ch = str.charCodeAt(index); + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(scanWhitespaceTrivia()); + continue; + case 47 /* slash */: + var ch2 = str.charCodeAt(index + 1); + if (ch2 === 47 /* slash */) { + trivia.push(scanSingleLineCommentTrivia()); + continue; + } + if (ch2 === 42 /* asterisk */) { + trivia.push(scanMultiLineCommentTrivia()); + continue; + } + throw TypeScript.Errors.invalidOperation(); + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(scanLineTerminatorSequenceTrivia(ch)); + if (!isTrailing) { + continue; + } + break; + default: + throw TypeScript.Errors.invalidOperation(); + } + } + var triviaList = TypeScript.Syntax.triviaList(trivia); + triviaList.parent = parent; + return triviaList; + } + } + function scanTriviaInfo(isTrailing) { + var result = 0; + var _end = end; + while (index < _end) { + var ch = str.charCodeAt(index); + switch (ch) { + case 9 /* tab */: + case 32 /* space */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + index++; + result = 1; + continue; + case 13 /* carriageReturn */: + if ((index + 1) < end && str.charCodeAt(index + 1) === 10 /* lineFeed */) { + index++; + } + case 10 /* lineFeed */: + index++; + if (isTrailing) { + return 1; + } + result = 1; + continue; + case 47 /* slash */: + if ((index + 1) < _end) { + var ch2 = str.charCodeAt(index + 1); + if (ch2 === 47 /* slash */) { + result = 1; + skipSingleLineCommentTrivia(); + continue; + } + if (ch2 === 42 /* asterisk */) { + result = 1; + skipMultiLineCommentTrivia(); + continue; + } + } + return result; + default: + if (ch > 127 /* maxAsciiCharacter */ && slowScanTriviaInfo(ch)) { + result = 1; + continue; + } + return result; + } + } + return result; + } + function slowScanTriviaInfo(ch) { + switch (ch) { + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + index++; + return true; + default: + return false; + } + } + function isNewLineCharacter(ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + } + function scanWhitespaceTrivia() { + var absoluteStartIndex = index; + while (true) { + var ch = str.charCodeAt(index); + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + index++; + continue; + } + break; + } + return createTrivia(4 /* WhitespaceTrivia */, absoluteStartIndex); + } + function createTrivia(kind, absoluteStartIndex) { + var fullWidth = index - absoluteStartIndex; + return TypeScript.Syntax.deferredTrivia(kind, text, absoluteStartIndex, fullWidth); + } + function scanSingleLineCommentTrivia() { + var absoluteStartIndex = index; + skipSingleLineCommentTrivia(); + return createTrivia(7 /* SingleLineCommentTrivia */, absoluteStartIndex); + } + function skipSingleLineCommentTrivia() { + index += 2; + while (index < end) { + if (isNewLineCharacter(str.charCodeAt(index))) { + return; + } + index++; + } + } + function scanMultiLineCommentTrivia() { + var absoluteStartIndex = index; + skipMultiLineCommentTrivia(); + return createTrivia(6 /* MultiLineCommentTrivia */, absoluteStartIndex); + } + function skipMultiLineCommentTrivia() { + index += 2; + while (true) { + if (index === end) { + reportDiagnostic(end, 0, TypeScript.DiagnosticCode.AsteriskSlash_expected, null); + return; + } + if ((index + 1) < end && str.charCodeAt(index) === 42 /* asterisk */ && str.charCodeAt(index + 1) === 47 /* slash */) { + index += 2; + return; + } + index++; + } + } + function scanLineTerminatorSequenceTrivia(ch) { + var absoluteStartIndex = index; + skipLineTerminatorSequence(ch); + return createTrivia(5 /* NewLineTrivia */, absoluteStartIndex); + } + function skipLineTerminatorSequence(ch) { + index++; + if (ch === 13 /* carriageReturn */ && str.charCodeAt(index) === 10 /* lineFeed */) { + index++; + } + } + function scanSyntaxKind(allowContextualToken) { + if (index >= end) { + return 10 /* EndOfFileToken */; + } + var character = str.charCodeAt(index); + index++; + switch (character) { + case 33 /* exclamation */: + return scanExclamationToken(); + case 34 /* doubleQuote */: + return scanStringLiteral(character); + case 37 /* percent */: + return scanPercentToken(); + case 38 /* ampersand */: + return scanAmpersandToken(); + case 39 /* singleQuote */: + return scanStringLiteral(character); + case 40 /* openParen */: + return 72 /* OpenParenToken */; + case 41 /* closeParen */: + return 73 /* CloseParenToken */; + case 42 /* asterisk */: + return scanAsteriskToken(); + case 43 /* plus */: + return scanPlusToken(); + case 44 /* comma */: + return 79 /* CommaToken */; + case 45 /* minus */: + return scanMinusToken(); + case 46 /* dot */: + return scanDotToken(); + case 47 /* slash */: + return scanSlashToken(allowContextualToken); + case 48 /* _0 */: + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + return scanNumericLiteral(character); + case 58 /* colon */: + return 106 /* ColonToken */; + case 59 /* semicolon */: + return 78 /* SemicolonToken */; + case 60 /* lessThan */: + return scanLessThanToken(); + case 61 /* equals */: + return scanEqualsToken(); + case 62 /* greaterThan */: + return scanGreaterThanToken(allowContextualToken); + case 63 /* question */: + return 105 /* QuestionToken */; + case 91 /* openBracket */: + return 74 /* OpenBracketToken */; + case 93 /* closeBracket */: + return 75 /* CloseBracketToken */; + case 94 /* caret */: + return scanCaretToken(); + case 123 /* openBrace */: + return 70 /* OpenBraceToken */; + case 124 /* bar */: + return scanBarToken(); + case 125 /* closeBrace */: + return 71 /* CloseBraceToken */; + case 126 /* tilde */: + return 102 /* TildeToken */; + } + if (isIdentifierStartCharacter[character]) { + var result = tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + index--; + if (isIdentifierStart(peekCharOrUnicodeEscape())) { + return slowScanIdentifierOrKeyword(); + } + var text = String.fromCharCode(character); + var messageText = getErrorMessageText(text); + reportDiagnostic(index, 1, TypeScript.DiagnosticCode.Unexpected_character_0, [messageText]); + index++; + return 9 /* ErrorToken */; + } + function isIdentifierStart(interpretedChar) { + if (isIdentifierStartCharacter[interpretedChar]) { + return true; + } + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, languageVersion); + } + function isIdentifierPart(interpretedChar) { + if (isIdentifierPartCharacter[interpretedChar]) { + return true; + } + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, languageVersion); + } + function tryFastScanIdentifierOrKeyword(firstCharacter) { + var startIndex = index; + var character = firstCharacter; + while (index < end) { + character = str.charCodeAt(index); + if (!isIdentifierPartCharacter[character]) { + break; + } + index++; + } + if (index < end && (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */)) { + index = startIndex; + return 0 /* None */; + } + else { + if (isKeywordStartCharacter[firstCharacter]) { + return TypeScript.ScannerUtilities.identifierKind(str, startIndex - 1, index - startIndex + 1); + } + else { + return 11 /* IdentifierName */; + } + } + } + function slowScanIdentifierOrKeyword() { + var startIndex = index; + do { + scanCharOrUnicodeEscape(); + } while (isIdentifierPart(peekCharOrUnicodeEscape())); + var length = index - startIndex; + var text = str.substr(startIndex, length); + var valueText = TypeScript.massageEscapes(text); + var keywordKind = TypeScript.SyntaxFacts.getTokenKind(valueText); + if (keywordKind >= TypeScript.SyntaxKind.FirstKeyword && keywordKind <= TypeScript.SyntaxKind.LastKeyword) { + return keywordKind | 128 /* IsVariableWidthMask */; + } + return 11 /* IdentifierName */; + } + function scanNumericLiteral(ch) { + if (isHexNumericLiteral(ch)) { + scanHexNumericLiteral(); + } + else if (isOctalNumericLiteral(ch)) { + scanOctalNumericLiteral(); + } + else { + scanDecimalNumericLiteral(); + } + return 13 /* NumericLiteral */; + } + function isOctalNumericLiteral(ch) { + return ch === 48 /* _0 */ && TypeScript.CharacterInfo.isOctalDigit(str.charCodeAt(index)); + } + function scanOctalNumericLiteral() { + var start = index - 1; + while (TypeScript.CharacterInfo.isOctalDigit(str.charCodeAt(index))) { + index++; + } + if (languageVersion >= 1 /* ES5 */) { + reportDiagnostic(start, index - start, TypeScript.DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, null); + } + } + function scanDecimalDigits() { + while (TypeScript.CharacterInfo.isDecimalDigit(str.charCodeAt(index))) { + index++; + } + } + function scanDecimalNumericLiteral() { + scanDecimalDigits(); + if (str.charCodeAt(index) === 46 /* dot */) { + index++; + } + scanDecimalNumericLiteralAfterDot(); + } + function scanDecimalNumericLiteralAfterDot() { + scanDecimalDigits(); + var ch = str.charCodeAt(index); + if (ch === 101 /* e */ || ch === 69 /* E */) { + var nextChar1 = str.charCodeAt(index + 1); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar1)) { + index++; + scanDecimalDigits(); + } + else if (nextChar1 === 45 /* minus */ || nextChar1 === 43 /* plus */) { + var nextChar2 = str.charCodeAt(index + 2); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar2)) { + index += 2; + scanDecimalDigits(); + } + } + } + } + function scanHexNumericLiteral() { + index++; + while (TypeScript.CharacterInfo.isHexDigit(str.charCodeAt(index))) { + index++; + } + } + function isHexNumericLiteral(ch) { + if (ch === 48 /* _0 */) { + var ch = str.charCodeAt(index); + if (ch === 120 /* x */ || ch === 88 /* X */) { + return TypeScript.CharacterInfo.isHexDigit(str.charCodeAt(index + 1)); + } + } + return false; + } + function scanLessThanToken() { + var ch0 = str.charCodeAt(index); + if (ch0 === 61 /* equals */) { + index++; + return 82 /* LessThanEqualsToken */; + } + else if (ch0 === 60 /* lessThan */) { + index++; + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 112 /* LessThanLessThanEqualsToken */; + } + else { + return 95 /* LessThanLessThanToken */; + } + } + else { + return 80 /* LessThanToken */; + } + } + function scanGreaterThanToken(allowContextualToken) { + if (allowContextualToken) { + var ch0 = str.charCodeAt(index); + if (ch0 === 62 /* greaterThan */) { + index++; + var ch1 = str.charCodeAt(index); + if (ch1 === 62 /* greaterThan */) { + index++; + var ch2 = str.charCodeAt(index); + if (ch2 === 61 /* equals */) { + index++; + return 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + else { + return 97 /* GreaterThanGreaterThanGreaterThanToken */; + } + } + else if (ch1 === 61 /* equals */) { + index++; + return 113 /* GreaterThanGreaterThanEqualsToken */; + } + else { + return 96 /* GreaterThanGreaterThanToken */; + } + } + else if (ch0 === 61 /* equals */) { + index++; + return 83 /* GreaterThanEqualsToken */; + } + } + return 81 /* GreaterThanToken */; + } + function scanBarToken() { + var ch = str.charCodeAt(index); + if (ch === 61 /* equals */) { + index++; + return 116 /* BarEqualsToken */; + } + else if (ch === 124 /* bar */) { + index++; + return 104 /* BarBarToken */; + } + else { + return 99 /* BarToken */; + } + } + function scanCaretToken() { + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 117 /* CaretEqualsToken */; + } + else { + return 100 /* CaretToken */; + } + } + function scanAmpersandToken() { + var character = str.charCodeAt(index); + if (character === 61 /* equals */) { + index++; + return 115 /* AmpersandEqualsToken */; + } + else if (character === 38 /* ampersand */) { + index++; + return 103 /* AmpersandAmpersandToken */; + } + else { + return 98 /* AmpersandToken */; + } + } + function scanPercentToken() { + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 111 /* PercentEqualsToken */; + } + else { + return 92 /* PercentToken */; + } + } + function scanMinusToken() { + var character = str.charCodeAt(index); + if (character === 61 /* equals */) { + index++; + return 109 /* MinusEqualsToken */; + } + else if (character === 45 /* minus */) { + index++; + return 94 /* MinusMinusToken */; + } + else { + return 90 /* MinusToken */; + } + } + function scanPlusToken() { + var character = str.charCodeAt(index); + if (character === 61 /* equals */) { + index++; + return 108 /* PlusEqualsToken */; + } + else if (character === 43 /* plus */) { + index++; + return 93 /* PlusPlusToken */; + } + else { + return 89 /* PlusToken */; + } + } + function scanAsteriskToken() { + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 110 /* AsteriskEqualsToken */; + } + else { + return 91 /* AsteriskToken */; + } + } + function scanEqualsToken() { + var character = str.charCodeAt(index); + if (character === 61 /* equals */) { + index++; + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 87 /* EqualsEqualsEqualsToken */; + } + else { + return 84 /* EqualsEqualsToken */; + } + } + else if (character === 62 /* greaterThan */) { + index++; + return 85 /* EqualsGreaterThanToken */; + } + else { + return 107 /* EqualsToken */; + } + } + function scanDotToken() { + var nextChar = str.charCodeAt(index); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar)) { + scanDecimalNumericLiteralAfterDot(); + return 13 /* NumericLiteral */; + } + if (nextChar === 46 /* dot */ && str.charCodeAt(index + 1) === 46 /* dot */) { + index += 2; + return 77 /* DotDotDotToken */; + } + else { + return 76 /* DotToken */; + } + } + function scanSlashToken(allowContextualToken) { + if (allowContextualToken) { + var result = tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 119 /* SlashEqualsToken */; + } + else { + return 118 /* SlashToken */; + } + } + function tryScanRegularExpressionToken() { + var startIndex = index; + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = str.charCodeAt(index); + if (isNaN(ch) || isNewLineCharacter(ch)) { + index = startIndex; + return 0 /* None */; + } + index++; + if (inEscape) { + inEscape = false; + continue; + } + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + case 91 /* openBracket */: + inCharacterClass = true; + continue; + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + break; + default: + continue; + } + break; + } + while (isIdentifierPartCharacter[str.charCodeAt(index)]) { + index++; + } + return 12 /* RegularExpressionLiteral */; + } + function scanExclamationToken() { + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + if (str.charCodeAt(index) === 61 /* equals */) { + index++; + return 88 /* ExclamationEqualsEqualsToken */; + } + else { + return 86 /* ExclamationEqualsToken */; + } + } + else { + return 101 /* ExclamationToken */; + } + } + function getErrorMessageText(text) { + if (text === "\\") { + return '"\\"'; + } + return JSON.stringify(text); + } + function skipEscapeSequence() { + var rewindPoint = index; + index++; + var ch = str.charCodeAt(index); + if (isNaN(ch)) { + return; + } + index++; + switch (ch) { + case 120 /* x */: + case 117 /* u */: + index = rewindPoint; + var value = scanUnicodeOrHexEscape(true); + break; + case 13 /* carriageReturn */: + if (str.charCodeAt(index) === 10 /* lineFeed */) { + index++; + } + break; + default: + break; + } + } + function scanStringLiteral(quoteCharacter) { + while (true) { + var ch = str.charCodeAt(index); + if (ch === 92 /* backslash */) { + skipEscapeSequence(); + } + else if (ch === quoteCharacter) { + index++; + break; + } + else if (isNaN(ch) || isNewLineCharacter(ch)) { + reportDiagnostic(Math.min(index, end), 1, TypeScript.DiagnosticCode.Missing_close_quote_character, null); + break; + } + else { + index++; + } + } + return 14 /* StringLiteral */; + } + function isUnicodeEscape(character) { + return character === 92 /* backslash */ && str.charCodeAt(index + 1) === 117 /* u */; + } + function peekCharOrUnicodeEscape() { + var character = str.charCodeAt(index); + if (isUnicodeEscape(character)) { + return peekUnicodeOrHexEscape(); + } + else { + return character; + } + } + function peekUnicodeOrHexEscape() { + var startIndex = index; + var ch = scanUnicodeOrHexEscape(false); + index = startIndex; + return ch; + } + function scanCharOrUnicodeEscape() { + if (str.charCodeAt(index) === 92 /* backslash */ && str.charCodeAt(index + 1) === 117 /* u */) { + scanUnicodeOrHexEscape(true); + } + else { + index++; + } + } + function scanUnicodeOrHexEscape(report) { + var start = index; + var character = str.charCodeAt(index); + index++; + character = str.charCodeAt(index); + var intChar = 0; + index++; + var count = character === 117 /* u */ ? 4 : 2; + for (var i = 0; i < count; i++) { + var ch2 = str.charCodeAt(index); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (report) { + reportDiagnostic(start, index - start, TypeScript.DiagnosticCode.Unrecognized_escape_sequence, null); + } + break; + } + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + index++; + } + return intChar; + } + function fillTokenInfo(token, text, tokenInfo) { + var fullStart = token.fullStart(); + var fullEnd = fullStart + token.fullWidth(); + reset(text, fullStart, fullEnd); + var leadingTriviaInfo = scanTriviaInfo(false); + var start = index; + scanSyntaxKind(isContextualToken(token)); + var end = index; + tokenInfo.leadingTriviaWidth = start - fullStart; + tokenInfo.width = end - start; + } + reset(text, 0, text.length()); + return { + setIndex: setIndex, + scan: scan, + fillTokenInfo: fillTokenInfo, + scanTrivia: scanTrivia + }; + } + function isValidIdentifier(text, languageVersion) { + var hadError = false; + var scanner = createScanner(languageVersion, text, function () { return hadError = true; }); + var token = scanner.scan(false); + return !hadError && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && TypeScript.width(token) === text.length(); + } + Scanner.isValidIdentifier = isValidIdentifier; + function createParserSource(fileName, text, languageVersion) { + var _absolutePosition = 0; + var _tokenDiagnostics = []; + var rewindPointPool = []; + var rewindPointPoolCount = 0; + var lastDiagnostic = null; + var reportDiagnostic = function (position, fullWidth, diagnosticKey, args) { + lastDiagnostic = new TypeScript.Diagnostic(fileName, text.lineMap(), position, fullWidth, diagnosticKey, args); + }; + var slidingWindow = new TypeScript.SlidingWindow(fetchNextItem, TypeScript.ArrayUtilities.createArray(1024, null), null); + var scanner = createScanner(languageVersion, text, reportDiagnostic); + function release() { + slidingWindow = null; + scanner = null; + _tokenDiagnostics = []; + rewindPointPool = []; + lastDiagnostic = null; + reportDiagnostic = null; + } + function currentNode() { + return null; + } + function consumeNode(node) { + throw TypeScript.Errors.invalidOperation(); + } + function absolutePosition() { + return _absolutePosition; + } + function tokenDiagnostics() { + return _tokenDiagnostics; + } + function getOrCreateRewindPoint() { + if (rewindPointPoolCount === 0) { + return {}; + } + rewindPointPoolCount--; + var result = rewindPointPool[rewindPointPoolCount]; + rewindPointPool[rewindPointPoolCount] = null; + return result; + } + function getRewindPoint() { + var slidingWindowIndex = slidingWindow.getAndPinAbsoluteIndex(); + var rewindPoint = getOrCreateRewindPoint(); + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.absolutePosition = _absolutePosition; + return rewindPoint; + } + function rewind(rewindPoint) { + slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + _absolutePosition = rewindPoint.absolutePosition; + } + function releaseRewindPoint(rewindPoint) { + slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint.absoluteIndex); + rewindPointPool[rewindPointPoolCount] = rewindPoint; + rewindPointPoolCount++; + } + function fetchNextItem(allowContextualToken) { + var token = scanner.scan(allowContextualToken); + if (lastDiagnostic === null) { + return token; + } + _tokenDiagnostics.push(lastDiagnostic); + lastDiagnostic = null; + return TypeScript.Syntax.realizeToken(token, text); + } + function peekToken(n) { + return slidingWindow.peekItemN(n); + } + function consumeToken(token) { + _absolutePosition += token.fullWidth(); + slidingWindow.moveToNextItem(); + } + function currentToken() { + return slidingWindow.currentItem(false); + } + function removeDiagnosticsOnOrAfterPosition(position) { + var tokenDiagnosticsLength = _tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = _tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } + else { + break; + } + } + _tokenDiagnostics.length = tokenDiagnosticsLength; + } + function resetToPosition(absolutePosition) { + _absolutePosition = absolutePosition; + removeDiagnosticsOnOrAfterPosition(absolutePosition); + slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + scanner.setIndex(absolutePosition); + } + function currentContextualToken() { + resetToPosition(_absolutePosition); + var token = slidingWindow.currentItem(true); + return token; + } + return { + text: text, + fileName: fileName, + languageVersion: languageVersion, + currentNode: currentNode, + currentToken: currentToken, + currentContextualToken: currentContextualToken, + peekToken: peekToken, + consumeNode: consumeNode, + consumeToken: consumeToken, + getRewindPoint: getRewindPoint, + rewind: rewind, + releaseRewindPoint: releaseRewindPoint, + tokenDiagnostics: tokenDiagnostics, + release: release, + absolutePosition: absolutePosition, + resetToPosition: resetToPosition + }; + } + Scanner.createParserSource = createParserSource; + })(TypeScript.Scanner || (TypeScript.Scanner = {})); + var Scanner = TypeScript.Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (str, start, length) { + switch (length) { + case 2: + switch (str.charCodeAt(start)) { + case 100 /* d */: + return (str.charCodeAt(start + 1) === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (str.charCodeAt(start + 1)) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + default: + return 11 /* IdentifierName */; + } + case 3: + switch (str.charCodeAt(start)) { + case 97 /* a */: + return (str.charCodeAt(start + 1) === 110 /* n */ && str.charCodeAt(start + 2) === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (str.charCodeAt(start + 1) === 111 /* o */ && str.charCodeAt(start + 2) === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 116 /* t */) ? 64 /* GetKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 116 /* t */) ? 68 /* SetKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (str.charCodeAt(start + 1) === 114 /* r */ && str.charCodeAt(start + 2) === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (str.charCodeAt(start + 1) === 97 /* a */ && str.charCodeAt(start + 2) === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 4: + switch (str.charCodeAt(start)) { + case 99 /* c */: + return (str.charCodeAt(start + 1) === 97 /* a */ && str.charCodeAt(start + 2) === 115 /* s */ && str.charCodeAt(start + 3) === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (str.charCodeAt(start + 1)) { + case 108 /* l */: + return (str.charCodeAt(start + 2) === 115 /* s */ && str.charCodeAt(start + 3) === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (str.charCodeAt(start + 2) === 117 /* u */ && str.charCodeAt(start + 3) === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 110 /* n */: + return (str.charCodeAt(start + 1) === 117 /* u */ && str.charCodeAt(start + 2) === 108 /* l */ && str.charCodeAt(start + 3) === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (str.charCodeAt(start + 1)) { + case 104 /* h */: + return (str.charCodeAt(start + 2) === 105 /* i */ && str.charCodeAt(start + 3) === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (str.charCodeAt(start + 2) === 117 /* u */ && str.charCodeAt(start + 3) === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 118 /* v */: + return (str.charCodeAt(start + 1) === 111 /* o */ && str.charCodeAt(start + 2) === 105 /* i */ && str.charCodeAt(start + 3) === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (str.charCodeAt(start + 1) === 105 /* i */ && str.charCodeAt(start + 2) === 116 /* t */ && str.charCodeAt(start + 3) === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 5: + switch (str.charCodeAt(start)) { + case 98 /* b */: + return (str.charCodeAt(start + 1) === 114 /* r */ && str.charCodeAt(start + 2) === 101 /* e */ && str.charCodeAt(start + 3) === 97 /* a */ && str.charCodeAt(start + 4) === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (str.charCodeAt(start + 1)) { + case 97 /* a */: + return (str.charCodeAt(start + 2) === 116 /* t */ && str.charCodeAt(start + 3) === 99 /* c */ && str.charCodeAt(start + 4) === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (str.charCodeAt(start + 2) === 97 /* a */ && str.charCodeAt(start + 3) === 115 /* s */ && str.charCodeAt(start + 4) === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (str.charCodeAt(start + 2) === 110 /* n */ && str.charCodeAt(start + 3) === 115 /* s */ && str.charCodeAt(start + 4) === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 102 /* f */: + return (str.charCodeAt(start + 1) === 97 /* a */ && str.charCodeAt(start + 2) === 108 /* l */ && str.charCodeAt(start + 3) === 115 /* s */ && str.charCodeAt(start + 4) === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (str.charCodeAt(start + 1) === 117 /* u */ && str.charCodeAt(start + 2) === 112 /* p */ && str.charCodeAt(start + 3) === 101 /* e */ && str.charCodeAt(start + 4) === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (str.charCodeAt(start + 1) === 104 /* h */ && str.charCodeAt(start + 2) === 114 /* r */ && str.charCodeAt(start + 3) === 111 /* o */ && str.charCodeAt(start + 4) === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (str.charCodeAt(start + 1) === 104 /* h */ && str.charCodeAt(start + 2) === 105 /* i */ && str.charCodeAt(start + 3) === 108 /* l */ && str.charCodeAt(start + 4) === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (str.charCodeAt(start + 1) === 105 /* i */ && str.charCodeAt(start + 2) === 101 /* e */ && str.charCodeAt(start + 3) === 108 /* l */ && str.charCodeAt(start + 4) === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 6: + switch (str.charCodeAt(start)) { + case 100 /* d */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 108 /* l */ && str.charCodeAt(start + 3) === 101 /* e */ && str.charCodeAt(start + 4) === 116 /* t */ && str.charCodeAt(start + 5) === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (str.charCodeAt(start + 1) === 120 /* x */ && str.charCodeAt(start + 2) === 112 /* p */ && str.charCodeAt(start + 3) === 111 /* o */ && str.charCodeAt(start + 4) === 114 /* r */ && str.charCodeAt(start + 5) === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (str.charCodeAt(start + 1) === 109 /* m */ && str.charCodeAt(start + 2) === 112 /* p */ && str.charCodeAt(start + 3) === 111 /* o */ && str.charCodeAt(start + 4) === 114 /* r */ && str.charCodeAt(start + 5) === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (str.charCodeAt(start + 1) === 111 /* o */ && str.charCodeAt(start + 2) === 100 /* d */ && str.charCodeAt(start + 3) === 117 /* u */ && str.charCodeAt(start + 4) === 108 /* l */ && str.charCodeAt(start + 5) === 101 /* e */) ? 65 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (str.charCodeAt(start + 1) === 117 /* u */ && str.charCodeAt(start + 2) === 109 /* m */ && str.charCodeAt(start + 3) === 98 /* b */ && str.charCodeAt(start + 4) === 101 /* e */ && str.charCodeAt(start + 5) === 114 /* r */) ? 67 /* NumberKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (str.charCodeAt(start + 1) === 117 /* u */ && str.charCodeAt(start + 2) === 98 /* b */ && str.charCodeAt(start + 3) === 108 /* l */ && str.charCodeAt(start + 4) === 105 /* i */ && str.charCodeAt(start + 5) === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 116 /* t */ && str.charCodeAt(start + 3) === 117 /* u */ && str.charCodeAt(start + 4) === 114 /* r */ && str.charCodeAt(start + 5) === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (str.charCodeAt(start + 1)) { + case 116 /* t */: + switch (str.charCodeAt(start + 2)) { + case 97 /* a */: + return (str.charCodeAt(start + 3) === 116 /* t */ && str.charCodeAt(start + 4) === 105 /* i */ && str.charCodeAt(start + 5) === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (str.charCodeAt(start + 3) === 105 /* i */ && str.charCodeAt(start + 4) === 110 /* n */ && str.charCodeAt(start + 5) === 103 /* g */) ? 69 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 119 /* w */: + return (str.charCodeAt(start + 2) === 105 /* i */ && str.charCodeAt(start + 3) === 116 /* t */ && str.charCodeAt(start + 4) === 99 /* c */ && str.charCodeAt(start + 5) === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 116 /* t */: + return (str.charCodeAt(start + 1) === 121 /* y */ && str.charCodeAt(start + 2) === 112 /* p */ && str.charCodeAt(start + 3) === 101 /* e */ && str.charCodeAt(start + 4) === 111 /* o */ && str.charCodeAt(start + 5) === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 7: + switch (str.charCodeAt(start)) { + case 98 /* b */: + return (str.charCodeAt(start + 1) === 111 /* o */ && str.charCodeAt(start + 2) === 111 /* o */ && str.charCodeAt(start + 3) === 108 /* l */ && str.charCodeAt(start + 4) === 101 /* e */ && str.charCodeAt(start + 5) === 97 /* a */ && str.charCodeAt(start + 6) === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + switch (str.charCodeAt(start + 1)) { + case 101 /* e */: + switch (str.charCodeAt(start + 2)) { + case 99 /* c */: + return (str.charCodeAt(start + 3) === 108 /* l */ && str.charCodeAt(start + 4) === 97 /* a */ && str.charCodeAt(start + 5) === 114 /* r */ && str.charCodeAt(start + 6) === 101 /* e */) ? 63 /* DeclareKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (str.charCodeAt(start + 3) === 97 /* a */ && str.charCodeAt(start + 4) === 117 /* u */ && str.charCodeAt(start + 5) === 108 /* l */ && str.charCodeAt(start + 6) === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + default: + return 11 /* IdentifierName */; + } + case 101 /* e */: + return (str.charCodeAt(start + 1) === 120 /* x */ && str.charCodeAt(start + 2) === 116 /* t */ && str.charCodeAt(start + 3) === 101 /* e */ && str.charCodeAt(start + 4) === 110 /* n */ && str.charCodeAt(start + 5) === 100 /* d */ && str.charCodeAt(start + 6) === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (str.charCodeAt(start + 1) === 105 /* i */ && str.charCodeAt(start + 2) === 110 /* n */ && str.charCodeAt(start + 3) === 97 /* a */ && str.charCodeAt(start + 4) === 108 /* l */ && str.charCodeAt(start + 5) === 108 /* l */ && str.charCodeAt(start + 6) === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (str.charCodeAt(start + 1)) { + case 97 /* a */: + return (str.charCodeAt(start + 2) === 99 /* c */ && str.charCodeAt(start + 3) === 107 /* k */ && str.charCodeAt(start + 4) === 97 /* a */ && str.charCodeAt(start + 5) === 103 /* g */ && str.charCodeAt(start + 6) === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (str.charCodeAt(start + 2) === 105 /* i */ && str.charCodeAt(start + 3) === 118 /* v */ && str.charCodeAt(start + 4) === 97 /* a */ && str.charCodeAt(start + 5) === 116 /* t */ && str.charCodeAt(start + 6) === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 114 /* r */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 113 /* q */ && str.charCodeAt(start + 3) === 117 /* u */ && str.charCodeAt(start + 4) === 105 /* i */ && str.charCodeAt(start + 5) === 114 /* r */ && str.charCodeAt(start + 6) === 101 /* e */) ? 66 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 8: + switch (str.charCodeAt(start)) { + case 99 /* c */: + return (str.charCodeAt(start + 1) === 111 /* o */ && str.charCodeAt(start + 2) === 110 /* n */ && str.charCodeAt(start + 3) === 116 /* t */ && str.charCodeAt(start + 4) === 105 /* i */ && str.charCodeAt(start + 5) === 110 /* n */ && str.charCodeAt(start + 6) === 117 /* u */ && str.charCodeAt(start + 7) === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (str.charCodeAt(start + 1) === 101 /* e */ && str.charCodeAt(start + 2) === 98 /* b */ && str.charCodeAt(start + 3) === 117 /* u */ && str.charCodeAt(start + 4) === 103 /* g */ && str.charCodeAt(start + 5) === 103 /* g */ && str.charCodeAt(start + 6) === 101 /* e */ && str.charCodeAt(start + 7) === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (str.charCodeAt(start + 1) === 117 /* u */ && str.charCodeAt(start + 2) === 110 /* n */ && str.charCodeAt(start + 3) === 99 /* c */ && str.charCodeAt(start + 4) === 116 /* t */ && str.charCodeAt(start + 5) === 105 /* i */ && str.charCodeAt(start + 6) === 111 /* o */ && str.charCodeAt(start + 7) === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 9: + switch (str.charCodeAt(start)) { + case 105 /* i */: + return (str.charCodeAt(start + 1) === 110 /* n */ && str.charCodeAt(start + 2) === 116 /* t */ && str.charCodeAt(start + 3) === 101 /* e */ && str.charCodeAt(start + 4) === 114 /* r */ && str.charCodeAt(start + 5) === 102 /* f */ && str.charCodeAt(start + 6) === 97 /* a */ && str.charCodeAt(start + 7) === 99 /* c */ && str.charCodeAt(start + 8) === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (str.charCodeAt(start + 1) === 114 /* r */ && str.charCodeAt(start + 2) === 111 /* o */ && str.charCodeAt(start + 3) === 116 /* t */ && str.charCodeAt(start + 4) === 101 /* e */ && str.charCodeAt(start + 5) === 99 /* c */ && str.charCodeAt(start + 6) === 116 /* t */ && str.charCodeAt(start + 7) === 101 /* e */ && str.charCodeAt(start + 8) === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + case 10: + switch (str.charCodeAt(start)) { + case 105 /* i */: + switch (str.charCodeAt(start + 1)) { + case 109 /* m */: + return (str.charCodeAt(start + 2) === 112 /* p */ && str.charCodeAt(start + 3) === 108 /* l */ && str.charCodeAt(start + 4) === 101 /* e */ && str.charCodeAt(start + 5) === 109 /* m */ && str.charCodeAt(start + 6) === 101 /* e */ && str.charCodeAt(start + 7) === 110 /* n */ && str.charCodeAt(start + 8) === 116 /* t */ && str.charCodeAt(start + 9) === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (str.charCodeAt(start + 2) === 115 /* s */ && str.charCodeAt(start + 3) === 116 /* t */ && str.charCodeAt(start + 4) === 97 /* a */ && str.charCodeAt(start + 5) === 110 /* n */ && str.charCodeAt(start + 6) === 99 /* c */ && str.charCodeAt(start + 7) === 101 /* e */ && str.charCodeAt(start + 8) === 111 /* o */ && str.charCodeAt(start + 9) === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + default: + return 11 /* IdentifierName */; + } + case 11: + return (str.charCodeAt(start) === 99 /* c */ && str.charCodeAt(start + 1) === 111 /* o */ && str.charCodeAt(start + 2) === 110 /* n */ && str.charCodeAt(start + 3) === 115 /* s */ && str.charCodeAt(start + 4) === 116 /* t */ && str.charCodeAt(start + 5) === 114 /* r */ && str.charCodeAt(start + 6) === 117 /* u */ && str.charCodeAt(start + 7) === 99 /* c */ && str.charCodeAt(start + 8) === 116 /* t */ && str.charCodeAt(start + 9) === 111 /* o */ && str.charCodeAt(start + 10) === 114 /* r */) ? 62 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(fetchNextItem, window, defaultValue, sourceLength) { + if (sourceLength === void 0) { sourceLength = -1; } + this.fetchNextItem = fetchNextItem; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + var sourceLength = this.sourceLength; + if (sourceLength >= 0 && this.absoluteIndex() >= sourceLength) { + return false; + } + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + var item = this.fetchNextItem(argument); + this.window[this.windowCount] = item; + this.windowCount++; + return true; + }; + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + var shiftCount = this.windowCount - shiftStartIndex; + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + this.windowAbsoluteStartIndex += shiftStartIndex; + this.windowCount -= shiftStartIndex; + this.currentRelativeItemIndex -= shiftStartIndex; + } + else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + return absoluteIndex; + }; + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + this.currentRelativeItemIndex = relativeIndex; + }; + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + return this.window[this.currentRelativeItemIndex]; + }; + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + return this.window[this.currentRelativeItemIndex + n]; + }; + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax._nextSyntaxID = 1; + function childIndex(parent, child) { + for (var i = 0, n = TypeScript.childCount(parent); i < n; i++) { + var current = TypeScript.childAt(parent, i); + if (current === child) { + return i; + } + } + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < TypeScript.childCount(node); i++) { + var child = TypeScript.childAt(node, i); + if (TypeScript.isToken(child)) { + var token = child; + if (token.hasSkippedToken() || (TypeScript.width(token) === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } + else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = TypeScript.findToken(sourceUnit, position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.hasLeadingTrivia()) { + triviaList = positionedToken.leadingTrivia(); + } + else { + positionedToken = TypeScript.previousToken(positionedToken); + if (positionedToken) { + if (positionedToken && positionedToken.hasTrailingTrivia()) { + triviaList = positionedToken.trailingTrivia(); + fullStart = TypeScript.end(positionedToken); + } + } + } + } + else { + if (position <= (fullStart + positionedToken.leadingTriviaWidth())) { + triviaList = positionedToken.leadingTrivia(); + } + else if (position >= (fullStart + TypeScript.width(positionedToken))) { + triviaList = positionedToken.trailingTrivia(); + fullStart = TypeScript.end(positionedToken); + } + } + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } + else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + fullStart += trivia.fullWidth(); + } + } + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = TypeScript.findToken(sourceUnit, position); + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = TypeScript.previousToken(positionedToken); + return positionedToken && positionedToken.trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken); + } + else if (position > TypeScript.start(positionedToken)) { + return (position < TypeScript.end(positionedToken) && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= TypeScript.end(positionedToken) && isUnterminatedStringLiteral(positionedToken)); + } + } + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + function findSkippedTokenOnLeftInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullEnd; + if (lookInLeadingTriviaList) { + triviaList = positionedToken.leadingTrivia(); + fullEnd = positionedToken.fullStart() + triviaList.fullWidth(); + } + else { + triviaList = positionedToken.trailingTrivia(); + fullEnd = TypeScript.fullEnd(positionedToken); + } + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + if (trivia.isSkippedToken() && position >= fullEnd) { + return trivia.skippedToken(); + } + fullEnd -= triviaWidth; + } + } + return null; + } + function findSkippedTokenOnLeft(positionedToken, position) { + var positionInLeadingTriviaList = (position < TypeScript.start(positionedToken)); + return findSkippedTokenOnLeftInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenOnLeft = findSkippedTokenOnLeft; + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent) { + if (positionedToken.parent.kind() === kind) { + return positionedToken.parent; + } + positionedToken = positionedToken.parent; + } + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + function hasAncestorOfKind(positionedToken, kind) { + return getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + function isIntegerLiteral(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return TypeScript.isToken(expression) && TypeScript.IntegerUtilities.isInteger(expression.text()); + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + return false; + } + Syntax.isIntegerLiteral = isIntegerLiteral; + function containingNode(element) { + var current = element.parent; + while (current !== null && !TypeScript.isNode(current)) { + current = current.parent; + } + return current; + } + Syntax.containingNode = containingNode; + function findTokenOnLeft(element, position, includeSkippedTokens) { + if (includeSkippedTokens === void 0) { includeSkippedTokens = false; } + var positionedToken = TypeScript.findToken(element, position, false); + var _start = TypeScript.start(positionedToken); + if (includeSkippedTokens) { + positionedToken = findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + if (position > _start) { + return positionedToken; + } + if (positionedToken.fullStart() === 0) { + return null; + } + return TypeScript.previousToken(positionedToken, includeSkippedTokens); + } + Syntax.findTokenOnLeft = findTokenOnLeft; + function findCompleteTokenOnLeft(element, position, includeSkippedTokens) { + if (includeSkippedTokens === void 0) { includeSkippedTokens = false; } + var positionedToken = TypeScript.findToken(element, position, false); + if (includeSkippedTokens) { + positionedToken = findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + if (TypeScript.width(positionedToken) > 0 && position >= TypeScript.end(positionedToken)) { + return positionedToken; + } + return TypeScript.previousToken(positionedToken, includeSkippedTokens); + } + Syntax.findCompleteTokenOnLeft = findCompleteTokenOnLeft; + function firstTokenInLineContainingPosition(syntaxTree, position) { + var current = TypeScript.findToken(syntaxTree.sourceUnit(), position); + while (true) { + if (isFirstTokenInLine(current, syntaxTree.lineMap())) { + break; + } + current = TypeScript.previousToken(current); + } + return current; + } + Syntax.firstTokenInLineContainingPosition = firstTokenInLineContainingPosition; + function isFirstTokenInLine(token, lineMap) { + var _previousToken = TypeScript.previousToken(token); + if (_previousToken === null) { + return true; + } + return lineMap.getLineNumberFromPosition(TypeScript.end(_previousToken)) !== lineMap.getLineNumberFromPosition(TypeScript.start(token)); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function isShared(element) { + var kind = element.kind(); + return (kind === 1 /* List */ || kind === 2 /* SeparatedList */) && element.length === 0; + } + TypeScript.isShared = isShared; + function childCount(element) { + var kind = element.kind(); + if (kind === 1 /* List */) { + return element.length; + } + else if (kind === 2 /* SeparatedList */) { + return element.length + element.separators.length; + } + else if (kind >= TypeScript.SyntaxKind.FirstToken && kind <= TypeScript.SyntaxKind.LastToken) { + return 0; + } + else { + return TypeScript.nodeMetadata[kind].length; + } + } + TypeScript.childCount = childCount; + function childAt(element, index) { + var kind = element.kind(); + if (kind === 1 /* List */) { + return element[index]; + } + else if (kind === 2 /* SeparatedList */) { + return (index % 2 === 0) ? element[index / 2] : element.separators[(index - 1) / 2]; + } + else { + return element[TypeScript.nodeMetadata[element.kind()][index]]; + } + } + TypeScript.childAt = childAt; + function syntaxTree(element) { + if (element) { + TypeScript.Debug.assert(!isShared(element)); + while (element) { + if (element.kind() === 120 /* SourceUnit */) { + return element.syntaxTree; + } + element = element.parent; + } + } + return null; + } + TypeScript.syntaxTree = syntaxTree; + function parsedInStrictMode(node) { + var info = node.data; + if (info === undefined) { + return false; + } + return (info & 4 /* NodeParsedInStrictModeMask */) !== 0; + } + TypeScript.parsedInStrictMode = parsedInStrictMode; + function previousToken(token, includeSkippedTokens) { + if (includeSkippedTokens === void 0) { includeSkippedTokens = false; } + if (includeSkippedTokens) { + var triviaList = token.leadingTrivia(); + if (triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = TypeScript.start(token); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return trivia.skippedToken(); + } + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + } + var start = token.fullStart(); + if (start === 0) { + return null; + } + return findToken(syntaxTree(token).sourceUnit(), start - 1, includeSkippedTokens); + } + TypeScript.previousToken = previousToken; + function findToken(element, position, includeSkippedTokens) { + if (includeSkippedTokens === void 0) { includeSkippedTokens = false; } + var endOfFileToken = tryGetEndOfFileAt(element, position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + if (position < 0 || position >= fullWidth(element)) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + var positionedToken = findTokenWorker(element, position); + if (includeSkippedTokens) { + return findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + return positionedToken; + } + TypeScript.findToken = findToken; + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < start(positionedToken)); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + TypeScript.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + TypeScript.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + TypeScript.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + if (lookInLeadingTriviaList) { + triviaList = positionedToken.leadingTrivia(); + fullStart = positionedToken.fullStart(); + } + else { + triviaList = positionedToken.trailingTrivia(); + fullStart = end(positionedToken); + } + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return trivia.skippedToken(); + } + fullStart += triviaWidth; + } + } + return null; + } + function findTokenWorker(element, position) { + if (isToken(element)) { + TypeScript.Debug.assert(fullWidth(element) > 0); + return element; + } + if (isShared(element)) { + throw TypeScript.Errors.invalidOperation(); + } + for (var i = 0, n = childCount(element); i < n; i++) { + var child = childAt(element, i); + if (child !== null) { + var childFullWidth = fullWidth(child); + if (childFullWidth > 0) { + var childFullStart = fullStart(child); + if (position >= childFullStart) { + var childFullEnd = childFullStart + childFullWidth; + if (position < childFullEnd) { + return findTokenWorker(child, position); + } + } + } + } + } + throw TypeScript.Errors.invalidOperation(); + } + function tryGetEndOfFileAt(element, position) { + if (element.kind() === 120 /* SourceUnit */ && position === fullWidth(element)) { + var sourceUnit = element; + return sourceUnit.endOfFileToken; + } + return null; + } + function nextToken(token, text, includeSkippedTokens) { + if (includeSkippedTokens === void 0) { includeSkippedTokens = false; } + if (token.kind() === 10 /* EndOfFileToken */) { + return null; + } + if (includeSkippedTokens) { + var triviaList = token.trailingTrivia(text); + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return trivia.skippedToken(); + } + } + } + } + return findToken(syntaxTree(token).sourceUnit(), fullEnd(token), includeSkippedTokens); + } + TypeScript.nextToken = nextToken; + function isNode(element) { + if (element !== null) { + var kind = element.kind(); + return kind >= TypeScript.SyntaxKind.FirstNode && kind <= TypeScript.SyntaxKind.LastNode; + } + return false; + } + TypeScript.isNode = isNode; + function isTokenKind(kind) { + return kind >= TypeScript.SyntaxKind.FirstToken && kind <= TypeScript.SyntaxKind.LastToken; + } + function isToken(element) { + if (element !== null) { + return isTokenKind(element.kind()); + } + return false; + } + TypeScript.isToken = isToken; + function isList(element) { + return element !== null && element.kind() === 1 /* List */; + } + TypeScript.isList = isList; + function isSeparatedList(element) { + return element !== null && element.kind() === 2 /* SeparatedList */; + } + TypeScript.isSeparatedList = isSeparatedList; + function syntaxID(element) { + if (isShared(element)) { + throw TypeScript.Errors.invalidOperation("Should not use shared syntax element as a key."); + } + var obj = element; + if (obj._syntaxID === undefined) { + obj._syntaxID = TypeScript.Syntax._nextSyntaxID++; + } + return obj._syntaxID; + } + TypeScript.syntaxID = syntaxID; + function collectTextElements(element, elements, text) { + if (element) { + if (isToken(element)) { + elements.push(element.fullText(text)); + } + else { + for (var i = 0, n = childCount(element); i < n; i++) { + collectTextElements(childAt(element, i), elements, text); + } + } + } + } + function fullText(element, text) { + if (isToken(element)) { + return element.fullText(text); + } + var elements = []; + collectTextElements(element, elements, text); + return elements.join(""); + } + TypeScript.fullText = fullText; + function leadingTriviaWidth(element, text) { + var token = firstToken(element); + return token ? token.leadingTriviaWidth(text) : 0; + } + TypeScript.leadingTriviaWidth = leadingTriviaWidth; + function trailingTriviaWidth(element, text) { + var token = lastToken(element); + return token ? token.trailingTriviaWidth(text) : 0; + } + TypeScript.trailingTriviaWidth = trailingTriviaWidth; + function firstToken(element) { + if (element) { + var kind = element.kind(); + if (isTokenKind(kind)) { + return fullWidth(element) > 0 || element.kind() === 10 /* EndOfFileToken */ ? element : null; + } + if (kind === 1 /* List */) { + var array = element; + for (var i = 0, n = array.length; i < n; i++) { + var token = firstToken(array[i]); + if (token) { + return token; + } + } + } + else if (kind === 2 /* SeparatedList */) { + var array = element; + var separators = array.separators; + for (var i = 0, n = array.length + separators.length; i < n; i++) { + var token = firstToken(i % 2 === 0 ? array[i / 2] : separators[(i - 1) / 2]); + if (token) { + return token; + } + } + } + else { + var metadata = TypeScript.nodeMetadata[kind]; + for (var i = 0, n = metadata.length; i < n; i++) { + var child = element[metadata[i]]; + var token = firstToken(child); + if (token) { + return token; + } + } + if (element.kind() === 120 /* SourceUnit */) { + return element.endOfFileToken; + } + } + } + return null; + } + TypeScript.firstToken = firstToken; + function lastToken(element) { + if (isToken(element)) { + return fullWidth(element) > 0 || element.kind() === 10 /* EndOfFileToken */ ? element : null; + } + if (element.kind() === 120 /* SourceUnit */) { + return element.endOfFileToken; + } + for (var i = childCount(element) - 1; i >= 0; i--) { + var child = childAt(element, i); + if (child !== null) { + var token = lastToken(child); + if (token) { + return token; + } + } + } + return null; + } + TypeScript.lastToken = lastToken; + function fullStart(element) { + TypeScript.Debug.assert(!isShared(element)); + var token = isToken(element) ? element : firstToken(element); + return token ? token.fullStart() : -1; + } + TypeScript.fullStart = fullStart; + function fullWidth(element) { + if (isToken(element)) { + return element.fullWidth(); + } + if (isShared(element)) { + return 0; + } + var info = data(element); + return info >>> 3 /* NodeFullWidthShift */; + } + TypeScript.fullWidth = fullWidth; + function isIncrementallyUnusable(element) { + if (isToken(element)) { + return element.isIncrementallyUnusable(); + } + if (isShared(element)) { + return false; + } + return (data(element) & 2 /* NodeIncrementallyUnusableMask */) !== 0; + } + TypeScript.isIncrementallyUnusable = isIncrementallyUnusable; + function data(element) { + TypeScript.Debug.assert(isNode(element) || isList(element) || isSeparatedList(element)); + var dataElement = element; + var info = dataElement.data; + if (info === undefined) { + info = 0; + } + if ((info & 1 /* NodeDataComputed */) === 0) { + info |= computeData(element); + dataElement.data = info; + } + return info; + } + function computeData(element) { + var slotCount = childCount(element); + var fullWidth = 0; + var isIncrementallyUnusable = slotCount === 0; + for (var i = 0, n = slotCount; i < n; i++) { + var child = childAt(element, i); + if (child) { + fullWidth += TypeScript.fullWidth(child); + isIncrementallyUnusable = isIncrementallyUnusable || TypeScript.isIncrementallyUnusable(child); + } + } + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + } + function start(element, text) { + var token = isToken(element) ? element : firstToken(element); + return token ? token.fullStart() + token.leadingTriviaWidth(text) : -1; + } + TypeScript.start = start; + function end(element, text) { + var token = isToken(element) ? element : lastToken(element); + return token ? fullEnd(token) - token.trailingTriviaWidth(text) : -1; + } + TypeScript.end = end; + function width(element, text) { + if (isToken(element)) { + return element.text().length; + } + return fullWidth(element) - leadingTriviaWidth(element, text) - trailingTriviaWidth(element, text); + } + TypeScript.width = width; + function fullEnd(element) { + return fullStart(element) + fullWidth(element); + } + TypeScript.fullEnd = fullEnd; + function existsNewLineBetweenTokens(token1, token2, text) { + if (token1 === token2) { + return false; + } + if (token1 === null || token2 === null) { + return true; + } + var lineMap = text.lineMap(); + return lineMap.getLineNumberFromPosition(end(token1, text)) !== lineMap.getLineNumberFromPosition(start(token2, text)); + } + TypeScript.existsNewLineBetweenTokens = existsNewLineBetweenTokens; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.kind(); + return tokenKind === 11 /* IdentifierName */ || SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var _emptyList = []; + var _emptySeparatedList = []; + var _emptySeparators = []; + _emptySeparatedList.separators = _emptySeparators; + function assertEmptyLists() { + } + Array.prototype.kind = function () { + return this.separators === undefined ? 1 /* List */ : 2 /* SeparatedList */; + }; + Array.prototype.separatorCount = function () { + assertEmptyLists(); + return this.separators.length; + }; + Array.prototype.separatorAt = function (index) { + assertEmptyLists(); + return this.separators[index]; + }; + function emptyList() { + return _emptyList; + } + Syntax.emptyList = emptyList; + function emptySeparatedList() { + return _emptySeparatedList; + } + Syntax.emptySeparatedList = emptySeparatedList; + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return emptyList(); + } + for (var i = 0, n = nodes.length; i < n; i++) { + nodes[i].parent = nodes; + } + return nodes; + } + Syntax.list = list; + function separatedList(nodes, separators) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return emptySeparatedList(); + } + for (var i = 0, n = nodes.length; i < n; i++) { + nodes[i].parent = nodes; + } + for (var i = 0, n = separators.length; i < n; i++) { + separators[i].parent = nodes; + } + nodes.separators = separators.length === 0 ? _emptySeparators : separators; + return nodes; + } + Syntax.separatedList = separatedList; + function nonSeparatorIndexOf(list, ast) { + for (var i = 0, n = list.length; i < n; i++) { + if (list[i] === ast) { + return i; + } + } + return -1; + } + Syntax.nonSeparatorIndexOf = nonSeparatorIndexOf; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(data) { + if (data) { + this.data = data; + } + } + SyntaxNode.prototype.kind = function () { + return this.__kind; + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.nodeMetadata = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ["moduleElements", "endOfFileToken"], ["left", "dotToken", "right"], ["openBraceToken", "typeMembers", "closeBraceToken"], ["typeParameterList", "parameterList", "equalsGreaterThanToken", "type"], ["type", "openBracketToken", "closeBracketToken"], ["newKeyword", "typeParameterList", "parameterList", "equalsGreaterThanToken", "type"], ["name", "typeArgumentList"], ["typeOfKeyword", "name"], ["modifiers", "interfaceKeyword", "identifier", "typeParameterList", "heritageClauses", "body"], ["modifiers", "functionKeyword", "identifier", "callSignature", "block", "semicolonToken"], ["modifiers", "moduleKeyword", "name", "stringLiteral", "openBraceToken", "moduleElements", "closeBraceToken"], ["modifiers", "classKeyword", "identifier", "typeParameterList", "heritageClauses", "openBraceToken", "classElements", "closeBraceToken"], ["modifiers", "enumKeyword", "identifier", "openBraceToken", "enumElements", "closeBraceToken"], ["modifiers", "importKeyword", "identifier", "equalsToken", "moduleReference", "semicolonToken"], ["exportKeyword", "equalsToken", "identifier", "semicolonToken"], ["modifiers", "propertyName", "callSignature", "block", "semicolonToken"], ["modifiers", "variableDeclarator", "semicolonToken"], ["modifiers", "constructorKeyword", "callSignature", "block", "semicolonToken"], ["modifiers", "indexSignature", "semicolonToken"], ["modifiers", "getKeyword", "propertyName", "callSignature", "block"], ["modifiers", "setKeyword", "propertyName", "callSignature", "block"], ["propertyName", "questionToken", "typeAnnotation"], ["typeParameterList", "parameterList", "typeAnnotation"], ["newKeyword", "callSignature"], ["openBracketToken", "parameters", "closeBracketToken", "typeAnnotation"], ["propertyName", "questionToken", "callSignature"], ["openBraceToken", "statements", "closeBraceToken"], ["ifKeyword", "openParenToken", "condition", "closeParenToken", "statement", "elseClause"], ["modifiers", "variableDeclaration", "semicolonToken"], ["expression", "semicolonToken"], ["returnKeyword", "expression", "semicolonToken"], ["switchKeyword", "openParenToken", "expression", "closeParenToken", "openBraceToken", "switchClauses", "closeBraceToken"], ["breakKeyword", "identifier", "semicolonToken"], ["continueKeyword", "identifier", "semicolonToken"], ["forKeyword", "openParenToken", "variableDeclaration", "initializer", "firstSemicolonToken", "condition", "secondSemicolonToken", "incrementor", "closeParenToken", "statement"], ["forKeyword", "openParenToken", "variableDeclaration", "left", "inKeyword", "expression", "closeParenToken", "statement"], ["semicolonToken"], ["throwKeyword", "expression", "semicolonToken"], ["whileKeyword", "openParenToken", "condition", "closeParenToken", "statement"], ["tryKeyword", "block", "catchClause", "finallyClause"], ["identifier", "colonToken", "statement"], ["doKeyword", "statement", "whileKeyword", "openParenToken", "condition", "closeParenToken", "semicolonToken"], ["debuggerKeyword", "semicolonToken"], ["withKeyword", "openParenToken", "condition", "closeParenToken", "statement"], ["operatorToken", "operand"], ["operatorToken", "operand"], ["operatorToken", "operand"], ["operatorToken", "operand"], ["operatorToken", "operand"], ["operatorToken", "operand"], ["deleteKeyword", "expression"], ["typeOfKeyword", "expression"], ["voidKeyword", "expression"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["condition", "questionToken", "whenTrue", "colonToken", "whenFalse"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["left", "operatorToken", "right"], ["operand", "operatorToken"], ["operand", "operatorToken"], ["expression", "dotToken", "name"], ["expression", "argumentList"], ["openBracketToken", "expressions", "closeBracketToken"], ["openBraceToken", "propertyAssignments", "closeBraceToken"], ["newKeyword", "expression", "argumentList"], ["openParenToken", "expression", "closeParenToken"], ["callSignature", "equalsGreaterThanToken", "block", "expression"], ["parameter", "equalsGreaterThanToken", "block", "expression"], ["lessThanToken", "type", "greaterThanToken", "expression"], ["expression", "openBracketToken", "argumentExpression", "closeBracketToken"], ["functionKeyword", "identifier", "callSignature", "block"], [], ["varKeyword", "variableDeclarators"], ["propertyName", "typeAnnotation", "equalsValueClause"], ["typeArgumentList", "openParenToken", "arguments", "closeParenToken"], ["openParenToken", "parameters", "closeParenToken"], ["lessThanToken", "typeArguments", "greaterThanToken"], ["lessThanToken", "typeParameters", "greaterThanToken"], ["extendsOrImplementsKeyword", "typeNames"], ["extendsOrImplementsKeyword", "typeNames"], ["equalsToken", "value"], ["caseKeyword", "expression", "colonToken", "statements"], ["defaultKeyword", "colonToken", "statements"], ["elseKeyword", "statement"], ["catchKeyword", "openParenToken", "identifier", "typeAnnotation", "closeParenToken", "block"], ["finallyKeyword", "block"], ["identifier", "constraint"], ["extendsKeyword", "typeOrExpression"], ["propertyName", "colonToken", "expression"], ["propertyName", "callSignature", "block"], ["dotDotDotToken", "modifiers", "identifier", "questionToken", "typeAnnotation", "equalsValueClause"], ["propertyName", "equalsValueClause"], ["colonToken", "type"], ["requireKeyword", "openParenToken", "stringLiteral", "closeParenToken"], ["moduleName"], ]; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function tokenValue(token) { + if (token.fullWidth() === 0) { + return null; + } + var kind = token.kind(); + var text = token.text(); + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + if (kind === 13 /* NumericLiteral */) { + return TypeScript.IntegerUtilities.isHexInteger(text) ? parseInt(text, 16) : parseFloat(text); + } + else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } + else { + return massageEscapes(text.substr(1)); + } + } + else if (kind === 12 /* RegularExpressionLiteral */) { + return regularExpressionValue(text); + } + else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } + else { + throw TypeScript.Errors.invalidOperation(); + } + } + TypeScript.tokenValue = tokenValue; + function tokenValueText(token) { + var value = tokenValue(token); + return value === null ? "" : massageDisallowedIdentifiers(value.toString()); + } + TypeScript.tokenValueText = tokenValueText; + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + TypeScript.massageEscapes = massageEscapes; + function regularExpressionValue(text) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } + catch (e) { + return null; + } + } + function massageDisallowedIdentifiers(text) { + if (text.charCodeAt(0) === 95 /* _ */ && text.charCodeAt(1) === 95 /* _ */) { + return "_" + text; + } + return text; + } + var characterArray = []; + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + case 13 /* carriageReturn */: + var nextIndex = i + 1; + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { + i++; + } + continue; + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + continue; + default: + } + } + } + characterArray.push(ch); + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + return result; + } + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + return intChar; + } +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function realizeToken(token, text) { + return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), token.trailingTrivia(text)); + } + Syntax.realizeToken = realizeToken; + function convertKeywordToIdentifier(token) { + return new ConvertedKeywordToken(token); + } + Syntax.convertKeywordToIdentifier = convertKeywordToIdentifier; + function withLeadingTrivia(token, leadingTrivia, text) { + return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), leadingTrivia, token.text(), token.trailingTrivia(text)); + } + Syntax.withLeadingTrivia = withLeadingTrivia; + function withTrailingTrivia(token, trailingTrivia, text) { + return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), trailingTrivia); + } + Syntax.withTrailingTrivia = withTrailingTrivia; + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + var EmptyToken = (function () { + function EmptyToken(_kind) { + this._kind = _kind; + } + EmptyToken.prototype.setFullStart = function (fullStart) { + }; + EmptyToken.prototype.kind = function () { + return this._kind; + }; + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.kind()); + }; + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + EmptyToken.prototype.isKeywordConvertedToIdentifier = function () { + return false; + }; + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.position = function () { + var previousElement = this.previousNonZeroWidthElement(); + return previousElement === null ? 0 : TypeScript.fullStart(previousElement) + TypeScript.fullWidth(previousElement); + }; + EmptyToken.prototype.previousNonZeroWidthElement = function () { + var current = this; + while (true) { + var parent = current.parent; + if (parent === null) { + TypeScript.Debug.assert(current.kind() === 120 /* SourceUnit */, "We had a node without a parent that was not the root node!"); + return null; + } + for (var i = 0, n = TypeScript.childCount(parent); i < n; i++) { + if (TypeScript.childAt(parent, i) === current) { + break; + } + } + TypeScript.Debug.assert(i !== n, "Could not find current element in parent's child list!"); + for (var j = i - 1; j >= 0; j--) { + var sibling = TypeScript.childAt(parent, j); + if (sibling && TypeScript.fullWidth(sibling) > 0) { + return sibling; + } + } + current = current.parent; + } + }; + EmptyToken.prototype.fullStart = function () { + return this.position(); + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + return EmptyToken; + })(); + var RealizedToken = (function () { + function RealizedToken(fullStart, kind, isKeywordConvertedToIdentifier, leadingTrivia, text, trailingTrivia) { + this._fullStart = fullStart; + this._kind = kind; + this._isKeywordConvertedToIdentifier = isKeywordConvertedToIdentifier; + this._text = text; + this._leadingTrivia = leadingTrivia.clone(); + this._trailingTrivia = trailingTrivia.clone(); + if (!this._leadingTrivia.isShared()) { + this._leadingTrivia.parent = this; + } + if (!this._trailingTrivia.isShared()) { + this._trailingTrivia.parent = this; + } + } + RealizedToken.prototype.setFullStart = function (fullStart) { + this._fullStart = fullStart; + }; + RealizedToken.prototype.kind = function () { + return this._kind; + }; + RealizedToken.prototype.clone = function () { + return new RealizedToken(this._fullStart, this.kind(), this._isKeywordConvertedToIdentifier, this._leadingTrivia, this._text, this._trailingTrivia); + }; + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + RealizedToken.prototype.isKeywordConvertedToIdentifier = function () { + return this._isKeywordConvertedToIdentifier; + }; + RealizedToken.prototype.fullStart = function () { + return this._fullStart; + }; + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this._text.length + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.hasSkippedToken = function () { + return this._leadingTrivia.hasSkippedToken() || this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + return RealizedToken; + })(); + var ConvertedKeywordToken = (function () { + function ConvertedKeywordToken(underlyingToken) { + this.underlyingToken = underlyingToken; + } + ConvertedKeywordToken.prototype.kind = function () { + return 11 /* IdentifierName */; + }; + ConvertedKeywordToken.prototype.setFullStart = function (fullStart) { + this.underlyingToken.setFullStart(fullStart); + }; + ConvertedKeywordToken.prototype.fullStart = function () { + return this.underlyingToken.fullStart(); + }; + ConvertedKeywordToken.prototype.fullWidth = function () { + return this.underlyingToken.fullWidth(); + }; + ConvertedKeywordToken.prototype.text = function () { + return this.underlyingToken.text(); + }; + ConvertedKeywordToken.prototype.syntaxTreeText = function (text) { + var result = text || TypeScript.syntaxTree(this).text; + TypeScript.Debug.assert(result); + return result; + }; + ConvertedKeywordToken.prototype.fullText = function (text) { + return this.underlyingToken.fullText(this.syntaxTreeText(text)); + }; + ConvertedKeywordToken.prototype.hasLeadingTrivia = function () { + return this.underlyingToken.hasLeadingTrivia(); + }; + ConvertedKeywordToken.prototype.hasTrailingTrivia = function () { + return this.underlyingToken.hasTrailingTrivia(); + }; + ConvertedKeywordToken.prototype.hasSkippedToken = function () { + return this.underlyingToken.hasSkippedToken(); + }; + ConvertedKeywordToken.prototype.leadingTrivia = function (text) { + var result = this.underlyingToken.leadingTrivia(this.syntaxTreeText(text)); + result.parent = this; + return result; + }; + ConvertedKeywordToken.prototype.trailingTrivia = function (text) { + var result = this.underlyingToken.trailingTrivia(this.syntaxTreeText(text)); + result.parent = this; + return result; + }; + ConvertedKeywordToken.prototype.leadingTriviaWidth = function (text) { + return this.underlyingToken.leadingTriviaWidth(this.syntaxTreeText(text)); + }; + ConvertedKeywordToken.prototype.trailingTriviaWidth = function (text) { + return this.underlyingToken.trailingTriviaWidth(this.syntaxTreeText(text)); + }; + ConvertedKeywordToken.prototype.isKeywordConvertedToIdentifier = function () { + return true; + }; + ConvertedKeywordToken.prototype.isIncrementallyUnusable = function () { + return this.underlyingToken.isIncrementallyUnusable(); + }; + ConvertedKeywordToken.prototype.clone = function () { + return new ConvertedKeywordToken(this.underlyingToken); + }; + return ConvertedKeywordToken; + })(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var AbstractTrivia = (function () { + function AbstractTrivia(_kind) { + this._kind = _kind; + } + AbstractTrivia.prototype.kind = function () { + return this._kind; + }; + AbstractTrivia.prototype.clone = function () { + throw TypeScript.Errors.abstract(); + }; + AbstractTrivia.prototype.fullStart = function () { + throw TypeScript.Errors.abstract(); + }; + AbstractTrivia.prototype.fullWidth = function () { + throw TypeScript.Errors.abstract(); + }; + AbstractTrivia.prototype.fullText = function () { + throw TypeScript.Errors.abstract(); + }; + AbstractTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.abstract(); + }; + AbstractTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + AbstractTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + AbstractTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + AbstractTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + return AbstractTrivia; + })(); + var SkippedTokenTrivia = (function (_super) { + __extends(SkippedTokenTrivia, _super); + function SkippedTokenTrivia(_skippedToken, _fullText) { + _super.call(this, 8 /* SkippedTokenTrivia */); + this._skippedToken = _skippedToken; + this._fullText = _fullText; + _skippedToken.parent = this; + } + SkippedTokenTrivia.prototype.clone = function () { + return new SkippedTokenTrivia(this._skippedToken.clone(), this._fullText); + }; + SkippedTokenTrivia.prototype.fullStart = function () { + return this._skippedToken.fullStart(); + }; + SkippedTokenTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + SkippedTokenTrivia.prototype.fullText = function () { + return this._fullText; + }; + SkippedTokenTrivia.prototype.skippedToken = function () { + return this._skippedToken; + }; + return SkippedTokenTrivia; + })(AbstractTrivia); + var DeferredTrivia = (function (_super) { + __extends(DeferredTrivia, _super); + function DeferredTrivia(kind, _text, _fullStart, _fullWidth) { + _super.call(this, kind); + this._text = _text; + this._fullStart = _fullStart; + this._fullWidth = _fullWidth; + } + DeferredTrivia.prototype.clone = function () { + return new DeferredTrivia(this.kind(), this._text, this._fullStart, this._fullWidth); + }; + DeferredTrivia.prototype.fullStart = function () { + return this._fullStart; + }; + DeferredTrivia.prototype.fullWidth = function () { + return this._fullWidth; + }; + DeferredTrivia.prototype.fullText = function () { + return this._text.substr(this._fullStart, this._fullWidth); + }; + DeferredTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return DeferredTrivia; + })(AbstractTrivia); + function deferredTrivia(kind, text, fullStart, fullWidth) { + return new DeferredTrivia(kind, text, fullStart, fullWidth); + } + Syntax.deferredTrivia = deferredTrivia; + function skippedTokenTrivia(token, text) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SkippedTokenTrivia(token, token.fullText(text)); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + var triviaText = trivia.fullText(); + var currentIndex = 0; + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + currentIndex = i + 1; + continue; + } + } + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptyTriviaList = (function () { + function EmptyTriviaList() { + } + EmptyTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + EmptyTriviaList.prototype.isShared = function () { + return true; + }; + EmptyTriviaList.prototype.count = function () { + return 0; + }; + EmptyTriviaList.prototype.syntaxTriviaAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + EmptyTriviaList.prototype.last = function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + EmptyTriviaList.prototype.fullWidth = function () { + return 0; + }; + EmptyTriviaList.prototype.fullText = function () { + return ""; + }; + EmptyTriviaList.prototype.hasComment = function () { + return false; + }; + EmptyTriviaList.prototype.hasNewLine = function () { + return false; + }; + EmptyTriviaList.prototype.hasSkippedToken = function () { + return false; + }; + EmptyTriviaList.prototype.toArray = function () { + return []; + }; + EmptyTriviaList.prototype.clone = function () { + return this; + }; + return EmptyTriviaList; + })(); + ; + Syntax.emptyTriviaList = new EmptyTriviaList(); + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item.clone(); + this.item.parent = this; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + SingletonSyntaxTriviaList.prototype.isShared = function () { + return false; + }; + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + return this.item; + }; + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSyntaxTriviaList.prototype.clone = function () { + return new SingletonSyntaxTriviaList(this.item.clone()); + }; + return SingletonSyntaxTriviaList; + })(); + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + var _this = this; + this.trivia = trivia.map(function (t) { + var cloned = t.clone(); + cloned.parent = _this; + return cloned; + }); + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + NormalSyntaxTriviaList.prototype.isShared = function () { + return false; + }; + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + return this.trivia[index]; + }; + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { return t.fullWidth(); }); + }; + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = []; + for (var i = 0, n = this.trivia.length; i < n; i++) { + result.push(this.trivia[i].fullText()); + } + return result.join(""); + }; + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + return false; + }; + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + return false; + }; + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + return false; + }; + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + NormalSyntaxTriviaList.prototype.clone = function () { + return new NormalSyntaxTriviaList(this.trivia.map(function (t) { return t.clone(); })); + }; + return NormalSyntaxTriviaList; + })(); + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return Syntax.emptyTriviaList; + } + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAnyFunctionExpressionOrDeclaration = function (ast) { + switch (ast.kind()) { + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 129 /* FunctionDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 241 /* FunctionPropertyAssignment */: + case 137 /* ConstructorDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return true; + } + return false; + }; + SyntaxUtilities.isLastTokenOnLine = function (token, text) { + var _nextToken = TypeScript.nextToken(token, text); + if (_nextToken === null) { + return true; + } + var lineMap = text.lineMap(); + var tokenLine = lineMap.getLineNumberFromPosition(TypeScript.end(token, text)); + var nextTokenLine = lineMap.getLineNumberFromPosition(TypeScript.start(_nextToken, text)); + return tokenLine !== nextTokenLine; + }; + SyntaxUtilities.isLeftHandSizeExpression = function (element) { + if (element) { + switch (element.kind()) { + case 212 /* MemberAccessExpression */: + case 221 /* ElementAccessExpression */: + case 216 /* ObjectCreationExpression */: + case 213 /* InvocationExpression */: + case 214 /* ArrayLiteralExpression */: + case 217 /* ParenthesizedExpression */: + case 215 /* ObjectLiteralExpression */: + case 222 /* FunctionExpression */: + case 11 /* IdentifierName */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 50 /* SuperKeyword */: + return true; + } + } + return false; + }; + SyntaxUtilities.isExpression = function (element) { + if (element) { + switch (element.kind()) { + case 11 /* IdentifierName */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 50 /* SuperKeyword */: + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 167 /* LogicalNotExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + case 170 /* DeleteExpression */: + case 171 /* TypeOfExpression */: + case 172 /* VoidExpression */: + case 173 /* CommaExpression */: + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 186 /* ConditionalExpression */: + case 187 /* LogicalOrExpression */: + case 188 /* LogicalAndExpression */: + case 189 /* BitwiseOrExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 191 /* BitwiseAndExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + case 210 /* PostIncrementExpression */: + case 211 /* PostDecrementExpression */: + case 212 /* MemberAccessExpression */: + case 213 /* InvocationExpression */: + case 214 /* ArrayLiteralExpression */: + case 215 /* ObjectLiteralExpression */: + case 216 /* ObjectCreationExpression */: + case 217 /* ParenthesizedExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + case 220 /* CastExpression */: + case 221 /* ElementAccessExpression */: + case 222 /* FunctionExpression */: + case 223 /* OmittedExpression */: + return true; + } + } + return false; + }; + SyntaxUtilities.isSwitchClause = function (element) { + if (element) { + switch (element.kind()) { + case 233 /* CaseSwitchClause */: + case 234 /* DefaultSwitchClause */: + return true; + } + } + return false; + }; + SyntaxUtilities.isTypeMember = function (element) { + if (element) { + switch (element.kind()) { + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 144 /* IndexSignature */: + case 141 /* PropertySignature */: + case 142 /* CallSignature */: + return true; + } + } + return false; + }; + SyntaxUtilities.isClassElement = function (element) { + if (element) { + switch (element.kind()) { + case 137 /* ConstructorDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 135 /* MemberFunctionDeclaration */: + case 136 /* MemberVariableDeclaration */: + return true; + } + } + return false; + }; + SyntaxUtilities.isModuleElement = function (element) { + if (element) { + switch (element.kind()) { + case 133 /* ImportDeclaration */: + case 134 /* ExportAssignment */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + case 132 /* EnumDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 146 /* Block */: + case 147 /* IfStatement */: + case 149 /* ExpressionStatement */: + case 157 /* ThrowStatement */: + case 150 /* ReturnStatement */: + case 151 /* SwitchStatement */: + case 152 /* BreakStatement */: + case 153 /* ContinueStatement */: + case 155 /* ForInStatement */: + case 154 /* ForStatement */: + case 158 /* WhileStatement */: + case 163 /* WithStatement */: + case 156 /* EmptyStatement */: + case 159 /* TryStatement */: + case 160 /* LabeledStatement */: + case 161 /* DoStatement */: + case 162 /* DebuggerStatement */: + return true; + } + } + return false; + }; + SyntaxUtilities.isStatement = function (element) { + if (element) { + switch (element.kind()) { + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 146 /* Block */: + case 147 /* IfStatement */: + case 149 /* ExpressionStatement */: + case 157 /* ThrowStatement */: + case 150 /* ReturnStatement */: + case 151 /* SwitchStatement */: + case 152 /* BreakStatement */: + case 153 /* ContinueStatement */: + case 155 /* ForInStatement */: + case 154 /* ForStatement */: + case 158 /* WhileStatement */: + case 163 /* WithStatement */: + case 156 /* EmptyStatement */: + case 159 /* TryStatement */: + case 160 /* LabeledStatement */: + case 161 /* DoStatement */: + case 162 /* DebuggerStatement */: + return true; + } + } + return false; + }; + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement; + var parent = positionedElement.parent; + if (parent !== null && (element.kind() === 80 /* LessThanToken */ || element.kind() === 81 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 228 /* TypeArgumentList */: + case 229 /* TypeParameterList */: + case 220 /* CastExpression */: + return true; + } + } + return false; + }; + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.length; i < n; i++) { + var token = list[i]; + if (token.kind() === kind) { + return token; + } + } + return null; + }; + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + return SyntaxUtilities.getExportKeyword(moduleElement) !== null; + }; + SyntaxUtilities.getExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + case 133 /* ImportDeclaration */: + return SyntaxUtilities.getToken(moduleElement.modifiers, 47 /* ExportKeyword */); + default: + return null; + } + }; + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + var node = positionNode; + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + return true; + } + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + if (SyntaxUtilities.isClassElement(node) || SyntaxUtilities.isModuleElement(node)) { + return SyntaxUtilities.isAmbientDeclarationSyntax(TypeScript.Syntax.containingNode(positionNode)); + } + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(TypeScript.Syntax.containingNode(TypeScript.Syntax.containingNode(positionNode))); + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(TypeScript.Syntax.containingNode(positionNode)); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function visitNodeOrToken(visitor, element) { + if (element === null) { + return null; + } + if (TypeScript.isToken(element)) { + return visitor.visitToken(element); + } + switch (element.kind()) { + case 120 /* SourceUnit */: + return visitor.visitSourceUnit(element); + case 121 /* QualifiedName */: + return visitor.visitQualifiedName(element); + case 122 /* ObjectType */: + return visitor.visitObjectType(element); + case 123 /* FunctionType */: + return visitor.visitFunctionType(element); + case 124 /* ArrayType */: + return visitor.visitArrayType(element); + case 125 /* ConstructorType */: + return visitor.visitConstructorType(element); + case 126 /* GenericType */: + return visitor.visitGenericType(element); + case 127 /* TypeQuery */: + return visitor.visitTypeQuery(element); + case 128 /* InterfaceDeclaration */: + return visitor.visitInterfaceDeclaration(element); + case 129 /* FunctionDeclaration */: + return visitor.visitFunctionDeclaration(element); + case 130 /* ModuleDeclaration */: + return visitor.visitModuleDeclaration(element); + case 131 /* ClassDeclaration */: + return visitor.visitClassDeclaration(element); + case 132 /* EnumDeclaration */: + return visitor.visitEnumDeclaration(element); + case 133 /* ImportDeclaration */: + return visitor.visitImportDeclaration(element); + case 134 /* ExportAssignment */: + return visitor.visitExportAssignment(element); + case 135 /* MemberFunctionDeclaration */: + return visitor.visitMemberFunctionDeclaration(element); + case 136 /* MemberVariableDeclaration */: + return visitor.visitMemberVariableDeclaration(element); + case 137 /* ConstructorDeclaration */: + return visitor.visitConstructorDeclaration(element); + case 138 /* IndexMemberDeclaration */: + return visitor.visitIndexMemberDeclaration(element); + case 139 /* GetAccessor */: + return visitor.visitGetAccessor(element); + case 140 /* SetAccessor */: + return visitor.visitSetAccessor(element); + case 141 /* PropertySignature */: + return visitor.visitPropertySignature(element); + case 142 /* CallSignature */: + return visitor.visitCallSignature(element); + case 143 /* ConstructSignature */: + return visitor.visitConstructSignature(element); + case 144 /* IndexSignature */: + return visitor.visitIndexSignature(element); + case 145 /* MethodSignature */: + return visitor.visitMethodSignature(element); + case 146 /* Block */: + return visitor.visitBlock(element); + case 147 /* IfStatement */: + return visitor.visitIfStatement(element); + case 148 /* VariableStatement */: + return visitor.visitVariableStatement(element); + case 149 /* ExpressionStatement */: + return visitor.visitExpressionStatement(element); + case 150 /* ReturnStatement */: + return visitor.visitReturnStatement(element); + case 151 /* SwitchStatement */: + return visitor.visitSwitchStatement(element); + case 152 /* BreakStatement */: + return visitor.visitBreakStatement(element); + case 153 /* ContinueStatement */: + return visitor.visitContinueStatement(element); + case 154 /* ForStatement */: + return visitor.visitForStatement(element); + case 155 /* ForInStatement */: + return visitor.visitForInStatement(element); + case 156 /* EmptyStatement */: + return visitor.visitEmptyStatement(element); + case 157 /* ThrowStatement */: + return visitor.visitThrowStatement(element); + case 158 /* WhileStatement */: + return visitor.visitWhileStatement(element); + case 159 /* TryStatement */: + return visitor.visitTryStatement(element); + case 160 /* LabeledStatement */: + return visitor.visitLabeledStatement(element); + case 161 /* DoStatement */: + return visitor.visitDoStatement(element); + case 162 /* DebuggerStatement */: + return visitor.visitDebuggerStatement(element); + case 163 /* WithStatement */: + return visitor.visitWithStatement(element); + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 167 /* LogicalNotExpression */: + return visitor.visitPrefixUnaryExpression(element); + case 170 /* DeleteExpression */: + return visitor.visitDeleteExpression(element); + case 171 /* TypeOfExpression */: + return visitor.visitTypeOfExpression(element); + case 172 /* VoidExpression */: + return visitor.visitVoidExpression(element); + case 186 /* ConditionalExpression */: + return visitor.visitConditionalExpression(element); + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 191 /* BitwiseAndExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 189 /* BitwiseOrExpression */: + case 188 /* LogicalAndExpression */: + case 187 /* LogicalOrExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 174 /* AssignmentExpression */: + case 173 /* CommaExpression */: + return visitor.visitBinaryExpression(element); + case 210 /* PostIncrementExpression */: + case 211 /* PostDecrementExpression */: + return visitor.visitPostfixUnaryExpression(element); + case 212 /* MemberAccessExpression */: + return visitor.visitMemberAccessExpression(element); + case 213 /* InvocationExpression */: + return visitor.visitInvocationExpression(element); + case 214 /* ArrayLiteralExpression */: + return visitor.visitArrayLiteralExpression(element); + case 215 /* ObjectLiteralExpression */: + return visitor.visitObjectLiteralExpression(element); + case 216 /* ObjectCreationExpression */: + return visitor.visitObjectCreationExpression(element); + case 217 /* ParenthesizedExpression */: + return visitor.visitParenthesizedExpression(element); + case 218 /* ParenthesizedArrowFunctionExpression */: + return visitor.visitParenthesizedArrowFunctionExpression(element); + case 219 /* SimpleArrowFunctionExpression */: + return visitor.visitSimpleArrowFunctionExpression(element); + case 220 /* CastExpression */: + return visitor.visitCastExpression(element); + case 221 /* ElementAccessExpression */: + return visitor.visitElementAccessExpression(element); + case 222 /* FunctionExpression */: + return visitor.visitFunctionExpression(element); + case 223 /* OmittedExpression */: + return visitor.visitOmittedExpression(element); + case 224 /* VariableDeclaration */: + return visitor.visitVariableDeclaration(element); + case 225 /* VariableDeclarator */: + return visitor.visitVariableDeclarator(element); + case 226 /* ArgumentList */: + return visitor.visitArgumentList(element); + case 227 /* ParameterList */: + return visitor.visitParameterList(element); + case 228 /* TypeArgumentList */: + return visitor.visitTypeArgumentList(element); + case 229 /* TypeParameterList */: + return visitor.visitTypeParameterList(element); + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + return visitor.visitHeritageClause(element); + case 232 /* EqualsValueClause */: + return visitor.visitEqualsValueClause(element); + case 233 /* CaseSwitchClause */: + return visitor.visitCaseSwitchClause(element); + case 234 /* DefaultSwitchClause */: + return visitor.visitDefaultSwitchClause(element); + case 235 /* ElseClause */: + return visitor.visitElseClause(element); + case 236 /* CatchClause */: + return visitor.visitCatchClause(element); + case 237 /* FinallyClause */: + return visitor.visitFinallyClause(element); + case 238 /* TypeParameter */: + return visitor.visitTypeParameter(element); + case 239 /* Constraint */: + return visitor.visitConstraint(element); + case 240 /* SimplePropertyAssignment */: + return visitor.visitSimplePropertyAssignment(element); + case 241 /* FunctionPropertyAssignment */: + return visitor.visitFunctionPropertyAssignment(element); + case 242 /* Parameter */: + return visitor.visitParameter(element); + case 243 /* EnumElement */: + return visitor.visitEnumElement(element); + case 244 /* TypeAnnotation */: + return visitor.visitTypeAnnotation(element); + case 245 /* ExternalModuleReference */: + return visitor.visitExternalModuleReference(element); + case 246 /* ModuleNameModuleReference */: + return visitor.visitModuleNameModuleReference(element); + } + throw TypeScript.Errors.invalidOperation(); + } + TypeScript.visitNodeOrToken = visitNodeOrToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + SyntaxWalker.prototype.visitNode = function (node) { + TypeScript.visitNodeOrToken(this, node); + }; + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (TypeScript.isToken(nodeOrToken)) { + this.visitToken(nodeOrToken); + } + else { + this.visitNode(nodeOrToken); + } + }; + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + this.visitToken(token); + }; + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + this.visitNode(node); + }; + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + this.visitNodeOrToken(nodeOrToken); + }; + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.length; i < n; i++) { + this.visitNodeOrToken(list[i]); + } + }; + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = TypeScript.childCount(list); i < n; i++) { + var item = TypeScript.childAt(list, i); + this.visitNodeOrToken(item); + } + }; + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + SyntaxWalker.prototype.visitTypeQuery = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.name); + }; + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.name); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.moduleReference); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.constructorKeyword); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitIndexMemberDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.indexSignature); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitGetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + SyntaxWalker.prototype.visitSetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitOptionalToken(node.semicolonToken); + }; + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitNode(node.parameter); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.typeOrExpression); + }; + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitList(node.modifiers); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.requireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } + }; + return DepthLimitedWalker; + })(TypeScript.SyntaxWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + Parser.syntaxFactory; + var arrayPool = []; + var arrayPoolCount = 0; + function getArray() { + if (arrayPoolCount === 0) { + return []; + } + arrayPoolCount--; + var result = arrayPool[arrayPoolCount]; + arrayPool[arrayPoolCount] = null; + return result; + } + function returnZeroLengthArray(array) { + if (array.length === 0) { + returnArray(array); + } + } + function returnArray(array) { + array.length = 0; + arrayPool[arrayPoolCount] = array; + arrayPoolCount++; + } + function createParseSyntaxTree() { + var fileName; + var source; + var languageVersion; + var listParsingState = 0; + var isInStrictMode = false; + var diagnostics = []; + var parseNodeData = 0; + function parseSyntaxTree(_source, isDeclaration) { + fileName = _source.fileName; + source = _source; + languageVersion = source.languageVersion; + var result = parseSyntaxTreeWorker(isDeclaration); + diagnostics = []; + parseNodeData = 0 /* None */; + fileName = null; + source.release(); + source = null; + _source = null; + return result; + } + function parseSyntaxTreeWorker(isDeclaration) { + var sourceUnit = parseSourceUnit(); + var allDiagnostics = source.tokenDiagnostics().concat(diagnostics); + allDiagnostics.sort(function (a, b) { return a.start() - b.start(); }); + return new TypeScript.SyntaxTree(Parser.syntaxFactory.isConcrete, sourceUnit, isDeclaration, allDiagnostics, fileName, source.text, languageVersion); + } + function getRewindPoint() { + var rewindPoint = source.getRewindPoint(); + rewindPoint.diagnosticsCount = diagnostics.length; + rewindPoint.isInStrictMode = isInStrictMode; + rewindPoint.listParsingState = listParsingState; + return rewindPoint; + } + function rewind(rewindPoint) { + source.rewind(rewindPoint); + diagnostics.length = rewindPoint.diagnosticsCount; + } + function releaseRewindPoint(rewindPoint) { + source.releaseRewindPoint(rewindPoint); + } + function currentNode() { + var node = source.currentNode(); + if (node === null || TypeScript.parsedInStrictMode(node) !== isInStrictMode) { + return null; + } + return node; + } + function currentToken() { + return source.currentToken(); + } + function currentContextualToken() { + return source.currentContextualToken(); + } + function peekToken(n) { + return source.peekToken(n); + } + function consumeToken(token) { + source.consumeToken(token); + return token; + } + function consumeNode(node) { + source.consumeNode(node); + } + function eatToken(kind) { + var token = currentToken(); + if (token.kind() === kind) { + return consumeToken(token); + } + return createMissingToken(kind, token); + } + function tryEatToken(kind) { + var _currentToken = currentToken(); + if (_currentToken.kind() === kind) { + return consumeToken(_currentToken); + } + return null; + } + function isIdentifier(token) { + var tokenKind = token.kind(); + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + if (tokenKind >= TypeScript.SyntaxKind.FirstFutureReservedStrictKeyword) { + if (tokenKind <= TypeScript.SyntaxKind.LastFutureReservedStrictKeyword) { + return !isInStrictMode; + } + return tokenKind <= TypeScript.SyntaxKind.LastTypeScriptKeyword; + } + return false; + } + function eatIdentifierNameToken() { + var token = currentToken(); + var tokenKind = token.kind(); + if (tokenKind === 11 /* IdentifierName */) { + return consumeToken(token); + } + if (TypeScript.SyntaxFacts.isAnyKeyword(tokenKind)) { + return TypeScript.Syntax.convertKeywordToIdentifier(consumeToken(token)); + } + return createMissingToken(11 /* IdentifierName */, token); + } + function eatOptionalIdentifierToken() { + return isIdentifier(currentToken()) ? eatIdentifierToken() : null; + } + function eatIdentifierToken(diagnosticCode) { + var token = currentToken(); + if (isIdentifier(token)) { + consumeToken(token); + if (token.kind() === 11 /* IdentifierName */) { + return token; + } + return TypeScript.Syntax.convertKeywordToIdentifier(token); + } + return createMissingToken(11 /* IdentifierName */, token, diagnosticCode); + } + function previousTokenHasTrailingNewLine(token) { + var tokenFullStart = token.fullStart(); + if (tokenFullStart === 0) { + return false; + } + var lineNumber = source.text.lineMap().getLineNumberFromPosition(tokenFullStart); + var lineStart = source.text.lineMap().getLineStartPosition(lineNumber); + return lineStart == tokenFullStart; + } + function canEatAutomaticSemicolon(allowWithoutNewLine) { + var token = currentToken(); + var tokenKind = token.kind(); + if (tokenKind === 10 /* EndOfFileToken */) { + return true; + } + if (tokenKind === 71 /* CloseBraceToken */) { + return true; + } + if (allowWithoutNewLine) { + return true; + } + if (previousTokenHasTrailingNewLine(token)) { + return true; + } + return false; + } + function canEatExplicitOrAutomaticSemicolon(allowWithoutNewline) { + var token = currentToken(); + if (token.kind() === 78 /* SemicolonToken */) { + return true; + } + return canEatAutomaticSemicolon(allowWithoutNewline); + } + function eatExplicitOrAutomaticSemicolon(allowWithoutNewline) { + var token = currentToken(); + if (token.kind() === 78 /* SemicolonToken */) { + return consumeToken(token); + } + if (canEatAutomaticSemicolon(allowWithoutNewline)) { + return null; + } + return eatToken(78 /* SemicolonToken */); + } + function createMissingToken(expectedKind, actual, diagnosticCode) { + var diagnostic = getExpectedTokenDiagnostic(expectedKind, actual, diagnosticCode); + addDiagnostic(diagnostic); + return TypeScript.Syntax.emptyToken(expectedKind); + } + function getExpectedTokenDiagnostic(expectedKind, actual, diagnosticCode) { + var token = currentToken(); + var args = null; + if (!diagnosticCode) { + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + diagnosticCode = TypeScript.DiagnosticCode._0_expected; + args = [TypeScript.SyntaxFacts.getText(expectedKind)]; + } + else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.kind())) { + diagnosticCode = TypeScript.DiagnosticCode.Identifier_expected_0_is_a_keyword; + args = [TypeScript.SyntaxFacts.getText(actual.kind())]; + } + else { + diagnosticCode = TypeScript.DiagnosticCode.Identifier_expected; + } + } + } + return new TypeScript.Diagnostic(fileName, source.text.lineMap(), TypeScript.start(token, source.text), TypeScript.width(token), diagnosticCode, args); + } + function getBinaryExpressionPrecedence(tokenKind) { + switch (tokenKind) { + case 104 /* BarBarToken */: + return 2 /* LogicalOrExpressionPrecedence */; + case 103 /* AmpersandAmpersandToken */: + return 3 /* LogicalAndExpressionPrecedence */; + case 99 /* BarToken */: + return 4 /* BitwiseOrExpressionPrecedence */; + case 100 /* CaretToken */: + return 5 /* BitwiseExclusiveOrExpressionPrecedence */; + case 98 /* AmpersandToken */: + return 6 /* BitwiseAndExpressionPrecedence */; + case 84 /* EqualsEqualsToken */: + case 86 /* ExclamationEqualsToken */: + case 87 /* EqualsEqualsEqualsToken */: + case 88 /* ExclamationEqualsEqualsToken */: + return 7 /* EqualityExpressionPrecedence */; + case 80 /* LessThanToken */: + case 81 /* GreaterThanToken */: + case 82 /* LessThanEqualsToken */: + case 83 /* GreaterThanEqualsToken */: + case 30 /* InstanceOfKeyword */: + case 29 /* InKeyword */: + return 8 /* RelationalExpressionPrecedence */; + case 95 /* LessThanLessThanToken */: + case 96 /* GreaterThanGreaterThanToken */: + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + return 9 /* ShiftExpressionPrecdence */; + case 89 /* PlusToken */: + case 90 /* MinusToken */: + return 10 /* AdditiveExpressionPrecedence */; + case 91 /* AsteriskToken */: + case 118 /* SlashToken */: + case 92 /* PercentToken */: + return 11 /* MultiplicativeExpressionPrecedence */; + } + throw TypeScript.Errors.invalidOperation(); + } + function addSkippedTokenAfterNodeOrToken(nodeOrToken, skippedToken) { + if (TypeScript.isToken(nodeOrToken)) { + return addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } + else if (TypeScript.isNode(nodeOrToken)) { + return addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } + else { + throw TypeScript.Errors.invalidOperation(); + } + } + function replaceTokenInParent(oldToken, newToken) { + replaceTokenInParentWorker(oldToken, newToken); + var parent = oldToken.parent; + newToken.parent = parent; + TypeScript.Debug.assert(TypeScript.isNode(parent) || TypeScript.isList(parent) || TypeScript.isSeparatedList(parent)); + var dataElement = parent; + if (dataElement.data) { + dataElement.data &= 4 /* NodeParsedInStrictModeMask */; + } + } + function replaceTokenInParentWorker(oldToken, newToken) { + var parent = oldToken.parent; + if (TypeScript.isNode(parent)) { + var node = parent; + for (var key in node) { + if (node[key] === oldToken) { + node[key] = newToken; + return; + } + } + } + else if (TypeScript.isList(parent)) { + var list1 = parent; + for (var i = 0, n = list1.length; i < n; i++) { + if (list1[i] === oldToken) { + list1[i] = newToken; + return; + } + } + } + else if (TypeScript.isSeparatedList(parent)) { + var list2 = parent; + for (var i = 0, n = TypeScript.childCount(list2); i < n; i++) { + if (TypeScript.childAt(list2, i) === oldToken) { + if (i % 2 === 0) { + list2[i / 2] = newToken; + } + else { + list2.separators[(i - 1) / 2] = newToken; + } + return; + } + } + } + throw TypeScript.Errors.invalidOperation(); + } + function addSkippedTokenAfterNode(node, skippedToken) { + var oldToken = TypeScript.lastToken(node); + var newToken = addSkippedTokenAfterToken(oldToken, skippedToken); + replaceTokenInParent(oldToken, newToken); + return node; + } + function addSkippedTokensBeforeNode(node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = TypeScript.firstToken(node); + var newToken = addSkippedTokensBeforeToken(oldToken, skippedTokens); + replaceTokenInParent(oldToken, newToken); + } + return node; + } + function addSkippedTokensBeforeToken(token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + var skippedToken = skippedTokens[i]; + addSkippedTokenToTriviaArray(leadingTrivia, skippedToken); + } + addTriviaTo(token.leadingTrivia(source.text), leadingTrivia); + var updatedToken = TypeScript.Syntax.withLeadingTrivia(token, TypeScript.Syntax.triviaList(leadingTrivia), source.text); + updatedToken.setFullStart(skippedTokens[0].fullStart()); + returnArray(skippedTokens); + return updatedToken; + } + function addSkippedTokensAfterToken(token, skippedTokens) { + if (skippedTokens.length === 0) { + returnArray(skippedTokens); + return token; + } + var trailingTrivia = token.trailingTrivia(source.text).toArray(); + for (var i = 0, n = skippedTokens.length; i < n; i++) { + addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + returnArray(skippedTokens); + return TypeScript.Syntax.withTrailingTrivia(token, TypeScript.Syntax.triviaList(trailingTrivia), source.text); + } + function addSkippedTokenAfterToken(token, skippedToken) { + var trailingTrivia = token.trailingTrivia(source.text).toArray(); + addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + return TypeScript.Syntax.withTrailingTrivia(token, TypeScript.Syntax.triviaList(trailingTrivia), source.text); + } + function addSkippedTokenToTriviaArray(array, skippedToken) { + addTriviaTo(skippedToken.leadingTrivia(source.text), array); + var trimmedToken = TypeScript.Syntax.withTrailingTrivia(TypeScript.Syntax.withLeadingTrivia(skippedToken, TypeScript.Syntax.emptyTriviaList, source.text), TypeScript.Syntax.emptyTriviaList, source.text); + trimmedToken.setFullStart(TypeScript.start(skippedToken, source.text)); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken, source.text)); + addTriviaTo(skippedToken.trailingTrivia(source.text), array); + } + function addTriviaTo(list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + } + function setStrictMode(_isInStrictMode) { + isInStrictMode = _isInStrictMode; + parseNodeData = _isInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + function parseSourceUnit() { + var savedIsInStrictMode = isInStrictMode; + var skippedTokens = getArray(); + var moduleElements = parseSyntaxList(0 /* SourceUnit_ModuleElements */, skippedTokens, updateStrictModeState); + setStrictMode(savedIsInStrictMode); + var sourceUnit = new Parser.syntaxFactory.SourceUnitSyntax(parseNodeData, moduleElements, currentToken()); + sourceUnit = addSkippedTokensBeforeNode(sourceUnit, skippedTokens); + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert(TypeScript.fullWidth(sourceUnit) === source.text.length()); + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + TypeScript.Debug.assert(TypeScript.fullText(sourceUnit) === source.text.substr(0, source.text.length())); + } + } + return sourceUnit; + } + function updateStrictModeState(items) { + if (!isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + } + function isModuleElement(inErrorRecovery) { + if (TypeScript.SyntaxUtilities.isModuleElement(currentNode())) { + return true; + } + var _modifierCount = modifierCount(); + return isInterfaceEnumClassModuleImportOrExport(_modifierCount) || isStatement(_modifierCount, inErrorRecovery); + } + function tryParseModuleElement(inErrorRecovery) { + var node = currentNode(); + if (TypeScript.SyntaxUtilities.isModuleElement(node)) { + consumeNode(node); + return node; + } + var _currentToken = currentToken(); + var _modifierCount = modifierCount(); + if (_modifierCount) { + switch (peekToken(_modifierCount).kind()) { + case 49 /* ImportKeyword */: + return parseImportDeclaration(); + case 65 /* ModuleKeyword */: + return parseModuleDeclaration(); + case 52 /* InterfaceKeyword */: + return parseInterfaceDeclaration(); + case 44 /* ClassKeyword */: + return parseClassDeclaration(); + case 46 /* EnumKeyword */: + return parseEnumDeclaration(); + } + } + var nextToken = peekToken(1); + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 65 /* ModuleKeyword */: + if (isIdentifier(nextToken) || nextToken.kind() === 14 /* StringLiteral */) { + return parseModuleDeclaration(); + } + break; + case 49 /* ImportKeyword */: + if (isIdentifier(nextToken)) { + return parseImportDeclaration(); + } + break; + case 44 /* ClassKeyword */: + if (isIdentifier(nextToken)) { + return parseClassDeclaration(); + } + break; + case 46 /* EnumKeyword */: + if (isIdentifier(nextToken)) { + return parseEnumDeclaration(); + } + break; + case 52 /* InterfaceKeyword */: + if (isIdentifier(nextToken)) { + return parseInterfaceDeclaration(); + } + break; + case 47 /* ExportKeyword */: + if (nextToken.kind() === 107 /* EqualsToken */) { + return parseExportAssignment(); + } + break; + } + return tryParseStatementWorker(_currentToken, currentTokenKind, _modifierCount, inErrorRecovery); + } + function parseImportDeclaration() { + return new Parser.syntaxFactory.ImportDeclarationSyntax(parseNodeData, parseModifiers(), eatToken(49 /* ImportKeyword */), eatIdentifierToken(), eatToken(107 /* EqualsToken */), parseModuleReference(), eatExplicitOrAutomaticSemicolon(false)); + } + function parseExportAssignment() { + return new Parser.syntaxFactory.ExportAssignmentSyntax(parseNodeData, eatToken(47 /* ExportKeyword */), eatToken(107 /* EqualsToken */), eatIdentifierToken(), eatExplicitOrAutomaticSemicolon(false)); + } + function parseModuleReference() { + return isExternalModuleReference() ? parseExternalModuleReference() : parseModuleNameModuleReference(); + } + function isExternalModuleReference() { + return currentToken().kind() === 66 /* RequireKeyword */ && peekToken(1).kind() === 72 /* OpenParenToken */; + } + function parseExternalModuleReference() { + return new Parser.syntaxFactory.ExternalModuleReferenceSyntax(parseNodeData, eatToken(66 /* RequireKeyword */), eatToken(72 /* OpenParenToken */), eatToken(14 /* StringLiteral */), eatToken(73 /* CloseParenToken */)); + } + function parseModuleNameModuleReference() { + return new Parser.syntaxFactory.ModuleNameModuleReferenceSyntax(parseNodeData, parseName(false)); + } + function tryParseTypeArgumentList(inExpression) { + var _currentToken = currentToken(); + if (_currentToken.kind() !== 80 /* LessThanToken */) { + return null; + } + if (!inExpression) { + var lessThanToken = consumeToken(_currentToken); + var skippedTokens = getArray(); + var typeArguments = parseSeparatedSyntaxList(19 /* TypeArgumentList_Types */, skippedTokens); + lessThanToken = addSkippedTokensAfterToken(lessThanToken, skippedTokens); + return new Parser.syntaxFactory.TypeArgumentListSyntax(parseNodeData, lessThanToken, typeArguments, eatToken(81 /* GreaterThanToken */)); + } + var rewindPoint = getRewindPoint(); + var lessThanToken = consumeToken(_currentToken); + var skippedTokens = getArray(); + var typeArguments = parseSeparatedSyntaxList(19 /* TypeArgumentList_Types */, skippedTokens); + var lessThanToken = addSkippedTokensAfterToken(lessThanToken, skippedTokens); + var greaterThanToken = eatToken(81 /* GreaterThanToken */); + if (greaterThanToken.fullWidth() === 0 || !canFollowTypeArgumentListInExpression(currentToken().kind())) { + rewind(rewindPoint); + releaseRewindPoint(rewindPoint); + return null; + } + else { + releaseRewindPoint(rewindPoint); + return new Parser.syntaxFactory.TypeArgumentListSyntax(parseNodeData, lessThanToken, typeArguments, greaterThanToken); + } + } + function canFollowTypeArgumentListInExpression(kind) { + switch (kind) { + case 72 /* OpenParenToken */: + case 76 /* DotToken */: + case 73 /* CloseParenToken */: + case 75 /* CloseBracketToken */: + case 106 /* ColonToken */: + case 78 /* SemicolonToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + case 84 /* EqualsEqualsToken */: + case 87 /* EqualsEqualsEqualsToken */: + case 86 /* ExclamationEqualsToken */: + case 88 /* ExclamationEqualsEqualsToken */: + case 103 /* AmpersandAmpersandToken */: + case 104 /* BarBarToken */: + case 100 /* CaretToken */: + case 98 /* AmpersandToken */: + case 99 /* BarToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } + function parseName(allowIdentifierName) { + return tryParseName(allowIdentifierName) || eatIdentifierToken(); + } + function eatRightSideOfName(allowIdentifierNames) { + var _currentToken = currentToken(); + if (TypeScript.SyntaxFacts.isAnyKeyword(_currentToken.kind()) && previousTokenHasTrailingNewLine(_currentToken)) { + var token1 = peekToken(1); + if (!TypeScript.existsNewLineBetweenTokens(_currentToken, token1, source.text) && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return createMissingToken(11 /* IdentifierName */, _currentToken); + } + } + return allowIdentifierNames ? eatIdentifierNameToken() : eatIdentifierToken(); + } + function tryParseName(allowIdentifierNames) { + var token0 = currentToken(); + var shouldContinue = isIdentifier(token0); + if (!shouldContinue) { + return null; + } + var current = eatIdentifierToken(); + while (shouldContinue && currentToken().kind() === 76 /* DotToken */) { + var dotToken = consumeToken(currentToken()); + var identifierName = eatRightSideOfName(allowIdentifierNames); + current = new Parser.syntaxFactory.QualifiedNameSyntax(parseNodeData, current, dotToken, identifierName); + shouldContinue = identifierName.fullWidth() > 0; + } + return current; + } + function parseEnumDeclaration() { + var modifiers = parseModifiers(); + var enumKeyword = eatToken(46 /* EnumKeyword */); + var identifier = eatIdentifierToken(); + var openBraceToken = eatToken(70 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList(); + if (openBraceToken.fullWidth() > 0) { + var skippedTokens = getArray(); + enumElements = parseSeparatedSyntaxList(8 /* EnumDeclaration_EnumElements */, skippedTokens); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + } + return new Parser.syntaxFactory.EnumDeclarationSyntax(parseNodeData, modifiers, enumKeyword, identifier, openBraceToken, enumElements, eatToken(71 /* CloseBraceToken */)); + } + function isEnumElement(inErrorRecovery) { + var node = currentNode(); + if (node !== null && node.kind() === 243 /* EnumElement */) { + return true; + } + return isPropertyName(currentToken(), inErrorRecovery); + } + function tryParseEnumElementEqualsValueClause() { + return isEqualsValueClause(false) ? parseEqualsValueClause(true) : null; + } + function tryParseEnumElement(inErrorRecovery) { + var node = currentNode(); + if (node !== null && node.kind() === 243 /* EnumElement */) { + consumeNode(node); + return node; + } + if (!isPropertyName(currentToken(), inErrorRecovery)) { + return null; + } + return new Parser.syntaxFactory.EnumElementSyntax(parseNodeData, eatPropertyName(), tryParseEnumElementEqualsValueClause()); + } + function isModifierKind(kind) { + switch (kind) { + case 47 /* ExportKeyword */: + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 63 /* DeclareKeyword */: + return true; + } + return false; + } + function isModifier(token, index) { + if (isModifierKind(token.kind())) { + var nextToken = peekToken(index + 1); + var nextTokenKind = nextToken.kind(); + switch (nextTokenKind) { + case 11 /* IdentifierName */: + case 74 /* OpenBracketToken */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + return true; + default: + return TypeScript.SyntaxFacts.isAnyKeyword(nextTokenKind); + } + } + return false; + } + function modifierCount() { + var modifierCount = 0; + while (isModifier(peekToken(modifierCount), modifierCount)) { + modifierCount++; + } + return modifierCount; + } + function parseModifiers() { + var tokens = getArray(); + while (true) { + var token = currentToken(); + if (isModifier(token, 0)) { + tokens.push(consumeToken(token)); + continue; + } + break; + } + var result = TypeScript.Syntax.list(tokens); + returnZeroLengthArray(tokens); + return result; + } + function parseHeritageClauses() { + var heritageClauses = TypeScript.Syntax.emptyList(); + if (isHeritageClause()) { + heritageClauses = parseSyntaxList(10 /* ClassOrInterfaceDeclaration_HeritageClauses */, null); + } + return heritageClauses; + } + function tryParseHeritageClauseTypeName() { + return isHeritageClauseTypeName() ? tryParseNameOrGenericType() : null; + } + function parseClassDeclaration() { + var modifiers = parseModifiers(); + var classKeyword = eatToken(44 /* ClassKeyword */); + var identifier = eatIdentifierToken(); + var typeParameterList = tryParseTypeParameterList(false); + var heritageClauses = parseHeritageClauses(); + var openBraceToken = eatToken(70 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList(); + if (openBraceToken.fullWidth() > 0) { + var skippedTokens = getArray(); + classElements = parseSyntaxList(1 /* ClassDeclaration_ClassElements */, skippedTokens); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + } + ; + return new Parser.syntaxFactory.ClassDeclarationSyntax(parseNodeData, modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, eatToken(71 /* CloseBraceToken */)); + } + function isAccessor(modifierCount, inErrorRecovery) { + var tokenKind = peekToken(modifierCount).kind(); + if (tokenKind !== 64 /* GetKeyword */ && tokenKind !== 68 /* SetKeyword */) { + return false; + } + return isPropertyName(peekToken(modifierCount + 1), inErrorRecovery); + } + function parseAccessor(checkForStrictMode) { + var modifiers = parseModifiers(); + var _currenToken = currentToken(); + var tokenKind = _currenToken.kind(); + if (tokenKind === 64 /* GetKeyword */) { + return parseGetMemberAccessorDeclaration(modifiers, _currenToken, checkForStrictMode); + } + else if (tokenKind === 68 /* SetKeyword */) { + return parseSetMemberAccessorDeclaration(modifiers, _currenToken, checkForStrictMode); + } + else { + throw TypeScript.Errors.invalidOperation(); + } + } + function parseGetMemberAccessorDeclaration(modifiers, getKeyword, checkForStrictMode) { + return new Parser.syntaxFactory.GetAccessorSyntax(parseNodeData, modifiers, consumeToken(getKeyword), eatPropertyName(), parseCallSignature(false), parseBlock(false, checkForStrictMode)); + } + function parseSetMemberAccessorDeclaration(modifiers, setKeyword, checkForStrictMode) { + return new Parser.syntaxFactory.SetAccessorSyntax(parseNodeData, modifiers, consumeToken(setKeyword), eatPropertyName(), parseCallSignature(false), parseBlock(false, checkForStrictMode)); + } + function isClassElement(inErrorRecovery) { + if (TypeScript.SyntaxUtilities.isClassElement(currentNode())) { + return true; + } + var _modifierCount = modifierCount(); + return isConstructorDeclaration(_modifierCount) || isMemberFunctionDeclaration(_modifierCount, inErrorRecovery) || isAccessor(_modifierCount, inErrorRecovery) || isMemberVariableDeclaration(_modifierCount, inErrorRecovery) || isIndexMemberDeclaration(_modifierCount); + } + function tryParseClassElement(inErrorRecovery) { + var node = currentNode(); + if (TypeScript.SyntaxUtilities.isClassElement(node)) { + consumeNode(node); + return node; + } + var _modifierCount = modifierCount(); + if (isConstructorDeclaration(_modifierCount)) { + return parseConstructorDeclaration(); + } + else if (isMemberFunctionDeclaration(_modifierCount, inErrorRecovery)) { + return parseMemberFunctionDeclaration(); + } + else if (isAccessor(_modifierCount, inErrorRecovery)) { + return parseAccessor(false); + } + else if (isMemberVariableDeclaration(_modifierCount, inErrorRecovery)) { + return parseMemberVariableDeclaration(); + } + else if (isIndexMemberDeclaration(_modifierCount)) { + return parseIndexMemberDeclaration(); + } + else { + return null; + } + } + function isConstructorDeclaration(modifierCount) { + return peekToken(modifierCount).kind() === 62 /* ConstructorKeyword */; + } + function parseConstructorDeclaration() { + var modifiers = parseModifiers(); + var constructorKeyword = eatToken(62 /* ConstructorKeyword */); + var callSignature = parseCallSignature(false); + var semicolonToken = null; + var block = null; + if (isBlock()) { + block = parseBlock(false, true); + } + else { + semicolonToken = eatExplicitOrAutomaticSemicolon(false); + } + return new Parser.syntaxFactory.ConstructorDeclarationSyntax(parseNodeData, modifiers, constructorKeyword, callSignature, block, semicolonToken); + } + function isMemberFunctionDeclaration(modifierCount, inErrorRecovery) { + return isPropertyName(peekToken(modifierCount), inErrorRecovery) && isCallSignature(modifierCount + 1); + } + function parseMemberFunctionDeclaration() { + var modifiers = parseModifiers(); + var propertyName = eatPropertyName(); + var callSignature = parseCallSignature(false); + var parseBlockEvenWithNoOpenBrace = tryAddUnexpectedEqualsGreaterThanToken(callSignature); + var block = null; + var semicolon = null; + if (parseBlockEvenWithNoOpenBrace || isBlock()) { + block = parseBlock(parseBlockEvenWithNoOpenBrace, true); + } + else { + semicolon = eatExplicitOrAutomaticSemicolon(false); + } + return new Parser.syntaxFactory.MemberFunctionDeclarationSyntax(parseNodeData, modifiers, propertyName, callSignature, block, semicolon); + } + function isDefinitelyMemberVariablePropertyName(index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(peekToken(index).kind())) { + var nextToken = peekToken(index + 1); + switch (nextToken.kind()) { + case 78 /* SemicolonToken */: + case 107 /* EqualsToken */: + case 106 /* ColonToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return previousTokenHasTrailingNewLine(nextToken); + } + } + else { + return true; + } + } + function isMemberVariableDeclaration(modifierCount, inErrorRecover) { + return isPropertyName(peekToken(modifierCount), inErrorRecover) && isDefinitelyMemberVariablePropertyName(modifierCount); + } + function parseMemberVariableDeclaration() { + return new Parser.syntaxFactory.MemberVariableDeclarationSyntax(parseNodeData, parseModifiers(), tryParseVariableDeclarator(true, true), eatExplicitOrAutomaticSemicolon(false)); + } + function isIndexMemberDeclaration(modifierCount) { + return isIndexSignature(modifierCount); + } + function parseIndexMemberDeclaration() { + return new Parser.syntaxFactory.IndexMemberDeclarationSyntax(parseNodeData, parseModifiers(), parseIndexSignature(), eatExplicitOrAutomaticSemicolon(false)); + } + function tryAddUnexpectedEqualsGreaterThanToken(callSignature) { + var token0 = currentToken(); + var hasEqualsGreaterThanToken = token0.kind() === 85 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + var _lastToken = TypeScript.lastToken(callSignature); + if (_lastToken && _lastToken.fullWidth() > 0) { + var diagnostic = new TypeScript.Diagnostic(fileName, source.text.lineMap(), TypeScript.start(token0, source.text), TypeScript.width(token0), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [TypeScript.SyntaxFacts.getText(70 /* OpenBraceToken */)]); + addDiagnostic(diagnostic); + consumeToken(token0); + if (Parser.syntaxFactory.isConcrete) { + addSkippedTokenAfterNode(callSignature, token0); + } + return true; + } + } + return false; + } + function isFunctionDeclaration(modifierCount) { + return peekToken(modifierCount).kind() === 27 /* FunctionKeyword */; + } + function parseFunctionDeclaration() { + var modifiers = parseModifiers(); + var functionKeyword = eatToken(27 /* FunctionKeyword */); + var identifier = eatIdentifierToken(); + var callSignature = parseCallSignature(false); + var parseBlockEvenWithNoOpenBrace = tryAddUnexpectedEqualsGreaterThanToken(callSignature); + var semicolonToken = null; + var block = null; + if (parseBlockEvenWithNoOpenBrace || isBlock()) { + block = parseBlock(parseBlockEvenWithNoOpenBrace, true); + } + else { + semicolonToken = eatExplicitOrAutomaticSemicolon(false); + } + return new Parser.syntaxFactory.FunctionDeclarationSyntax(parseNodeData, modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + } + function parseModuleDeclaration() { + var modifiers = parseModifiers(); + var moduleKeyword = eatToken(65 /* ModuleKeyword */); + var moduleName = null; + var stringLiteral = null; + if (currentToken().kind() === 14 /* StringLiteral */) { + stringLiteral = eatToken(14 /* StringLiteral */); + } + else { + moduleName = parseName(false); + } + var openBraceToken = eatToken(70 /* OpenBraceToken */); + var moduleElements = TypeScript.Syntax.emptyList(); + if (openBraceToken.fullWidth() > 0) { + var skippedTokens = getArray(); + moduleElements = parseSyntaxList(2 /* ModuleDeclaration_ModuleElements */, skippedTokens); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + } + return new Parser.syntaxFactory.ModuleDeclarationSyntax(parseNodeData, modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, eatToken(71 /* CloseBraceToken */)); + } + function parseInterfaceDeclaration() { + return new Parser.syntaxFactory.InterfaceDeclarationSyntax(parseNodeData, parseModifiers(), eatToken(52 /* InterfaceKeyword */), eatIdentifierToken(), tryParseTypeParameterList(false), parseHeritageClauses(), parseObjectType()); + } + function parseObjectType() { + var openBraceToken = eatToken(70 /* OpenBraceToken */); + var typeMembers = TypeScript.Syntax.emptySeparatedList(); + if (openBraceToken.fullWidth() > 0) { + var skippedTokens = getArray(); + typeMembers = parseSeparatedSyntaxList(9 /* ObjectType_TypeMembers */, skippedTokens); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + } + return new Parser.syntaxFactory.ObjectTypeSyntax(parseNodeData, openBraceToken, typeMembers, eatToken(71 /* CloseBraceToken */)); + } + function isTypeMember(inErrorRecovery) { + if (TypeScript.SyntaxUtilities.isTypeMember(currentNode())) { + return true; + } + return isCallSignature(0) || isConstructSignature() || isIndexSignature(0) || isMethodSignature(inErrorRecovery) || isPropertySignature(inErrorRecovery); + } + function tryParseTypeMember(inErrorRecovery) { + var node = currentNode(); + if (TypeScript.SyntaxUtilities.isTypeMember(node)) { + consumeNode(node); + return node; + } + if (isCallSignature(0)) { + return parseCallSignature(false); + } + else if (isConstructSignature()) { + return parseConstructSignature(); + } + else if (isIndexSignature(0)) { + return parseIndexSignature(); + } + else if (isMethodSignature(inErrorRecovery)) { + return parseMethodSignature(); + } + else if (isPropertySignature(inErrorRecovery)) { + return parsePropertySignature(); + } + else { + return null; + } + } + function parseConstructSignature() { + return new Parser.syntaxFactory.ConstructSignatureSyntax(parseNodeData, eatToken(31 /* NewKeyword */), parseCallSignature(false)); + } + function parseIndexSignature() { + var openBracketToken = eatToken(74 /* OpenBracketToken */); + var skippedTokens = getArray(); + var parameters = parseSeparatedSyntaxList(18 /* IndexSignature_Parameters */, skippedTokens); + openBracketToken = addSkippedTokensAfterToken(openBracketToken, skippedTokens); + return new Parser.syntaxFactory.IndexSignatureSyntax(parseNodeData, openBracketToken, parameters, eatToken(75 /* CloseBracketToken */), parseOptionalTypeAnnotation(false)); + } + function parseMethodSignature() { + return new Parser.syntaxFactory.MethodSignatureSyntax(parseNodeData, eatPropertyName(), tryEatToken(105 /* QuestionToken */), parseCallSignature(false)); + } + function parsePropertySignature() { + return new Parser.syntaxFactory.PropertySignatureSyntax(parseNodeData, eatPropertyName(), tryEatToken(105 /* QuestionToken */), parseOptionalTypeAnnotation(false)); + } + function isCallSignature(peekIndex) { + var tokenKind = peekToken(peekIndex).kind(); + return tokenKind === 72 /* OpenParenToken */ || tokenKind === 80 /* LessThanToken */; + } + function isConstructSignature() { + if (currentToken().kind() !== 31 /* NewKeyword */) { + return false; + } + return isCallSignature(1); + } + function isIndexSignature(peekIndex) { + return peekToken(peekIndex).kind() === 74 /* OpenBracketToken */; + } + function isMethodSignature(inErrorRecovery) { + if (isPropertyName(currentToken(), inErrorRecovery)) { + if (isCallSignature(1)) { + return true; + } + if (peekToken(1).kind() === 105 /* QuestionToken */ && isCallSignature(2)) { + return true; + } + } + return false; + } + function isPropertySignature(inErrorRecovery) { + var _currentToken = currentToken(); + if (isModifier(_currentToken, 0)) { + if (!TypeScript.existsNewLineBetweenTokens(_currentToken, peekToken(1), source.text) && isPropertyName(peekToken(1), inErrorRecovery)) { + return false; + } + } + return isPropertyName(_currentToken, inErrorRecovery); + } + function isHeritageClause() { + var tokenKind = currentToken().kind(); + return tokenKind === 48 /* ExtendsKeyword */ || tokenKind === 51 /* ImplementsKeyword */; + } + function isNotHeritageClauseTypeName() { + var tokenKind = currentToken().kind(); + if (tokenKind === 51 /* ImplementsKeyword */ || tokenKind === 48 /* ExtendsKeyword */) { + return isIdentifier(peekToken(1)); + } + return false; + } + function isHeritageClauseTypeName() { + if (isIdentifier(currentToken())) { + return !isNotHeritageClauseTypeName(); + } + return false; + } + function tryParseHeritageClause() { + var extendsOrImplementsKeyword = currentToken(); + var tokenKind = extendsOrImplementsKeyword.kind(); + if (tokenKind !== 48 /* ExtendsKeyword */ && tokenKind !== 51 /* ImplementsKeyword */) { + return null; + } + consumeToken(extendsOrImplementsKeyword); + var skippedTokens = getArray(); + var typeNames = parseSeparatedSyntaxList(11 /* HeritageClause_TypeNameList */, skippedTokens); + extendsOrImplementsKeyword = addSkippedTokensAfterToken(extendsOrImplementsKeyword, skippedTokens); + return new Parser.syntaxFactory.HeritageClauseSyntax(parseNodeData, extendsOrImplementsKeyword, typeNames); + } + function isInterfaceEnumClassModuleImportOrExport(modifierCount) { + var _currentToken = currentToken(); + if (modifierCount) { + switch (peekToken(modifierCount).kind()) { + case 49 /* ImportKeyword */: + case 65 /* ModuleKeyword */: + case 52 /* InterfaceKeyword */: + case 44 /* ClassKeyword */: + case 46 /* EnumKeyword */: + return true; + } + } + var nextToken = peekToken(1); + switch (_currentToken.kind()) { + case 65 /* ModuleKeyword */: + if (isIdentifier(nextToken) || nextToken.kind() === 14 /* StringLiteral */) { + return true; + } + break; + case 49 /* ImportKeyword */: + case 44 /* ClassKeyword */: + case 46 /* EnumKeyword */: + case 52 /* InterfaceKeyword */: + if (isIdentifier(nextToken)) { + return true; + } + break; + case 47 /* ExportKeyword */: + if (nextToken.kind() === 107 /* EqualsToken */) { + return true; + } + break; + } + return false; + } + function isStatement(modifierCount, inErrorRecovery) { + if (TypeScript.SyntaxUtilities.isStatement(currentNode())) { + return true; + } + var _currentToken = currentToken(); + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + break; + case 28 /* IfKeyword */: + case 70 /* OpenBraceToken */: + case 33 /* ReturnKeyword */: + case 34 /* SwitchKeyword */: + case 36 /* ThrowKeyword */: + case 15 /* BreakKeyword */: + case 18 /* ContinueKeyword */: + case 26 /* ForKeyword */: + case 42 /* WhileKeyword */: + case 43 /* WithKeyword */: + case 22 /* DoKeyword */: + case 38 /* TryKeyword */: + case 19 /* DebuggerKeyword */: + return true; + } + if (isInterfaceEnumClassModuleImportOrExport(modifierCount)) { + return false; + } + return isLabeledStatement(_currentToken) || isVariableStatement(modifierCount) || isFunctionDeclaration(modifierCount) || isEmptyStatement(_currentToken, inErrorRecovery) || isExpressionStatement(_currentToken); + } + function parseStatement(inErrorRecovery) { + return tryParseStatement(inErrorRecovery) || parseExpressionStatement(); + } + function tryParseStatement(inErrorRecovery) { + var node = currentNode(); + if (TypeScript.SyntaxUtilities.isStatement(node)) { + consumeNode(node); + return node; + } + var _currentToken = currentToken(); + var currentTokenKind = _currentToken.kind(); + return tryParseStatementWorker(_currentToken, currentTokenKind, modifierCount(), inErrorRecovery); + } + function tryParseStatementWorker(_currentToken, currentTokenKind, modifierCount, inErrorRecovery) { + switch (currentTokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(peekToken(1))) { + return null; + } + else { + break; + } + case 28 /* IfKeyword */: + return parseIfStatement(_currentToken); + case 70 /* OpenBraceToken */: + return parseBlock(false, false); + case 33 /* ReturnKeyword */: + return parseReturnStatement(_currentToken); + case 34 /* SwitchKeyword */: + return parseSwitchStatement(_currentToken); + case 36 /* ThrowKeyword */: + return parseThrowStatement(_currentToken); + case 15 /* BreakKeyword */: + return parseBreakStatement(_currentToken); + case 18 /* ContinueKeyword */: + return parseContinueStatement(_currentToken); + case 26 /* ForKeyword */: + return parseForOrForInStatement(_currentToken); + case 42 /* WhileKeyword */: + return parseWhileStatement(_currentToken); + case 43 /* WithKeyword */: + return parseWithStatement(_currentToken); + case 22 /* DoKeyword */: + return parseDoStatement(_currentToken); + case 38 /* TryKeyword */: + return parseTryStatement(_currentToken); + case 19 /* DebuggerKeyword */: + return parseDebuggerStatement(_currentToken); + } + if (isInterfaceEnumClassModuleImportOrExport(modifierCount)) { + return null; + } + else if (isVariableStatement(modifierCount)) { + return parseVariableStatement(); + } + else if (isLabeledStatement(_currentToken)) { + return parseLabeledStatement(_currentToken); + } + else if (isFunctionDeclaration(modifierCount)) { + return parseFunctionDeclaration(); + } + else if (isEmptyStatement(_currentToken, inErrorRecovery)) { + return parseEmptyStatement(_currentToken); + } + else if (isExpressionStatement(_currentToken)) { + return parseExpressionStatement(); + } + else { + return null; + } + } + function parseDebuggerStatement(debuggerKeyword) { + return new Parser.syntaxFactory.DebuggerStatementSyntax(parseNodeData, consumeToken(debuggerKeyword), eatExplicitOrAutomaticSemicolon(false)); + } + function parseDoStatement(doKeyword) { + return new Parser.syntaxFactory.DoStatementSyntax(parseNodeData, consumeToken(doKeyword), parseStatement(false), eatToken(42 /* WhileKeyword */), eatToken(72 /* OpenParenToken */), parseExpression(true), eatToken(73 /* CloseParenToken */), eatExplicitOrAutomaticSemicolon(true)); + } + function isLabeledStatement(currentToken) { + return isIdentifier(currentToken) && peekToken(1).kind() === 106 /* ColonToken */; + } + function parseLabeledStatement(identifierToken) { + return new Parser.syntaxFactory.LabeledStatementSyntax(parseNodeData, consumeToken(identifierToken), eatToken(106 /* ColonToken */), parseStatement(false)); + } + function parseTryStatement(tryKeyword) { + var tryKeyword = consumeToken(tryKeyword); + var savedListParsingState = listParsingState; + listParsingState |= (1 << 6 /* TryBlock_Statements */); + var block = parseBlock(false, false); + listParsingState = savedListParsingState; + var catchClause = null; + if (currentToken().kind() === 17 /* CatchKeyword */) { + catchClause = parseCatchClause(); + } + var finallyClause = null; + if (catchClause === null || currentToken().kind() === 25 /* FinallyKeyword */) { + finallyClause = parseFinallyClause(); + } + return new Parser.syntaxFactory.TryStatementSyntax(parseNodeData, tryKeyword, block, catchClause, finallyClause); + } + function parseCatchClauseBlock() { + var savedListParsingState = listParsingState; + listParsingState |= (1 << 7 /* CatchBlock_Statements */); + var block = parseBlock(false, false); + listParsingState = savedListParsingState; + return block; + } + function parseCatchClause() { + return new Parser.syntaxFactory.CatchClauseSyntax(parseNodeData, eatToken(17 /* CatchKeyword */), eatToken(72 /* OpenParenToken */), eatIdentifierToken(), parseOptionalTypeAnnotation(false), eatToken(73 /* CloseParenToken */), parseCatchClauseBlock()); + } + function parseFinallyClause() { + return new Parser.syntaxFactory.FinallyClauseSyntax(parseNodeData, eatToken(25 /* FinallyKeyword */), parseBlock(false, false)); + } + function parseWithStatement(withKeyword) { + return new Parser.syntaxFactory.WithStatementSyntax(parseNodeData, consumeToken(withKeyword), eatToken(72 /* OpenParenToken */), parseExpression(true), eatToken(73 /* CloseParenToken */), parseStatement(false)); + } + function parseWhileStatement(whileKeyword) { + return new Parser.syntaxFactory.WhileStatementSyntax(parseNodeData, consumeToken(whileKeyword), eatToken(72 /* OpenParenToken */), parseExpression(true), eatToken(73 /* CloseParenToken */), parseStatement(false)); + } + function isEmptyStatement(currentToken, inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + return currentToken.kind() === 78 /* SemicolonToken */; + } + function parseEmptyStatement(semicolonToken) { + return new Parser.syntaxFactory.EmptyStatementSyntax(parseNodeData, consumeToken(semicolonToken)); + } + function parseForOrForInStatement(forKeyword) { + consumeToken(forKeyword); + var openParenToken = eatToken(72 /* OpenParenToken */); + var _currentToken = currentToken(); + var tokenKind = _currentToken.kind(); + if (tokenKind === 40 /* VarKeyword */) { + return parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } + else if (tokenKind === 78 /* SemicolonToken */) { + return parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword, openParenToken); + } + else { + return parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + } + function parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken) { + var variableDeclaration = parseVariableDeclaration(false); + return currentToken().kind() === 29 /* InKeyword */ ? parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null) : parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + function parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, initializer) { + return new Parser.syntaxFactory.ForInStatementSyntax(parseNodeData, forKeyword, openParenToken, variableDeclaration, initializer, eatToken(29 /* InKeyword */), parseExpression(true), eatToken(73 /* CloseParenToken */), parseStatement(false)); + } + function parseForOrForInStatementWithInitializer(forKeyword, openParenToken) { + var initializer = parseExpression(false); + return currentToken().kind() === 29 /* InKeyword */ ? parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer) : parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + function parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword, openParenToken) { + return parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, null); + } + function tryParseForStatementCondition() { + var tokenKind = currentToken().kind(); + if (tokenKind !== 78 /* SemicolonToken */ && tokenKind !== 73 /* CloseParenToken */ && tokenKind !== 10 /* EndOfFileToken */) { + return parseExpression(true); + } + return null; + } + function tryParseForStatementIncrementor() { + var tokenKind = currentToken().kind(); + if (tokenKind !== 73 /* CloseParenToken */ && tokenKind !== 10 /* EndOfFileToken */) { + return parseExpression(true); + } + return null; + } + function parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, initializer) { + return new Parser.syntaxFactory.ForStatementSyntax(parseNodeData, forKeyword, openParenToken, variableDeclaration, initializer, eatToken(78 /* SemicolonToken */), tryParseForStatementCondition(), eatToken(78 /* SemicolonToken */), tryParseForStatementIncrementor(), eatToken(73 /* CloseParenToken */), parseStatement(false)); + } + function tryEatBreakOrContinueLabel() { + var identifier = null; + if (!canEatExplicitOrAutomaticSemicolon(false)) { + if (isIdentifier(currentToken())) { + return eatIdentifierToken(); + } + } + return null; + } + function parseBreakStatement(breakKeyword) { + return new Parser.syntaxFactory.BreakStatementSyntax(parseNodeData, consumeToken(breakKeyword), tryEatBreakOrContinueLabel(), eatExplicitOrAutomaticSemicolon(false)); + } + function parseContinueStatement(continueKeyword) { + return new Parser.syntaxFactory.ContinueStatementSyntax(parseNodeData, consumeToken(continueKeyword), tryEatBreakOrContinueLabel(), eatExplicitOrAutomaticSemicolon(false)); + } + function parseSwitchStatement(switchKeyword) { + consumeToken(switchKeyword); + var openParenToken = eatToken(72 /* OpenParenToken */); + var expression = parseExpression(true); + var closeParenToken = eatToken(73 /* CloseParenToken */); + var openBraceToken = eatToken(70 /* OpenBraceToken */); + var switchClauses = TypeScript.Syntax.emptyList(); + if (openBraceToken.fullWidth() > 0) { + var skippedTokens = getArray(); + switchClauses = parseSyntaxList(3 /* SwitchStatement_SwitchClauses */, skippedTokens); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + } + return new Parser.syntaxFactory.SwitchStatementSyntax(parseNodeData, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, eatToken(71 /* CloseBraceToken */)); + } + function isSwitchClause() { + if (TypeScript.SyntaxUtilities.isSwitchClause(currentNode())) { + return true; + } + var currentTokenKind = currentToken().kind(); + return currentTokenKind === 16 /* CaseKeyword */ || currentTokenKind === 20 /* DefaultKeyword */; + } + function tryParseSwitchClause() { + var node = currentNode(); + if (TypeScript.SyntaxUtilities.isSwitchClause(node)) { + consumeNode(node); + return node; + } + var _currentToken = currentToken(); + var kind = _currentToken.kind(); + if (kind === 16 /* CaseKeyword */) { + return parseCaseSwitchClause(_currentToken); + } + else if (kind === 20 /* DefaultKeyword */) { + return parseDefaultSwitchClause(_currentToken); + } + else { + return null; + } + } + function parseCaseSwitchClause(caseKeyword) { + consumeToken(caseKeyword); + var expression = parseExpression(true); + var colonToken = eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList(); + if (colonToken.fullWidth() > 0) { + var skippedTokens = getArray(); + statements = parseSyntaxList(4 /* SwitchClause_Statements */, skippedTokens); + colonToken = addSkippedTokensAfterToken(colonToken, skippedTokens); + } + return new Parser.syntaxFactory.CaseSwitchClauseSyntax(parseNodeData, caseKeyword, expression, colonToken, statements); + } + function parseDefaultSwitchClause(defaultKeyword) { + consumeToken(defaultKeyword); + var colonToken = eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList(); + if (colonToken.fullWidth() > 0) { + var skippedTokens = getArray(); + statements = parseSyntaxList(4 /* SwitchClause_Statements */, skippedTokens); + colonToken = addSkippedTokensAfterToken(colonToken, skippedTokens); + } + return new Parser.syntaxFactory.DefaultSwitchClauseSyntax(parseNodeData, defaultKeyword, colonToken, statements); + } + function parseThrowStatementExpression() { + return canEatExplicitOrAutomaticSemicolon(false) ? createMissingToken(11 /* IdentifierName */, null) : parseExpression(true); + } + function parseThrowStatement(throwKeyword) { + return new Parser.syntaxFactory.ThrowStatementSyntax(parseNodeData, consumeToken(throwKeyword), parseThrowStatementExpression(), eatExplicitOrAutomaticSemicolon(false)); + } + function tryParseReturnStatementExpression() { + return !canEatExplicitOrAutomaticSemicolon(false) ? parseExpression(true) : null; + } + function parseReturnStatement(returnKeyword) { + return new Parser.syntaxFactory.ReturnStatementSyntax(parseNodeData, consumeToken(returnKeyword), tryParseReturnStatementExpression(), eatExplicitOrAutomaticSemicolon(false)); + } + function isExpressionStatement(currentToken) { + var tokenKind = currentToken.kind(); + return tokenKind !== 70 /* OpenBraceToken */ && tokenKind !== 27 /* FunctionKeyword */ && isExpression(currentToken); + } + function isAssignmentOrOmittedExpression() { + var _currentToken = currentToken(); + return _currentToken.kind() === 79 /* CommaToken */ || isExpression(_currentToken); + } + function tryParseAssignmentOrOmittedExpression() { + if (currentToken().kind() === 79 /* CommaToken */) { + return new Parser.syntaxFactory.OmittedExpressionSyntax(parseNodeData); + } + return tryParseAssignmentExpressionOrHigher(false, true); + } + function isExpression(currentToken) { + switch (currentToken.kind()) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 74 /* OpenBracketToken */: + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 89 /* PlusToken */: + case 90 /* MinusToken */: + case 102 /* TildeToken */: + case 101 /* ExclamationToken */: + case 70 /* OpenBraceToken */: + case 85 /* EqualsGreaterThanToken */: + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 31 /* NewKeyword */: + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + case 27 /* FunctionKeyword */: + return true; + } + return isIdentifier(currentToken); + } + function parseExpressionStatement() { + return new Parser.syntaxFactory.ExpressionStatementSyntax(parseNodeData, parseExpression(true), eatExplicitOrAutomaticSemicolon(false)); + } + function parseIfStatement(ifKeyword) { + return new Parser.syntaxFactory.IfStatementSyntax(parseNodeData, consumeToken(ifKeyword), eatToken(72 /* OpenParenToken */), parseExpression(true), eatToken(73 /* CloseParenToken */), parseStatement(false), parseOptionalElseClause()); + } + function parseOptionalElseClause() { + return currentToken().kind() === 23 /* ElseKeyword */ ? parseElseClause() : null; + } + function parseElseClause() { + return new Parser.syntaxFactory.ElseClauseSyntax(parseNodeData, eatToken(23 /* ElseKeyword */), parseStatement(false)); + } + function isVariableStatement(modifierCount) { + return peekToken(modifierCount).kind() === 40 /* VarKeyword */; + } + function parseVariableStatement() { + return new Parser.syntaxFactory.VariableStatementSyntax(parseNodeData, parseModifiers(), parseVariableDeclaration(true), eatExplicitOrAutomaticSemicolon(false)); + } + function parseVariableDeclaration(allowIn) { + var varKeyword = eatToken(40 /* VarKeyword */); + var listParsingState = allowIn ? 12 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 13 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + var skippedTokens = getArray(); + var variableDeclarators = parseSeparatedSyntaxList(listParsingState, skippedTokens); + varKeyword = addSkippedTokensAfterToken(varKeyword, skippedTokens); + return new Parser.syntaxFactory.VariableDeclarationSyntax(parseNodeData, varKeyword, variableDeclarators); + } + function isVariableDeclarator() { + var node = currentNode(); + if (node !== null && node.kind() === 225 /* VariableDeclarator */) { + return true; + } + return isIdentifier(currentToken()); + } + function canReuseVariableDeclaratorNode(node) { + if (node === null || node.kind() !== 225 /* VariableDeclarator */) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + } + function tryParseVariableDeclarator(allowIn, allowPropertyName) { + var node = currentNode(); + if (canReuseVariableDeclaratorNode(node)) { + consumeNode(node); + return node; + } + if (allowPropertyName) { + } + if (!allowPropertyName && !isIdentifier(currentToken())) { + return null; + } + var propertyName = allowPropertyName ? eatPropertyName() : eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + if (propertyName.fullWidth() > 0) { + typeAnnotation = parseOptionalTypeAnnotation(false); + if (isEqualsValueClause(false)) { + equalsValueClause = parseEqualsValueClause(allowIn); + } + } + return new Parser.syntaxFactory.VariableDeclaratorSyntax(parseNodeData, propertyName, typeAnnotation, equalsValueClause); + } + function isEqualsValueClause(inParameter) { + var token0 = currentToken(); + if (token0.kind() === 107 /* EqualsToken */) { + return true; + } + if (!previousTokenHasTrailingNewLine(token0)) { + var tokenKind = token0.kind(); + if (tokenKind === 85 /* EqualsGreaterThanToken */) { + return false; + } + if (tokenKind === 70 /* OpenBraceToken */ && inParameter) { + return false; + } + return isExpression(token0); + } + return false; + } + function parseEqualsValueClause(allowIn) { + return new Parser.syntaxFactory.EqualsValueClauseSyntax(parseNodeData, eatToken(107 /* EqualsToken */), tryParseAssignmentExpressionOrHigher(true, allowIn)); + } + function parseExpression(allowIn) { + var leftOperand = tryParseAssignmentExpressionOrHigher(true, allowIn); + while (true) { + var _currentToken = currentToken(); + if (_currentToken.kind() !== 79 /* CommaToken */) { + break; + } + leftOperand = new Parser.syntaxFactory.BinaryExpressionSyntax(parseNodeData, leftOperand, consumeToken(_currentToken), tryParseAssignmentExpressionOrHigher(true, allowIn)); + } + return leftOperand; + } + function tryParseAssignmentExpressionOrHigher(force, allowIn) { + var _currentToken = currentToken(); + var arrowFunction = tryParseAnyArrowFunctionExpression(_currentToken); + if (arrowFunction !== null) { + return arrowFunction; + } + var leftOperand = tryParseBinaryExpressionOrHigher(_currentToken, force, 1 /* Lowest */, allowIn); + if (leftOperand === null) { + return null; + } + if (TypeScript.SyntaxUtilities.isLeftHandSizeExpression(leftOperand)) { + var operatorToken = currentOperatorToken(); + if (TypeScript.SyntaxFacts.isAssignmentOperatorToken(operatorToken.kind())) { + return new Parser.syntaxFactory.BinaryExpressionSyntax(parseNodeData, leftOperand, consumeToken(operatorToken), tryParseAssignmentExpressionOrHigher(true, allowIn)); + } + } + return parseConditionalExpressionRest(allowIn, leftOperand); + } + function tryParseAnyArrowFunctionExpression(_currentToken) { + return isSimpleArrowFunctionExpression(_currentToken) ? parseSimpleArrowFunctionExpression() : tryParseParenthesizedArrowFunctionExpression(); + } + function tryParseUnaryExpressionOrHigher(_currentToken, force) { + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 89 /* PlusToken */: + case 90 /* MinusToken */: + case 102 /* TildeToken */: + case 101 /* ExclamationToken */: + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + return new Parser.syntaxFactory.PrefixUnaryExpressionSyntax(parseNodeData, consumeToken(_currentToken), tryParseUnaryExpressionOrHigher(currentToken(), true)); + case 39 /* TypeOfKeyword */: + return parseTypeOfExpression(_currentToken); + case 41 /* VoidKeyword */: + return parseVoidExpression(_currentToken); + case 21 /* DeleteKeyword */: + return parseDeleteExpression(_currentToken); + case 80 /* LessThanToken */: + return parseCastExpression(_currentToken); + default: + return tryParsePostfixExpressionOrHigher(_currentToken, force); + } + } + function tryParseBinaryExpressionOrHigher(_currentToken, force, precedence, allowIn) { + var leftOperand = tryParseUnaryExpressionOrHigher(_currentToken, force); + if (leftOperand === null) { + return null; + } + return parseBinaryExpressionRest(precedence, allowIn, leftOperand); + } + function parseConditionalExpressionRest(allowIn, leftOperand) { + var _currentToken = currentToken(); + if (_currentToken.kind() !== 105 /* QuestionToken */) { + return leftOperand; + } + return new Parser.syntaxFactory.ConditionalExpressionSyntax(parseNodeData, leftOperand, consumeToken(_currentToken), tryParseAssignmentExpressionOrHigher(true, true), eatToken(106 /* ColonToken */), tryParseAssignmentExpressionOrHigher(true, allowIn)); + } + function parseBinaryExpressionRest(precedence, allowIn, leftOperand) { + while (true) { + var operatorToken = currentOperatorToken(); + var tokenKind = operatorToken.kind(); + if (!TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(tokenKind) || tokenKind === 79 /* CommaToken */ || TypeScript.SyntaxFacts.isAssignmentOperatorToken(tokenKind)) { + break; + } + if (tokenKind === 29 /* InKeyword */ && !allowIn) { + break; + } + var newPrecedence = getBinaryExpressionPrecedence(tokenKind); + if (newPrecedence <= precedence) { + break; + } + leftOperand = new Parser.syntaxFactory.BinaryExpressionSyntax(parseNodeData, leftOperand, consumeToken(operatorToken), tryParseBinaryExpressionOrHigher(currentToken(), true, newPrecedence, allowIn)); + } + return leftOperand; + } + function currentOperatorToken() { + var token0 = currentToken(); + if (token0.kind() === 81 /* GreaterThanToken */) { + return currentContextualToken(); + } + return token0; + } + function tryParseMemberExpressionOrHigher(_currentToken, force, inObjectCreation) { + var expression = tryParsePrimaryExpression(_currentToken, force); + if (expression === null) { + return null; + } + return parseMemberExpressionRest(expression, inObjectCreation); + } + function parseCallExpressionRest(expression) { + while (true) { + var _currentToken = currentToken(); + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 72 /* OpenParenToken */: + expression = new Parser.syntaxFactory.InvocationExpressionSyntax(parseNodeData, expression, parseArgumentList(null)); + continue; + case 80 /* LessThanToken */: + var argumentList = tryParseArgumentList(); + if (argumentList === null) { + break; + } + expression = new Parser.syntaxFactory.InvocationExpressionSyntax(parseNodeData, expression, argumentList); + continue; + case 74 /* OpenBracketToken */: + expression = parseElementAccessExpression(expression, _currentToken, false); + continue; + case 76 /* DotToken */: + expression = new Parser.syntaxFactory.MemberAccessExpressionSyntax(parseNodeData, expression, consumeToken(_currentToken), eatIdentifierNameToken()); + continue; + } + return expression; + } + } + function parseMemberExpressionRest(expression, inObjectCreation) { + while (true) { + var _currentToken = currentToken(); + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 74 /* OpenBracketToken */: + expression = parseElementAccessExpression(expression, _currentToken, inObjectCreation); + continue; + case 76 /* DotToken */: + expression = new Parser.syntaxFactory.MemberAccessExpressionSyntax(parseNodeData, expression, consumeToken(_currentToken), eatIdentifierNameToken()); + continue; + } + return expression; + } + } + function tryParseLeftHandSideExpressionOrHigher(_currentToken, force) { + var expression = null; + if (_currentToken.kind() === 50 /* SuperKeyword */) { + expression = parseSuperExpression(_currentToken); + } + else { + expression = tryParseMemberExpressionOrHigher(_currentToken, force, false); + if (expression === null) { + return null; + } + } + return parseCallExpressionRest(expression); + } + function parseSuperExpression(superToken) { + var expression = consumeToken(superToken); + var currentTokenKind = currentToken().kind(); + return currentTokenKind === 72 /* OpenParenToken */ || currentTokenKind === 76 /* DotToken */ ? expression : new Parser.syntaxFactory.MemberAccessExpressionSyntax(parseNodeData, expression, eatToken(76 /* DotToken */), eatIdentifierNameToken()); + } + function tryParsePostfixExpressionOrHigher(_currentToken, force) { + var expression = tryParseLeftHandSideExpressionOrHigher(_currentToken, force); + if (expression === null) { + return null; + } + var _currentToken = currentToken(); + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + if (previousTokenHasTrailingNewLine(_currentToken)) { + break; + } + return new Parser.syntaxFactory.PostfixUnaryExpressionSyntax(parseNodeData, expression, consumeToken(_currentToken)); + } + return expression; + } + function tryParseGenericArgumentList() { + var rewindPoint = getRewindPoint(); + var typeArgumentList = tryParseTypeArgumentList(true); + var token0 = currentToken(); + var tokenKind = token0.kind(); + var isOpenParen = tokenKind === 72 /* OpenParenToken */; + var isDot = tokenKind === 76 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + var argumentList = null; + if (typeArgumentList === null || !isOpenParenOrDot) { + rewind(rewindPoint); + releaseRewindPoint(rewindPoint); + return null; + } + else { + releaseRewindPoint(rewindPoint); + if (isDot) { + var diagnostic = new TypeScript.Diagnostic(fileName, source.text.lineMap(), TypeScript.start(token0, source.text), TypeScript.width(token0), TypeScript.DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, null); + addDiagnostic(diagnostic); + return new Parser.syntaxFactory.ArgumentListSyntax(parseNodeData, typeArgumentList, TypeScript.Syntax.emptyToken(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList(), TypeScript.Syntax.emptyToken(73 /* CloseParenToken */)); + } + else { + return parseArgumentList(typeArgumentList); + } + } + } + function tryParseArgumentList() { + var tokenKind = currentToken().kind(); + if (tokenKind === 80 /* LessThanToken */) { + return tryParseGenericArgumentList(); + } + if (tokenKind === 72 /* OpenParenToken */) { + return parseArgumentList(null); + } + return null; + } + function parseArgumentList(typeArgumentList) { + var openParenToken = eatToken(72 /* OpenParenToken */); + var _arguments = TypeScript.Syntax.emptySeparatedList(); + if (openParenToken.fullWidth() > 0) { + var skippedTokens = getArray(); + _arguments = parseSeparatedSyntaxList(14 /* ArgumentList_AssignmentExpressions */, skippedTokens); + openParenToken = addSkippedTokensAfterToken(openParenToken, skippedTokens); + } + return new Parser.syntaxFactory.ArgumentListSyntax(parseNodeData, typeArgumentList, openParenToken, _arguments, eatToken(73 /* CloseParenToken */)); + } + function tryParseArgumentListExpression() { + var force = currentToken().kind() === 79 /* CommaToken */; + return tryParseAssignmentExpressionOrHigher(force, true); + } + function parseElementAccessArgumentExpression(openBracketToken, inObjectCreation) { + if (inObjectCreation && currentToken().kind() === 75 /* CloseBracketToken */) { + var errorStart = TypeScript.start(openBracketToken, source.text); + var errorEnd = TypeScript.end(currentToken(), source.text); + var diagnostic = new TypeScript.Diagnostic(fileName, source.text.lineMap(), errorStart, errorEnd - errorStart, TypeScript.DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, null); + addDiagnostic(diagnostic); + return TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } + else { + return parseExpression(true); + } + } + function parseElementAccessExpression(expression, openBracketToken, inObjectCreation) { + return new Parser.syntaxFactory.ElementAccessExpressionSyntax(parseNodeData, expression, consumeToken(openBracketToken), parseElementAccessArgumentExpression(openBracketToken, inObjectCreation), eatToken(75 /* CloseBracketToken */)); + } + function tryParsePrimaryExpression(_currentToken, force) { + if (isIdentifier(_currentToken)) { + return eatIdentifierToken(); + } + var currentTokenKind = _currentToken.kind(); + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 14 /* StringLiteral */: + return consumeToken(_currentToken); + case 27 /* FunctionKeyword */: + return parseFunctionExpression(_currentToken); + case 74 /* OpenBracketToken */: + return parseArrayLiteralExpression(_currentToken); + case 70 /* OpenBraceToken */: + return parseObjectLiteralExpression(_currentToken); + case 72 /* OpenParenToken */: + return parseParenthesizedExpression(_currentToken); + case 31 /* NewKeyword */: + return parseObjectCreationExpression(_currentToken); + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + var result = tryReparseDivideAsRegularExpression(); + return result || eatIdentifierToken(TypeScript.DiagnosticCode.Expression_expected); + } + if (!force) { + return null; + } + return eatIdentifierToken(TypeScript.DiagnosticCode.Expression_expected); + } + function tryReparseDivideAsRegularExpression() { + var currentToken = currentContextualToken(); + var tokenKind = currentToken.kind(); + if (tokenKind === 118 /* SlashToken */ || tokenKind === 119 /* SlashEqualsToken */) { + return null; + } + else if (tokenKind === 12 /* RegularExpressionLiteral */) { + return consumeToken(currentToken); + } + else { + throw TypeScript.Errors.invalidOperation(); + } + } + function parseTypeOfExpression(typeOfKeyword) { + return new Parser.syntaxFactory.TypeOfExpressionSyntax(parseNodeData, consumeToken(typeOfKeyword), tryParseUnaryExpressionOrHigher(currentToken(), true)); + } + function parseDeleteExpression(deleteKeyword) { + return new Parser.syntaxFactory.DeleteExpressionSyntax(parseNodeData, consumeToken(deleteKeyword), tryParseUnaryExpressionOrHigher(currentToken(), true)); + } + function parseVoidExpression(voidKeyword) { + return new Parser.syntaxFactory.VoidExpressionSyntax(parseNodeData, consumeToken(voidKeyword), tryParseUnaryExpressionOrHigher(currentToken(), true)); + } + function parseFunctionExpression(functionKeyword) { + return new Parser.syntaxFactory.FunctionExpressionSyntax(parseNodeData, consumeToken(functionKeyword), eatOptionalIdentifierToken(), parseCallSignature(false), parseBlock(false, true)); + } + function parseObjectCreationExpression(newKeyword) { + return new Parser.syntaxFactory.ObjectCreationExpressionSyntax(parseNodeData, consumeToken(newKeyword), tryParseMemberExpressionOrHigher(currentToken(), true, true), tryParseArgumentList()); + } + function parseCastExpression(lessThanToken) { + return new Parser.syntaxFactory.CastExpressionSyntax(parseNodeData, consumeToken(lessThanToken), parseType(), eatToken(81 /* GreaterThanToken */), tryParseUnaryExpressionOrHigher(currentToken(), true)); + } + function parseParenthesizedExpression(openParenToken) { + return new Parser.syntaxFactory.ParenthesizedExpressionSyntax(parseNodeData, consumeToken(openParenToken), parseExpression(true), eatToken(73 /* CloseParenToken */)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var tokenKind = currentToken().kind(); + if (tokenKind !== 72 /* OpenParenToken */ && tokenKind !== 80 /* LessThanToken */) { + return null; + } + if (isDefinitelyArrowFunctionExpression()) { + return tryParseParenthesizedArrowFunctionExpressionWorker(false); + } + if (!isPossiblyArrowFunctionExpression()) { + return null; + } + var rewindPoint = getRewindPoint(); + var arrowFunction = tryParseParenthesizedArrowFunctionExpressionWorker(true); + if (arrowFunction === null) { + rewind(rewindPoint); + } + releaseRewindPoint(rewindPoint); + return arrowFunction; + } + function tryParseParenthesizedArrowFunctionExpressionWorker(requireArrow) { + var _currentToken = currentToken(); + var callSignature = parseCallSignature(true); + if (requireArrow && currentToken().kind() !== 85 /* EqualsGreaterThanToken */) { + return null; + } + var equalsGreaterThanToken = eatToken(85 /* EqualsGreaterThanToken */); + var block = tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = tryParseAssignmentExpressionOrHigher(true, true); + } + return new Parser.syntaxFactory.ParenthesizedArrowFunctionExpressionSyntax(parseNodeData, callSignature, equalsGreaterThanToken, block, expression); + } + function tryParseArrowFunctionBlock() { + if (isBlock()) { + return parseBlock(false, false); + } + else { + var _modifierCount = modifierCount(); + if (isStatement(_modifierCount, false) && !isExpressionStatement(currentToken()) && !isFunctionDeclaration(_modifierCount)) { + return parseBlock(true, false); + } + else { + return null; + } + } + } + function isSimpleArrowFunctionExpression(_currentToken) { + if (_currentToken.kind() === 85 /* EqualsGreaterThanToken */) { + return true; + } + return isIdentifier(_currentToken) && peekToken(1).kind() === 85 /* EqualsGreaterThanToken */; + } + function parseSimpleArrowFunctionExpression() { + var parameter = eatSimpleParameter(); + var equalsGreaterThanToken = eatToken(85 /* EqualsGreaterThanToken */); + var block = tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = tryParseAssignmentExpressionOrHigher(true, true); + } + return new Parser.syntaxFactory.SimpleArrowFunctionExpressionSyntax(parseNodeData, parameter, equalsGreaterThanToken, block, expression); + } + function isBlock() { + return currentToken().kind() === 70 /* OpenBraceToken */; + } + function isDefinitelyArrowFunctionExpression() { + var token0 = currentToken(); + if (token0.kind() !== 72 /* OpenParenToken */) { + return false; + } + var token1 = peekToken(1); + var token1Kind = token1.kind(); + var token2; + if (token1Kind === 73 /* CloseParenToken */) { + token2 = peekToken(2); + var token2Kind = token2.kind(); + return token2Kind === 106 /* ColonToken */ || token2Kind === 85 /* EqualsGreaterThanToken */ || token2Kind === 70 /* OpenBraceToken */; + } + if (token1Kind === 77 /* DotDotDotToken */) { + return true; + } + token2 = peekToken(2); + token2Kind = token2.kind(); + if (token1Kind === 57 /* PublicKeyword */ || token1Kind === 55 /* PrivateKeyword */) { + if (isIdentifier(token2)) { + return true; + } + } + if (!isIdentifier(token1)) { + return false; + } + if (token2Kind === 106 /* ColonToken */) { + return true; + } + var token3 = peekToken(3); + var token3Kind = token3.kind(); + if (token2Kind === 105 /* QuestionToken */) { + if (token3Kind === 106 /* ColonToken */ || token3Kind === 73 /* CloseParenToken */ || token3Kind === 79 /* CommaToken */) { + return true; + } + } + if (token2Kind === 73 /* CloseParenToken */) { + if (token3Kind === 85 /* EqualsGreaterThanToken */) { + return true; + } + } + return false; + } + function isPossiblyArrowFunctionExpression() { + var token0 = currentToken(); + if (token0.kind() !== 72 /* OpenParenToken */) { + return true; + } + var token1 = peekToken(1); + if (!isIdentifier(token1)) { + return false; + } + var token2 = peekToken(2); + var token2Kind = token2.kind(); + if (token2Kind === 107 /* EqualsToken */) { + return true; + } + if (token2Kind === 79 /* CommaToken */) { + return true; + } + if (token2Kind === 73 /* CloseParenToken */) { + var token3 = peekToken(3); + if (token3.kind() === 106 /* ColonToken */) { + return true; + } + } + return false; + } + function parseObjectLiteralExpression(openBraceToken) { + consumeToken(openBraceToken); + var skippedTokens = getArray(); + var propertyAssignments = parseSeparatedSyntaxList(15 /* ObjectLiteralExpression_PropertyAssignments */, skippedTokens); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + return new Parser.syntaxFactory.ObjectLiteralExpressionSyntax(parseNodeData, openBraceToken, propertyAssignments, eatToken(71 /* CloseBraceToken */)); + } + function tryParsePropertyAssignment(inErrorRecovery) { + if (isAccessor(modifierCount(), inErrorRecovery)) { + return parseAccessor(true); + } + else if (isFunctionPropertyAssignment(inErrorRecovery)) { + return parseFunctionPropertyAssignment(); + } + else if (isSimplePropertyAssignment(inErrorRecovery)) { + return parseSimplePropertyAssignment(); + } + else { + return null; + } + } + function isPropertyAssignment(inErrorRecovery) { + return isAccessor(modifierCount(), inErrorRecovery) || isFunctionPropertyAssignment(inErrorRecovery) || isSimplePropertyAssignment(inErrorRecovery); + } + function eatPropertyName() { + var _currentToken = currentToken(); + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(_currentToken) ? eatIdentifierNameToken() : consumeToken(_currentToken); + } + function isFunctionPropertyAssignment(inErrorRecovery) { + return isPropertyName(currentToken(), inErrorRecovery) && isCallSignature(1); + } + function parseFunctionPropertyAssignment() { + return new Parser.syntaxFactory.FunctionPropertyAssignmentSyntax(parseNodeData, eatPropertyName(), parseCallSignature(false), parseBlock(false, true)); + } + function isSimplePropertyAssignment(inErrorRecovery) { + return isPropertyName(currentToken(), inErrorRecovery); + } + function parseSimplePropertyAssignment() { + return new Parser.syntaxFactory.SimplePropertyAssignmentSyntax(parseNodeData, eatPropertyName(), eatToken(106 /* ColonToken */), tryParseAssignmentExpressionOrHigher(true, true)); + } + function isPropertyName(token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return isIdentifier(token); + } + else { + return true; + } + } + var kind = token.kind(); + return kind === 14 /* StringLiteral */ || kind === 13 /* NumericLiteral */; + } + function parseArrayLiteralExpression(openBracketToken) { + consumeToken(openBracketToken); + var skippedTokens = getArray(); + var expressions = parseSeparatedSyntaxList(16 /* ArrayLiteralExpression_AssignmentExpressions */, skippedTokens); + openBracketToken = addSkippedTokensAfterToken(openBracketToken, skippedTokens); + return new Parser.syntaxFactory.ArrayLiteralExpressionSyntax(parseNodeData, openBracketToken, expressions, eatToken(75 /* CloseBracketToken */)); + } + function parseBlock(parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = eatToken(70 /* OpenBraceToken */); + var statements = TypeScript.Syntax.emptyList(); + if (parseBlockEvenWithNoOpenBrace || openBraceToken.fullWidth() > 0) { + var savedIsInStrictMode = isInStrictMode; + var processItems = checkForStrictMode ? updateStrictModeState : null; + var skippedTokens = getArray(); + var statements = parseSyntaxList(5 /* Block_Statements */, skippedTokens, processItems); + openBraceToken = addSkippedTokensAfterToken(openBraceToken, skippedTokens); + setStrictMode(savedIsInStrictMode); + } + return new Parser.syntaxFactory.BlockSyntax(parseNodeData, openBraceToken, statements, eatToken(71 /* CloseBraceToken */)); + } + function parseCallSignature(requireCompleteTypeParameterList) { + return new Parser.syntaxFactory.CallSignatureSyntax(parseNodeData, tryParseTypeParameterList(requireCompleteTypeParameterList), parseParameterList(), parseOptionalTypeAnnotation(false)); + } + function tryParseTypeParameterList(requireCompleteTypeParameterList) { + var _currentToken = currentToken(); + if (_currentToken.kind() !== 80 /* LessThanToken */) { + return null; + } + var rewindPoint = getRewindPoint(); + var lessThanToken = consumeToken(_currentToken); + var skippedTokens = getArray(); + var typeParameters = parseSeparatedSyntaxList(20 /* TypeParameterList_TypeParameters */, skippedTokens); + lessThanToken = addSkippedTokensAfterToken(lessThanToken, skippedTokens); + var greaterThanToken = eatToken(81 /* GreaterThanToken */); + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + rewind(rewindPoint); + releaseRewindPoint(rewindPoint); + return null; + } + else { + releaseRewindPoint(rewindPoint); + return new Parser.syntaxFactory.TypeParameterListSyntax(parseNodeData, lessThanToken, typeParameters, greaterThanToken); + } + } + function isTypeParameter() { + return isIdentifier(currentToken()); + } + function tryParseTypeParameter() { + if (!isIdentifier(currentToken())) { + return null; + } + return new Parser.syntaxFactory.TypeParameterSyntax(parseNodeData, eatIdentifierToken(), tryParseConstraint()); + } + function tryParseConstraint() { + if (currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + return new Parser.syntaxFactory.ConstraintSyntax(parseNodeData, eatToken(48 /* ExtendsKeyword */), parseTypeOrExpression()); + } + function tryParseParameterList() { + if (currentToken().kind() === 72 /* OpenParenToken */) { + var token1 = peekToken(1); + if (token1.kind() === 73 /* CloseParenToken */ || isParameterHelper(token1)) { + return parseParameterList(); + } + } + return null; + } + function parseParameterList() { + var openParenToken = eatToken(72 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList(); + if (openParenToken.fullWidth() > 0) { + var skippedTokens = getArray(); + parameters = parseSeparatedSyntaxList(17 /* ParameterList_Parameters */, skippedTokens); + openParenToken = addSkippedTokensAfterToken(openParenToken, skippedTokens); + } + return new Parser.syntaxFactory.ParameterListSyntax(parseNodeData, openParenToken, parameters, eatToken(73 /* CloseParenToken */)); + } + function parseOptionalTypeAnnotation(allowStringLiteral) { + return currentToken().kind() === 106 /* ColonToken */ ? parseTypeAnnotation(allowStringLiteral) : null; + } + function parseTypeAnnotationType(allowStringLiteral) { + if (allowStringLiteral) { + var _currentToken = currentToken(); + if (_currentToken.kind() === 14 /* StringLiteral */) { + return consumeToken(_currentToken); + } + } + return parseType(); + } + function parseTypeAnnotation(allowStringLiteral) { + return new Parser.syntaxFactory.TypeAnnotationSyntax(parseNodeData, consumeToken(currentToken()), parseTypeAnnotationType(allowStringLiteral)); + } + function isType() { + var _currentToken = currentToken(); + switch (_currentToken.kind()) { + case 39 /* TypeOfKeyword */: + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + case 70 /* OpenBraceToken */: + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + case 31 /* NewKeyword */: + return true; + default: + return isIdentifier(_currentToken); + } + } + function parseTypeOrExpression() { + var result = tryParseType(); + if (result) { + return result; + } + var _currentToken = currentToken(); + if (isExpression(_currentToken)) { + return tryParseUnaryExpressionOrHigher(_currentToken, true); + } + return eatIdentifierToken(TypeScript.DiagnosticCode.Type_expected); + } + function parseType() { + return tryParseType() || eatIdentifierToken(TypeScript.DiagnosticCode.Type_expected); + } + function tryParseType() { + var type = tryParseNonArrayType(); + while (type) { + var _currentToken = currentToken(); + if (previousTokenHasTrailingNewLine(_currentToken) || _currentToken.kind() !== 74 /* OpenBracketToken */) { + break; + } + type = new Parser.syntaxFactory.ArrayTypeSyntax(parseNodeData, type, consumeToken(_currentToken), eatToken(75 /* CloseBracketToken */)); + } + return type; + } + function parseTypeQuery(typeOfKeyword) { + return new Parser.syntaxFactory.TypeQuerySyntax(parseNodeData, consumeToken(typeOfKeyword), parseName(true)); + } + function tryParseNonArrayType() { + var _currentToken = currentToken(); + switch (_currentToken.kind()) { + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + if (peekToken(1).kind() === 76 /* DotToken */) { + break; + } + return consumeToken(_currentToken); + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + return tryParseFunctionType(); + case 41 /* VoidKeyword */: + return consumeToken(_currentToken); + case 70 /* OpenBraceToken */: + return parseObjectType(); + case 31 /* NewKeyword */: + return parseConstructorType(); + case 39 /* TypeOfKeyword */: + return parseTypeQuery(_currentToken); + } + return tryParseNameOrGenericType(); + } + function tryParseNameOrGenericType() { + var name = tryParseName(false); + if (name === null) { + return null; + } + if (previousTokenHasTrailingNewLine(currentToken())) { + return name; + } + var typeArgumentList = tryParseTypeArgumentList(false); + return typeArgumentList === null ? name : new Parser.syntaxFactory.GenericTypeSyntax(parseNodeData, name, typeArgumentList); + } + function tryParseFunctionType() { + var typeParameterList = tryParseTypeParameterList(false); + var parameterList = null; + if (typeParameterList === null) { + parameterList = tryParseParameterList(); + if (parameterList === null) { + return null; + } + } + else { + parameterList = parseParameterList(); + } + return new Parser.syntaxFactory.FunctionTypeSyntax(parseNodeData, typeParameterList, parameterList, eatToken(85 /* EqualsGreaterThanToken */), parseType()); + } + function parseConstructorType() { + return new Parser.syntaxFactory.ConstructorTypeSyntax(parseNodeData, eatToken(31 /* NewKeyword */), tryParseTypeParameterList(false), parseParameterList(), eatToken(85 /* EqualsGreaterThanToken */), parseType()); + } + function isParameter() { + if (currentNode() !== null && currentNode().kind() === 242 /* Parameter */) { + return true; + } + return isParameterHelper(currentToken()); + } + function isParameterHelper(token) { + var tokenKind = token.kind(); + return tokenKind === 77 /* DotDotDotToken */ || isModifierKind(tokenKind) || isIdentifier(token); + } + function eatSimpleParameter() { + return new Parser.syntaxFactory.ParameterSyntax(parseNodeData, null, TypeScript.Syntax.emptyList(), eatIdentifierToken(), null, null, null); + } + function tryParseParameter() { + var node = currentNode(); + if (node !== null && node.kind() === 242 /* Parameter */) { + consumeNode(node); + return node; + } + var dotDotDotToken = tryEatToken(77 /* DotDotDotToken */); + var modifiers = parseModifiers(); + var _currentToken = currentToken(); + if (!isIdentifier(_currentToken) && dotDotDotToken === null && modifiers.length === 0) { + if (isModifierKind(_currentToken.kind())) { + modifiers = TypeScript.Syntax.list([consumeToken(_currentToken)]); + } + else { + return null; + } + } + var identifier = eatIdentifierToken(); + var questionToken = tryEatToken(105 /* QuestionToken */); + var typeAnnotation = parseOptionalTypeAnnotation(true); + var equalsValueClause = null; + if (isEqualsValueClause(true)) { + equalsValueClause = parseEqualsValueClause(true); + } + return new Parser.syntaxFactory.ParameterSyntax(parseNodeData, dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause); + } + function parseSyntaxList(currentListType, skippedTokens, processItems) { + if (processItems === void 0) { processItems = null; } + var savedListParsingState = listParsingState; + listParsingState |= (1 << currentListType); + var result = parseSyntaxListWorker(currentListType, skippedTokens, processItems); + listParsingState = savedListParsingState; + return result; + } + function parseSeparatedSyntaxList(currentListType, skippedTokens) { + var savedListParsingState = listParsingState; + listParsingState |= (1 << currentListType); + var result = parseSeparatedSyntaxListWorker(currentListType, skippedTokens); + listParsingState = savedListParsingState; + return result; + } + function abortParsingListOrMoveToNextToken(currentListType, nodes, separators, skippedTokens) { + reportUnexpectedTokenDiagnostic(currentListType); + for (var state = ListParsingState.LastListParsingState; state >= ListParsingState.FirstListParsingState; state--) { + if ((listParsingState & (1 << state)) !== 0) { + if (isExpectedListTerminator(state) || isExpectedListItem(state, true)) { + return true; + } + } + } + addSkippedTokenToList(nodes, separators, skippedTokens, consumeToken(currentToken())); + return false; + } + function addSkippedTokenToList(nodes, separators, skippedTokens, skippedToken) { + if (Parser.syntaxFactory.isConcrete) { + var length = nodes.length + (separators ? separators.length : 0); + for (var i = length - 1; i >= 0; i--) { + var array = separators && (i % 2 === 1) ? separators : nodes; + var arrayIndex = separators ? TypeScript.IntegerUtilities.integerDivide(i, 2) : i; + var item = array[arrayIndex]; + var _lastToken = TypeScript.lastToken(item); + if (_lastToken && _lastToken.fullWidth() > 0) { + array[arrayIndex] = addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + skippedTokens.push(skippedToken); + } + } + function tryParseExpectedListItem(currentListType, inErrorRecovery, items, processItems) { + var item = tryParseExpectedListItemWorker(currentListType, inErrorRecovery); + if (item === null) { + return false; + } + items.push(item); + if (processItems !== null) { + processItems(items); + } + return true; + } + function listIsTerminated(currentListType) { + return isExpectedListTerminator(currentListType) || currentToken().kind() === 10 /* EndOfFileToken */; + } + function parseSyntaxListWorker(currentListType, skippedTokens, processItems) { + var items = getArray(); + while (true) { + var succeeded = tryParseExpectedListItem(currentListType, false, items, processItems); + if (!succeeded) { + if (listIsTerminated(currentListType)) { + break; + } + var abort = abortParsingListOrMoveToNextToken(currentListType, items, null, skippedTokens); + if (abort) { + break; + } + } + } + var result = TypeScript.Syntax.list(items); + returnZeroLengthArray(items); + return result; + } + function parseSeparatedSyntaxListWorker(currentListType, skippedTokens) { + var nodes = getArray(); + var separators = getArray(); + var _separatorKind = currentListType === 9 /* ObjectType_TypeMembers */ ? 78 /* SemicolonToken */ : 79 /* CommaToken */; + var allowAutomaticSemicolonInsertion = _separatorKind === 78 /* SemicolonToken */; + var inErrorRecovery = false; + while (true) { + var succeeded = tryParseExpectedListItem(currentListType, inErrorRecovery, nodes, null); + if (!succeeded) { + if (listIsTerminated(currentListType)) { + break; + } + var abort = abortParsingListOrMoveToNextToken(currentListType, nodes, separators, skippedTokens); + if (abort) { + break; + } + else { + inErrorRecovery = true; + continue; + } + } + inErrorRecovery = false; + var _currentToken = currentToken(); + var tokenKind = _currentToken.kind(); + if (tokenKind === _separatorKind || tokenKind === 79 /* CommaToken */) { + separators.push(consumeToken(_currentToken)); + continue; + } + if (listIsTerminated(currentListType)) { + break; + } + if (allowAutomaticSemicolonInsertion && canEatAutomaticSemicolon(false)) { + var semicolonToken = eatExplicitOrAutomaticSemicolon(false) || TypeScript.Syntax.emptyToken(78 /* SemicolonToken */); + separators.push(semicolonToken); + continue; + } + separators.push(eatToken(_separatorKind)); + inErrorRecovery = true; + } + var result = TypeScript.Syntax.separatedList(nodes, separators); + returnZeroLengthArray(nodes); + returnZeroLengthArray(separators); + return result; + } + function reportUnexpectedTokenDiagnostic(listType) { + var token = currentToken(); + var diagnostic = new TypeScript.Diagnostic(fileName, source.text.lineMap(), TypeScript.start(token, source.text), TypeScript.width(token), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [getExpectedListElementType(listType)]); + addDiagnostic(diagnostic); + } + function addDiagnostic(diagnostic) { + if (diagnostics.length > 0 && diagnostics[diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + diagnostics.push(diagnostic); + } + function isExpectedListTerminator(currentListType) { + switch (currentListType) { + case 0 /* SourceUnit_ModuleElements */: + return isExpectedSourceUnit_ModuleElementsTerminator(); + case 1 /* ClassDeclaration_ClassElements */: + return isExpectedClassDeclaration_ClassElementsTerminator(); + case 2 /* ModuleDeclaration_ModuleElements */: + return isExpectedModuleDeclaration_ModuleElementsTerminator(); + case 3 /* SwitchStatement_SwitchClauses */: + return isExpectedSwitchStatement_SwitchClausesTerminator(); + case 4 /* SwitchClause_Statements */: + return isExpectedSwitchClause_StatementsTerminator(); + case 5 /* Block_Statements */: + return isExpectedBlock_StatementsTerminator(); + case 6 /* TryBlock_Statements */: + return isExpectedTryBlock_StatementsTerminator(); + case 7 /* CatchBlock_Statements */: + return isExpectedCatchBlock_StatementsTerminator(); + case 8 /* EnumDeclaration_EnumElements */: + return isExpectedEnumDeclaration_EnumElementsTerminator(); + case 9 /* ObjectType_TypeMembers */: + return isExpectedObjectType_TypeMembersTerminator(); + case 10 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + case 11 /* HeritageClause_TypeNameList */: + return isExpectedHeritageClause_TypeNameListTerminator(); + case 12 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + case 13 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + case 14 /* ArgumentList_AssignmentExpressions */: + return isExpectedArgumentList_AssignmentExpressionsTerminator(); + case 15 /* ObjectLiteralExpression_PropertyAssignments */: + return isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + case 16 /* ArrayLiteralExpression_AssignmentExpressions */: + return isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + case 17 /* ParameterList_Parameters */: + return isExpectedParameterList_ParametersTerminator(); + case 18 /* IndexSignature_Parameters */: + return isExpectedIndexSignature_ParametersTerminator(); + case 19 /* TypeArgumentList_Types */: + return isExpectedTypeArgumentList_TypesTerminator(); + case 20 /* TypeParameterList_TypeParameters */: + return isExpectedTypeParameterList_TypeParametersTerminator(); + default: + throw TypeScript.Errors.invalidOperation(); + } + } + function isExpectedSourceUnit_ModuleElementsTerminator() { + return currentToken().kind() === 10 /* EndOfFileToken */; + } + function isExpectedEnumDeclaration_EnumElementsTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedModuleDeclaration_ModuleElementsTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedObjectType_TypeMembersTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedLiteralExpression_AssignmentExpressionsTerminator() { + return currentToken().kind() === 75 /* CloseBracketToken */; + } + function isExpectedTypeArgumentList_TypesTerminator() { + var token = currentToken(); + var tokenKind = token.kind(); + if (tokenKind === 81 /* GreaterThanToken */) { + return true; + } + if (canFollowTypeArgumentListInExpression(tokenKind)) { + return true; + } + return false; + } + function isExpectedTypeParameterList_TypeParametersTerminator() { + var tokenKind = currentToken().kind(); + if (tokenKind === 81 /* GreaterThanToken */) { + return true; + } + if (tokenKind === 72 /* OpenParenToken */ || tokenKind === 70 /* OpenBraceToken */ || tokenKind === 48 /* ExtendsKeyword */ || tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + return false; + } + function isExpectedParameterList_ParametersTerminator() { + var tokenKind = currentToken().kind(); + if (tokenKind === 73 /* CloseParenToken */) { + return true; + } + if (tokenKind === 70 /* OpenBraceToken */) { + return true; + } + if (tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + return false; + } + function isExpectedIndexSignature_ParametersTerminator() { + var tokenKind = currentToken().kind(); + if (tokenKind === 75 /* CloseBracketToken */) { + return true; + } + if (tokenKind === 70 /* OpenBraceToken */) { + return true; + } + return false; + } + function isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator() { + var tokenKind = currentToken().kind(); + if (tokenKind === 78 /* SemicolonToken */ || tokenKind === 73 /* CloseParenToken */) { + return true; + } + if (tokenKind === 29 /* InKeyword */) { + return true; + } + return false; + } + function isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator() { + if (currentToken().kind() === 85 /* EqualsGreaterThanToken */) { + return true; + } + return canEatExplicitOrAutomaticSemicolon(false); + } + function isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator() { + var tokenKind = currentToken().kind(); + if (tokenKind === 70 /* OpenBraceToken */ || tokenKind === 71 /* CloseBraceToken */) { + return true; + } + return false; + } + function isExpectedHeritageClause_TypeNameListTerminator() { + var tokenKind = currentToken().kind(); + if (tokenKind === 48 /* ExtendsKeyword */ || tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + if (isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + return false; + } + function isExpectedArgumentList_AssignmentExpressionsTerminator() { + var token0 = currentToken(); + var tokenKind = token0.kind(); + return tokenKind === 73 /* CloseParenToken */ || tokenKind === 78 /* SemicolonToken */; + } + function isExpectedClassDeclaration_ClassElementsTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedSwitchStatement_SwitchClausesTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedSwitchClause_StatementsTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */ || isSwitchClause(); + } + function isExpectedBlock_StatementsTerminator() { + return currentToken().kind() === 71 /* CloseBraceToken */; + } + function isExpectedTryBlock_StatementsTerminator() { + var tokenKind = currentToken().kind(); + return tokenKind === 17 /* CatchKeyword */ || tokenKind === 25 /* FinallyKeyword */; + } + function isExpectedCatchBlock_StatementsTerminator() { + return currentToken().kind() === 25 /* FinallyKeyword */; + } + function isExpectedListItem(currentListType, inErrorRecovery) { + switch (currentListType) { + case 0 /* SourceUnit_ModuleElements */: + return isModuleElement(inErrorRecovery); + case 1 /* ClassDeclaration_ClassElements */: + return isClassElement(inErrorRecovery); + case 2 /* ModuleDeclaration_ModuleElements */: + return isModuleElement(inErrorRecovery); + case 3 /* SwitchStatement_SwitchClauses */: + return isSwitchClause(); + case 4 /* SwitchClause_Statements */: + return isStatement(modifierCount(), inErrorRecovery); + case 5 /* Block_Statements */: + return isStatement(modifierCount(), inErrorRecovery); + case 6 /* TryBlock_Statements */: + return false; + case 7 /* CatchBlock_Statements */: + return false; + case 8 /* EnumDeclaration_EnumElements */: + return isEnumElement(inErrorRecovery); + case 9 /* ObjectType_TypeMembers */: + return isTypeMember(inErrorRecovery); + case 10 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return isHeritageClause(); + case 11 /* HeritageClause_TypeNameList */: + return isHeritageClauseTypeName(); + case 12 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return isVariableDeclarator(); + case 13 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return isVariableDeclarator(); + case 14 /* ArgumentList_AssignmentExpressions */: + return isExpectedArgumentList_AssignmentExpression(); + case 15 /* ObjectLiteralExpression_PropertyAssignments */: + return isPropertyAssignment(inErrorRecovery); + case 16 /* ArrayLiteralExpression_AssignmentExpressions */: + return isAssignmentOrOmittedExpression(); + case 17 /* ParameterList_Parameters */: + return isParameter(); + case 18 /* IndexSignature_Parameters */: + return isParameter(); + case 19 /* TypeArgumentList_Types */: + return isType(); + case 20 /* TypeParameterList_TypeParameters */: + return isTypeParameter(); + default: + throw TypeScript.Errors.invalidOperation(); + } + } + function isExpectedArgumentList_AssignmentExpression() { + var _currentToken = currentToken(); + if (isExpression(_currentToken)) { + return true; + } + if (_currentToken.kind() === 79 /* CommaToken */) { + return true; + } + return false; + } + function tryParseExpectedListItemWorker(currentListType, inErrorRecovery) { + switch (currentListType) { + case 0 /* SourceUnit_ModuleElements */: + return tryParseModuleElement(inErrorRecovery); + case 1 /* ClassDeclaration_ClassElements */: + return tryParseClassElement(inErrorRecovery); + case 2 /* ModuleDeclaration_ModuleElements */: + return tryParseModuleElement(inErrorRecovery); + case 3 /* SwitchStatement_SwitchClauses */: + return tryParseSwitchClause(); + case 4 /* SwitchClause_Statements */: + return tryParseStatement(inErrorRecovery); + case 5 /* Block_Statements */: + return tryParseStatement(inErrorRecovery); + case 6 /* TryBlock_Statements */: + return tryParseStatement(inErrorRecovery); + case 7 /* CatchBlock_Statements */: + return tryParseStatement(inErrorRecovery); + case 8 /* EnumDeclaration_EnumElements */: + return tryParseEnumElement(inErrorRecovery); + case 9 /* ObjectType_TypeMembers */: + return tryParseTypeMember(inErrorRecovery); + case 10 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return tryParseHeritageClause(); + case 11 /* HeritageClause_TypeNameList */: + return tryParseHeritageClauseTypeName(); + case 12 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return tryParseVariableDeclarator(true, false); + case 13 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return tryParseVariableDeclarator(false, false); + case 14 /* ArgumentList_AssignmentExpressions */: + return tryParseArgumentListExpression(); + case 15 /* ObjectLiteralExpression_PropertyAssignments */: + return tryParsePropertyAssignment(inErrorRecovery); + case 16 /* ArrayLiteralExpression_AssignmentExpressions */: + return tryParseAssignmentOrOmittedExpression(); + case 17 /* ParameterList_Parameters */: + return tryParseParameter(); + case 18 /* IndexSignature_Parameters */: + return tryParseParameter(); + case 19 /* TypeArgumentList_Types */: + return tryParseType(); + case 20 /* TypeParameterList_TypeParameters */: + return tryParseTypeParameter(); + default: + throw TypeScript.Errors.invalidOperation(); + } + } + function getExpectedListElementType(currentListType) { + switch (currentListType) { + case 0 /* SourceUnit_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + case 10 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + case 1 /* ClassDeclaration_ClassElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.constructor_function_accessor_or_variable, null); + case 2 /* ModuleDeclaration_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + case 3 /* SwitchStatement_SwitchClauses */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.case_or_default_clause, null); + case 4 /* SwitchClause_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + case 5 /* Block_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + case 12 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + case 13 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + case 8 /* EnumDeclaration_EnumElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + case 9 /* ObjectType_TypeMembers */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.call_construct_index_property_or_function_signature, null); + case 14 /* ArgumentList_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + case 11 /* HeritageClause_TypeNameList */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null); + case 15 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.property_or_accessor, null); + case 17 /* ParameterList_Parameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.parameter, null); + case 18 /* IndexSignature_Parameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.parameter, null); + case 19 /* TypeArgumentList_Types */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type, null); + case 20 /* TypeParameterList_TypeParameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_parameter, null); + case 16 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + default: + throw TypeScript.Errors.invalidOperation(); + } + } + return parseSyntaxTree; + } + var BinaryExpressionPrecedence; + (function (BinaryExpressionPrecedence) { + BinaryExpressionPrecedence[BinaryExpressionPrecedence["Lowest"] = 1] = "Lowest"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["LogicalOrExpressionPrecedence"] = 2] = "LogicalOrExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["LogicalAndExpressionPrecedence"] = 3] = "LogicalAndExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 4] = "BitwiseOrExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 5] = "BitwiseExclusiveOrExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 6] = "BitwiseAndExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["EqualityExpressionPrecedence"] = 7] = "EqualityExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["RelationalExpressionPrecedence"] = 8] = "RelationalExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["ShiftExpressionPrecdence"] = 9] = "ShiftExpressionPrecdence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["AdditiveExpressionPrecedence"] = 10] = "AdditiveExpressionPrecedence"; + BinaryExpressionPrecedence[BinaryExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 11] = "MultiplicativeExpressionPrecedence"; + })(BinaryExpressionPrecedence || (BinaryExpressionPrecedence = {})); + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["IndexSignature_Parameters"] = 18] = "IndexSignature_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 19] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 20] = "TypeParameterList_TypeParameters"; + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + var parseSyntaxTree = createParseSyntaxTree(); + function parse(fileName, text, languageVersion, isDeclaration) { + return parseSource(TypeScript.Scanner.createParserSource(fileName, text, languageVersion), isDeclaration); + } + Parser.parse = parse; + function parseSource(source, isDeclaration) { + return parseSyntaxTree(source, isDeclaration); + } + Parser.parseSource = parseSource; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + (function (Concrete) { + TypeScript.Parser.syntaxFactory = Concrete; + Concrete.isConcrete = true; + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(data, moduleElements, endOfFileToken) { + _super.call(this, data); + this.syntaxTree = null; + this.parent = null, this.moduleElements = moduleElements, this.endOfFileToken = endOfFileToken, !TypeScript.isShared(moduleElements) && (moduleElements.parent = this), endOfFileToken.parent = this; + } + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + Concrete.SourceUnitSyntax = SourceUnitSyntax; + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(data, left, dotToken, right) { + _super.call(this, data); + this.left = left, this.dotToken = dotToken, this.right = right, left.parent = this, dotToken.parent = this, right.parent = this; + } + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + Concrete.QualifiedNameSyntax = QualifiedNameSyntax; + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(data, openBraceToken, typeMembers, closeBraceToken) { + _super.call(this, data); + this.openBraceToken = openBraceToken, this.typeMembers = typeMembers, this.closeBraceToken = closeBraceToken, openBraceToken.parent = this, !TypeScript.isShared(typeMembers) && (typeMembers.parent = this), closeBraceToken.parent = this; + } + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + Concrete.ObjectTypeSyntax = ObjectTypeSyntax; + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(data, typeParameterList, parameterList, equalsGreaterThanToken, type) { + _super.call(this, data); + this.typeParameterList = typeParameterList, this.parameterList = parameterList, this.equalsGreaterThanToken = equalsGreaterThanToken, this.type = type, typeParameterList && (typeParameterList.parent = this), parameterList.parent = this, equalsGreaterThanToken.parent = this, type.parent = this; + } + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + Concrete.FunctionTypeSyntax = FunctionTypeSyntax; + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(data, type, openBracketToken, closeBracketToken) { + _super.call(this, data); + this.type = type, this.openBracketToken = openBracketToken, this.closeBracketToken = closeBracketToken, type.parent = this, openBracketToken.parent = this, closeBracketToken.parent = this; + } + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + Concrete.ArrayTypeSyntax = ArrayTypeSyntax; + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(data, newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + _super.call(this, data); + this.newKeyword = newKeyword, this.typeParameterList = typeParameterList, this.parameterList = parameterList, this.equalsGreaterThanToken = equalsGreaterThanToken, this.type = type, newKeyword.parent = this, typeParameterList && (typeParameterList.parent = this), parameterList.parent = this, equalsGreaterThanToken.parent = this, type.parent = this; + } + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + Concrete.ConstructorTypeSyntax = ConstructorTypeSyntax; + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(data, name, typeArgumentList) { + _super.call(this, data); + this.name = name, this.typeArgumentList = typeArgumentList, name.parent = this, typeArgumentList.parent = this; + } + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + Concrete.GenericTypeSyntax = GenericTypeSyntax; + var TypeQuerySyntax = (function (_super) { + __extends(TypeQuerySyntax, _super); + function TypeQuerySyntax(data, typeOfKeyword, name) { + _super.call(this, data); + this.typeOfKeyword = typeOfKeyword, this.name = name, typeOfKeyword.parent = this, name.parent = this; + } + return TypeQuerySyntax; + })(TypeScript.SyntaxNode); + Concrete.TypeQuerySyntax = TypeQuerySyntax; + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(data, modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + _super.call(this, data); + this.modifiers = modifiers, this.interfaceKeyword = interfaceKeyword, this.identifier = identifier, this.typeParameterList = typeParameterList, this.heritageClauses = heritageClauses, this.body = body, !TypeScript.isShared(modifiers) && (modifiers.parent = this), interfaceKeyword.parent = this, identifier.parent = this, typeParameterList && (typeParameterList.parent = this), !TypeScript.isShared(heritageClauses) && (heritageClauses.parent = this), body.parent = this; + } + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(data, modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.functionKeyword = functionKeyword, this.identifier = identifier, this.callSignature = callSignature, this.block = block, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), functionKeyword.parent = this, identifier.parent = this, callSignature.parent = this, block && (block.parent = this), semicolonToken && (semicolonToken.parent = this); + } + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(data, modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + _super.call(this, data); + this.modifiers = modifiers, this.moduleKeyword = moduleKeyword, this.name = name, this.stringLiteral = stringLiteral, this.openBraceToken = openBraceToken, this.moduleElements = moduleElements, this.closeBraceToken = closeBraceToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), moduleKeyword.parent = this, name && (name.parent = this), stringLiteral && (stringLiteral.parent = this), openBraceToken.parent = this, !TypeScript.isShared(moduleElements) && (moduleElements.parent = this), closeBraceToken.parent = this; + } + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(data, modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + _super.call(this, data); + this.modifiers = modifiers, this.classKeyword = classKeyword, this.identifier = identifier, this.typeParameterList = typeParameterList, this.heritageClauses = heritageClauses, this.openBraceToken = openBraceToken, this.classElements = classElements, this.closeBraceToken = closeBraceToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), classKeyword.parent = this, identifier.parent = this, typeParameterList && (typeParameterList.parent = this), !TypeScript.isShared(heritageClauses) && (heritageClauses.parent = this), openBraceToken.parent = this, !TypeScript.isShared(classElements) && (classElements.parent = this), closeBraceToken.parent = this; + } + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.ClassDeclarationSyntax = ClassDeclarationSyntax; + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(data, modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + _super.call(this, data); + this.modifiers = modifiers, this.enumKeyword = enumKeyword, this.identifier = identifier, this.openBraceToken = openBraceToken, this.enumElements = enumElements, this.closeBraceToken = closeBraceToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), enumKeyword.parent = this, identifier.parent = this, openBraceToken.parent = this, !TypeScript.isShared(enumElements) && (enumElements.parent = this), closeBraceToken.parent = this; + } + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.EnumDeclarationSyntax = EnumDeclarationSyntax; + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(data, modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.importKeyword = importKeyword, this.identifier = identifier, this.equalsToken = equalsToken, this.moduleReference = moduleReference, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), importKeyword.parent = this, identifier.parent = this, equalsToken.parent = this, moduleReference.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.ImportDeclarationSyntax = ImportDeclarationSyntax; + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(data, exportKeyword, equalsToken, identifier, semicolonToken) { + _super.call(this, data); + this.exportKeyword = exportKeyword, this.equalsToken = equalsToken, this.identifier = identifier, this.semicolonToken = semicolonToken, exportKeyword.parent = this, equalsToken.parent = this, identifier.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + Concrete.ExportAssignmentSyntax = ExportAssignmentSyntax; + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(data, modifiers, propertyName, callSignature, block, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.propertyName = propertyName, this.callSignature = callSignature, this.block = block, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), propertyName.parent = this, callSignature.parent = this, block && (block.parent = this), semicolonToken && (semicolonToken.parent = this); + } + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(data, modifiers, variableDeclarator, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.variableDeclarator = variableDeclarator, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), variableDeclarator.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(data, modifiers, constructorKeyword, callSignature, block, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.constructorKeyword = constructorKeyword, this.callSignature = callSignature, this.block = block, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), constructorKeyword.parent = this, callSignature.parent = this, block && (block.parent = this), semicolonToken && (semicolonToken.parent = this); + } + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + var IndexMemberDeclarationSyntax = (function (_super) { + __extends(IndexMemberDeclarationSyntax, _super); + function IndexMemberDeclarationSyntax(data, modifiers, indexSignature, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.indexSignature = indexSignature, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), indexSignature.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return IndexMemberDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.IndexMemberDeclarationSyntax = IndexMemberDeclarationSyntax; + var GetAccessorSyntax = (function (_super) { + __extends(GetAccessorSyntax, _super); + function GetAccessorSyntax(data, modifiers, getKeyword, propertyName, callSignature, block) { + _super.call(this, data); + this.modifiers = modifiers, this.getKeyword = getKeyword, this.propertyName = propertyName, this.callSignature = callSignature, this.block = block, !TypeScript.isShared(modifiers) && (modifiers.parent = this), getKeyword.parent = this, propertyName.parent = this, callSignature.parent = this, block.parent = this; + } + return GetAccessorSyntax; + })(TypeScript.SyntaxNode); + Concrete.GetAccessorSyntax = GetAccessorSyntax; + var SetAccessorSyntax = (function (_super) { + __extends(SetAccessorSyntax, _super); + function SetAccessorSyntax(data, modifiers, setKeyword, propertyName, callSignature, block) { + _super.call(this, data); + this.modifiers = modifiers, this.setKeyword = setKeyword, this.propertyName = propertyName, this.callSignature = callSignature, this.block = block, !TypeScript.isShared(modifiers) && (modifiers.parent = this), setKeyword.parent = this, propertyName.parent = this, callSignature.parent = this, block.parent = this; + } + return SetAccessorSyntax; + })(TypeScript.SyntaxNode); + Concrete.SetAccessorSyntax = SetAccessorSyntax; + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(data, propertyName, questionToken, typeAnnotation) { + _super.call(this, data); + this.propertyName = propertyName, this.questionToken = questionToken, this.typeAnnotation = typeAnnotation, propertyName.parent = this, questionToken && (questionToken.parent = this), typeAnnotation && (typeAnnotation.parent = this); + } + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + Concrete.PropertySignatureSyntax = PropertySignatureSyntax; + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(data, typeParameterList, parameterList, typeAnnotation) { + _super.call(this, data); + this.typeParameterList = typeParameterList, this.parameterList = parameterList, this.typeAnnotation = typeAnnotation, typeParameterList && (typeParameterList.parent = this), parameterList.parent = this, typeAnnotation && (typeAnnotation.parent = this); + } + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + Concrete.CallSignatureSyntax = CallSignatureSyntax; + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(data, newKeyword, callSignature) { + _super.call(this, data); + this.newKeyword = newKeyword, this.callSignature = callSignature, newKeyword.parent = this, callSignature.parent = this; + } + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + Concrete.ConstructSignatureSyntax = ConstructSignatureSyntax; + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(data, openBracketToken, parameters, closeBracketToken, typeAnnotation) { + _super.call(this, data); + this.openBracketToken = openBracketToken, this.parameters = parameters, this.closeBracketToken = closeBracketToken, this.typeAnnotation = typeAnnotation, openBracketToken.parent = this, !TypeScript.isShared(parameters) && (parameters.parent = this), closeBracketToken.parent = this, typeAnnotation && (typeAnnotation.parent = this); + } + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + Concrete.IndexSignatureSyntax = IndexSignatureSyntax; + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(data, propertyName, questionToken, callSignature) { + _super.call(this, data); + this.propertyName = propertyName, this.questionToken = questionToken, this.callSignature = callSignature, propertyName.parent = this, questionToken && (questionToken.parent = this), callSignature.parent = this; + } + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + Concrete.MethodSignatureSyntax = MethodSignatureSyntax; + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(data, openBraceToken, statements, closeBraceToken) { + _super.call(this, data); + this.openBraceToken = openBraceToken, this.statements = statements, this.closeBraceToken = closeBraceToken, openBraceToken.parent = this, !TypeScript.isShared(statements) && (statements.parent = this), closeBraceToken.parent = this; + } + return BlockSyntax; + })(TypeScript.SyntaxNode); + Concrete.BlockSyntax = BlockSyntax; + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(data, ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + _super.call(this, data); + this.ifKeyword = ifKeyword, this.openParenToken = openParenToken, this.condition = condition, this.closeParenToken = closeParenToken, this.statement = statement, this.elseClause = elseClause, ifKeyword.parent = this, openParenToken.parent = this, condition.parent = this, closeParenToken.parent = this, statement.parent = this, elseClause && (elseClause.parent = this); + } + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.IfStatementSyntax = IfStatementSyntax; + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(data, modifiers, variableDeclaration, semicolonToken) { + _super.call(this, data); + this.modifiers = modifiers, this.variableDeclaration = variableDeclaration, this.semicolonToken = semicolonToken, !TypeScript.isShared(modifiers) && (modifiers.parent = this), variableDeclaration.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.VariableStatementSyntax = VariableStatementSyntax; + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(data, expression, semicolonToken) { + _super.call(this, data); + this.expression = expression, this.semicolonToken = semicolonToken, expression.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.ExpressionStatementSyntax = ExpressionStatementSyntax; + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(data, returnKeyword, expression, semicolonToken) { + _super.call(this, data); + this.returnKeyword = returnKeyword, this.expression = expression, this.semicolonToken = semicolonToken, returnKeyword.parent = this, expression && (expression.parent = this), semicolonToken && (semicolonToken.parent = this); + } + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.ReturnStatementSyntax = ReturnStatementSyntax; + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(data, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + _super.call(this, data); + this.switchKeyword = switchKeyword, this.openParenToken = openParenToken, this.expression = expression, this.closeParenToken = closeParenToken, this.openBraceToken = openBraceToken, this.switchClauses = switchClauses, this.closeBraceToken = closeBraceToken, switchKeyword.parent = this, openParenToken.parent = this, expression.parent = this, closeParenToken.parent = this, openBraceToken.parent = this, !TypeScript.isShared(switchClauses) && (switchClauses.parent = this), closeBraceToken.parent = this; + } + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.SwitchStatementSyntax = SwitchStatementSyntax; + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(data, breakKeyword, identifier, semicolonToken) { + _super.call(this, data); + this.breakKeyword = breakKeyword, this.identifier = identifier, this.semicolonToken = semicolonToken, breakKeyword.parent = this, identifier && (identifier.parent = this), semicolonToken && (semicolonToken.parent = this); + } + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.BreakStatementSyntax = BreakStatementSyntax; + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(data, continueKeyword, identifier, semicolonToken) { + _super.call(this, data); + this.continueKeyword = continueKeyword, this.identifier = identifier, this.semicolonToken = semicolonToken, continueKeyword.parent = this, identifier && (identifier.parent = this), semicolonToken && (semicolonToken.parent = this); + } + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.ContinueStatementSyntax = ContinueStatementSyntax; + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(data, forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + _super.call(this, data); + this.forKeyword = forKeyword, this.openParenToken = openParenToken, this.variableDeclaration = variableDeclaration, this.initializer = initializer, this.firstSemicolonToken = firstSemicolonToken, this.condition = condition, this.secondSemicolonToken = secondSemicolonToken, this.incrementor = incrementor, this.closeParenToken = closeParenToken, this.statement = statement, forKeyword.parent = this, openParenToken.parent = this, variableDeclaration && (variableDeclaration.parent = this), initializer && (initializer.parent = this), firstSemicolonToken.parent = this, condition && (condition.parent = this), secondSemicolonToken.parent = this, incrementor && (incrementor.parent = this), closeParenToken.parent = this, statement.parent = this; + } + return ForStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.ForStatementSyntax = ForStatementSyntax; + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(data, forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + _super.call(this, data); + this.forKeyword = forKeyword, this.openParenToken = openParenToken, this.variableDeclaration = variableDeclaration, this.left = left, this.inKeyword = inKeyword, this.expression = expression, this.closeParenToken = closeParenToken, this.statement = statement, forKeyword.parent = this, openParenToken.parent = this, variableDeclaration && (variableDeclaration.parent = this), left && (left.parent = this), inKeyword.parent = this, expression.parent = this, closeParenToken.parent = this, statement.parent = this; + } + return ForInStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.ForInStatementSyntax = ForInStatementSyntax; + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(data, semicolonToken) { + _super.call(this, data); + this.semicolonToken = semicolonToken, semicolonToken.parent = this; + } + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.EmptyStatementSyntax = EmptyStatementSyntax; + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(data, throwKeyword, expression, semicolonToken) { + _super.call(this, data); + this.throwKeyword = throwKeyword, this.expression = expression, this.semicolonToken = semicolonToken, throwKeyword.parent = this, expression.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.ThrowStatementSyntax = ThrowStatementSyntax; + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(data, whileKeyword, openParenToken, condition, closeParenToken, statement) { + _super.call(this, data); + this.whileKeyword = whileKeyword, this.openParenToken = openParenToken, this.condition = condition, this.closeParenToken = closeParenToken, this.statement = statement, whileKeyword.parent = this, openParenToken.parent = this, condition.parent = this, closeParenToken.parent = this, statement.parent = this; + } + return WhileStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.WhileStatementSyntax = WhileStatementSyntax; + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(data, tryKeyword, block, catchClause, finallyClause) { + _super.call(this, data); + this.tryKeyword = tryKeyword, this.block = block, this.catchClause = catchClause, this.finallyClause = finallyClause, tryKeyword.parent = this, block.parent = this, catchClause && (catchClause.parent = this), finallyClause && (finallyClause.parent = this); + } + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.TryStatementSyntax = TryStatementSyntax; + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(data, identifier, colonToken, statement) { + _super.call(this, data); + this.identifier = identifier, this.colonToken = colonToken, this.statement = statement, identifier.parent = this, colonToken.parent = this, statement.parent = this; + } + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.LabeledStatementSyntax = LabeledStatementSyntax; + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(data, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + _super.call(this, data); + this.doKeyword = doKeyword, this.statement = statement, this.whileKeyword = whileKeyword, this.openParenToken = openParenToken, this.condition = condition, this.closeParenToken = closeParenToken, this.semicolonToken = semicolonToken, doKeyword.parent = this, statement.parent = this, whileKeyword.parent = this, openParenToken.parent = this, condition.parent = this, closeParenToken.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return DoStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.DoStatementSyntax = DoStatementSyntax; + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(data, debuggerKeyword, semicolonToken) { + _super.call(this, data); + this.debuggerKeyword = debuggerKeyword, this.semicolonToken = semicolonToken, debuggerKeyword.parent = this, semicolonToken && (semicolonToken.parent = this); + } + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.DebuggerStatementSyntax = DebuggerStatementSyntax; + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(data, withKeyword, openParenToken, condition, closeParenToken, statement) { + _super.call(this, data); + this.withKeyword = withKeyword, this.openParenToken = openParenToken, this.condition = condition, this.closeParenToken = closeParenToken, this.statement = statement, withKeyword.parent = this, openParenToken.parent = this, condition.parent = this, closeParenToken.parent = this, statement.parent = this; + } + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + Concrete.WithStatementSyntax = WithStatementSyntax; + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(data, operatorToken, operand) { + _super.call(this, data); + this.operatorToken = operatorToken, this.operand = operand, operatorToken.parent = this, operand.parent = this; + } + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(this.operatorToken.kind()); + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(data, deleteKeyword, expression) { + _super.call(this, data); + this.deleteKeyword = deleteKeyword, this.expression = expression, deleteKeyword.parent = this, expression.parent = this; + } + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.DeleteExpressionSyntax = DeleteExpressionSyntax; + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(data, typeOfKeyword, expression) { + _super.call(this, data); + this.typeOfKeyword = typeOfKeyword, this.expression = expression, typeOfKeyword.parent = this, expression.parent = this; + } + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(data, voidKeyword, expression) { + _super.call(this, data); + this.voidKeyword = voidKeyword, this.expression = expression, voidKeyword.parent = this, expression.parent = this; + } + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.VoidExpressionSyntax = VoidExpressionSyntax; + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(data, condition, questionToken, whenTrue, colonToken, whenFalse) { + _super.call(this, data); + this.condition = condition, this.questionToken = questionToken, this.whenTrue = whenTrue, this.colonToken = colonToken, this.whenFalse = whenFalse, condition.parent = this, questionToken.parent = this, whenTrue.parent = this, colonToken.parent = this, whenFalse.parent = this; + } + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(data, left, operatorToken, right) { + _super.call(this, data); + this.left = left, this.operatorToken = operatorToken, this.right = right, left.parent = this, operatorToken.parent = this, right.parent = this; + } + BinaryExpressionSyntax.prototype.kind = function () { + return TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(this.operatorToken.kind()); + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.BinaryExpressionSyntax = BinaryExpressionSyntax; + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(data, operand, operatorToken) { + _super.call(this, data); + this.operand = operand, this.operatorToken = operatorToken, operand.parent = this, operatorToken.parent = this; + } + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(this.operatorToken.kind()); + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(data, expression, dotToken, name) { + _super.call(this, data); + this.expression = expression, this.dotToken = dotToken, this.name = name, expression.parent = this, dotToken.parent = this, name.parent = this; + } + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(data, expression, argumentList) { + _super.call(this, data); + this.expression = expression, this.argumentList = argumentList, expression.parent = this, argumentList.parent = this; + } + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.InvocationExpressionSyntax = InvocationExpressionSyntax; + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(data, openBracketToken, expressions, closeBracketToken) { + _super.call(this, data); + this.openBracketToken = openBracketToken, this.expressions = expressions, this.closeBracketToken = closeBracketToken, openBracketToken.parent = this, !TypeScript.isShared(expressions) && (expressions.parent = this), closeBracketToken.parent = this; + } + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(data, openBraceToken, propertyAssignments, closeBraceToken) { + _super.call(this, data); + this.openBraceToken = openBraceToken, this.propertyAssignments = propertyAssignments, this.closeBraceToken = closeBraceToken, openBraceToken.parent = this, !TypeScript.isShared(propertyAssignments) && (propertyAssignments.parent = this), closeBraceToken.parent = this; + } + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(data, newKeyword, expression, argumentList) { + _super.call(this, data); + this.newKeyword = newKeyword, this.expression = expression, this.argumentList = argumentList, newKeyword.parent = this, expression.parent = this, argumentList && (argumentList.parent = this); + } + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(data, openParenToken, expression, closeParenToken) { + _super.call(this, data); + this.openParenToken = openParenToken, this.expression = expression, this.closeParenToken = closeParenToken, openParenToken.parent = this, expression.parent = this, closeParenToken.parent = this; + } + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(data, callSignature, equalsGreaterThanToken, block, expression) { + _super.call(this, data); + this.callSignature = callSignature, this.equalsGreaterThanToken = equalsGreaterThanToken, this.block = block, this.expression = expression, callSignature.parent = this, equalsGreaterThanToken.parent = this, block && (block.parent = this), expression && (expression.parent = this); + } + return ParenthesizedArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(data, parameter, equalsGreaterThanToken, block, expression) { + _super.call(this, data); + this.parameter = parameter, this.equalsGreaterThanToken = equalsGreaterThanToken, this.block = block, this.expression = expression, parameter.parent = this, equalsGreaterThanToken.parent = this, block && (block.parent = this), expression && (expression.parent = this); + } + return SimpleArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(data, lessThanToken, type, greaterThanToken, expression) { + _super.call(this, data); + this.lessThanToken = lessThanToken, this.type = type, this.greaterThanToken = greaterThanToken, this.expression = expression, lessThanToken.parent = this, type.parent = this, greaterThanToken.parent = this, expression.parent = this; + } + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.CastExpressionSyntax = CastExpressionSyntax; + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(data, expression, openBracketToken, argumentExpression, closeBracketToken) { + _super.call(this, data); + this.expression = expression, this.openBracketToken = openBracketToken, this.argumentExpression = argumentExpression, this.closeBracketToken = closeBracketToken, expression.parent = this, openBracketToken.parent = this, argumentExpression.parent = this, closeBracketToken.parent = this; + } + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(data, functionKeyword, identifier, callSignature, block) { + _super.call(this, data); + this.functionKeyword = functionKeyword, this.identifier = identifier, this.callSignature = callSignature, this.block = block, functionKeyword.parent = this, identifier && (identifier.parent = this), callSignature.parent = this, block.parent = this; + } + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.FunctionExpressionSyntax = FunctionExpressionSyntax; + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(data) { + _super.call(this, data); + } + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + Concrete.OmittedExpressionSyntax = OmittedExpressionSyntax; + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(data, varKeyword, variableDeclarators) { + _super.call(this, data); + this.varKeyword = varKeyword, this.variableDeclarators = variableDeclarators, varKeyword.parent = this, !TypeScript.isShared(variableDeclarators) && (variableDeclarators.parent = this); + } + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + Concrete.VariableDeclarationSyntax = VariableDeclarationSyntax; + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(data, propertyName, typeAnnotation, equalsValueClause) { + _super.call(this, data); + this.propertyName = propertyName, this.typeAnnotation = typeAnnotation, this.equalsValueClause = equalsValueClause, propertyName.parent = this, typeAnnotation && (typeAnnotation.parent = this), equalsValueClause && (equalsValueClause.parent = this); + } + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + Concrete.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(data, typeArgumentList, openParenToken, _arguments, closeParenToken) { + _super.call(this, data); + this.typeArgumentList = typeArgumentList, this.openParenToken = openParenToken, this.arguments = _arguments, this.closeParenToken = closeParenToken, typeArgumentList && (typeArgumentList.parent = this), openParenToken.parent = this, !TypeScript.isShared(_arguments) && (_arguments.parent = this), closeParenToken.parent = this; + } + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + Concrete.ArgumentListSyntax = ArgumentListSyntax; + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(data, openParenToken, parameters, closeParenToken) { + _super.call(this, data); + this.openParenToken = openParenToken, this.parameters = parameters, this.closeParenToken = closeParenToken, openParenToken.parent = this, !TypeScript.isShared(parameters) && (parameters.parent = this), closeParenToken.parent = this; + } + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + Concrete.ParameterListSyntax = ParameterListSyntax; + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(data, lessThanToken, typeArguments, greaterThanToken) { + _super.call(this, data); + this.lessThanToken = lessThanToken, this.typeArguments = typeArguments, this.greaterThanToken = greaterThanToken, lessThanToken.parent = this, !TypeScript.isShared(typeArguments) && (typeArguments.parent = this), greaterThanToken.parent = this; + } + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + Concrete.TypeArgumentListSyntax = TypeArgumentListSyntax; + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(data, lessThanToken, typeParameters, greaterThanToken) { + _super.call(this, data); + this.lessThanToken = lessThanToken, this.typeParameters = typeParameters, this.greaterThanToken = greaterThanToken, lessThanToken.parent = this, !TypeScript.isShared(typeParameters) && (typeParameters.parent = this), greaterThanToken.parent = this; + } + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + Concrete.TypeParameterListSyntax = TypeParameterListSyntax; + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(data, extendsOrImplementsKeyword, typeNames) { + _super.call(this, data); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword, this.typeNames = typeNames, extendsOrImplementsKeyword.parent = this, !TypeScript.isShared(typeNames) && (typeNames.parent = this); + } + HeritageClauseSyntax.prototype.kind = function () { + return this.extendsOrImplementsKeyword.kind() === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.HeritageClauseSyntax = HeritageClauseSyntax; + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(data, equalsToken, value) { + _super.call(this, data); + this.equalsToken = equalsToken, this.value = value, equalsToken.parent = this, value.parent = this; + } + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(data, caseKeyword, expression, colonToken, statements) { + _super.call(this, data); + this.caseKeyword = caseKeyword, this.expression = expression, this.colonToken = colonToken, this.statements = statements, caseKeyword.parent = this, expression.parent = this, colonToken.parent = this, !TypeScript.isShared(statements) && (statements.parent = this); + } + return CaseSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(data, defaultKeyword, colonToken, statements) { + _super.call(this, data); + this.defaultKeyword = defaultKeyword, this.colonToken = colonToken, this.statements = statements, defaultKeyword.parent = this, colonToken.parent = this, !TypeScript.isShared(statements) && (statements.parent = this); + } + return DefaultSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(data, elseKeyword, statement) { + _super.call(this, data); + this.elseKeyword = elseKeyword, this.statement = statement, elseKeyword.parent = this, statement.parent = this; + } + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.ElseClauseSyntax = ElseClauseSyntax; + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(data, catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + _super.call(this, data); + this.catchKeyword = catchKeyword, this.openParenToken = openParenToken, this.identifier = identifier, this.typeAnnotation = typeAnnotation, this.closeParenToken = closeParenToken, this.block = block, catchKeyword.parent = this, openParenToken.parent = this, identifier.parent = this, typeAnnotation && (typeAnnotation.parent = this), closeParenToken.parent = this, block.parent = this; + } + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.CatchClauseSyntax = CatchClauseSyntax; + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(data, finallyKeyword, block) { + _super.call(this, data); + this.finallyKeyword = finallyKeyword, this.block = block, finallyKeyword.parent = this, block.parent = this; + } + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + Concrete.FinallyClauseSyntax = FinallyClauseSyntax; + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(data, identifier, constraint) { + _super.call(this, data); + this.identifier = identifier, this.constraint = constraint, identifier.parent = this, constraint && (constraint.parent = this); + } + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + Concrete.TypeParameterSyntax = TypeParameterSyntax; + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(data, extendsKeyword, typeOrExpression) { + _super.call(this, data); + this.extendsKeyword = extendsKeyword, this.typeOrExpression = typeOrExpression, extendsKeyword.parent = this, typeOrExpression.parent = this; + } + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + Concrete.ConstraintSyntax = ConstraintSyntax; + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(data, propertyName, colonToken, expression) { + _super.call(this, data); + this.propertyName = propertyName, this.colonToken = colonToken, this.expression = expression, propertyName.parent = this, colonToken.parent = this, expression.parent = this; + } + return SimplePropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + Concrete.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(data, propertyName, callSignature, block) { + _super.call(this, data); + this.propertyName = propertyName, this.callSignature = callSignature, this.block = block, propertyName.parent = this, callSignature.parent = this, block.parent = this; + } + return FunctionPropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + Concrete.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(data, dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + _super.call(this, data); + this.dotDotDotToken = dotDotDotToken, this.modifiers = modifiers, this.identifier = identifier, this.questionToken = questionToken, this.typeAnnotation = typeAnnotation, this.equalsValueClause = equalsValueClause, dotDotDotToken && (dotDotDotToken.parent = this), !TypeScript.isShared(modifiers) && (modifiers.parent = this), identifier.parent = this, questionToken && (questionToken.parent = this), typeAnnotation && (typeAnnotation.parent = this), equalsValueClause && (equalsValueClause.parent = this); + } + return ParameterSyntax; + })(TypeScript.SyntaxNode); + Concrete.ParameterSyntax = ParameterSyntax; + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(data, propertyName, equalsValueClause) { + _super.call(this, data); + this.propertyName = propertyName, this.equalsValueClause = equalsValueClause, propertyName.parent = this, equalsValueClause && (equalsValueClause.parent = this); + } + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + Concrete.EnumElementSyntax = EnumElementSyntax; + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(data, colonToken, type) { + _super.call(this, data); + this.colonToken = colonToken, this.type = type, colonToken.parent = this, type.parent = this; + } + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + Concrete.TypeAnnotationSyntax = TypeAnnotationSyntax; + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(data, requireKeyword, openParenToken, stringLiteral, closeParenToken) { + _super.call(this, data); + this.requireKeyword = requireKeyword, this.openParenToken = openParenToken, this.stringLiteral = stringLiteral, this.closeParenToken = closeParenToken, requireKeyword.parent = this, openParenToken.parent = this, stringLiteral.parent = this, closeParenToken.parent = this; + } + return ExternalModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + Concrete.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(data, moduleName) { + _super.call(this, data); + this.moduleName = moduleName, moduleName.parent = this; + } + return ModuleNameModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + Concrete.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + SourceUnitSyntax.prototype.__kind = 120 /* SourceUnit */, QualifiedNameSyntax.prototype.__kind = 121 /* QualifiedName */, ObjectTypeSyntax.prototype.__kind = 122 /* ObjectType */, FunctionTypeSyntax.prototype.__kind = 123 /* FunctionType */, ArrayTypeSyntax.prototype.__kind = 124 /* ArrayType */, ConstructorTypeSyntax.prototype.__kind = 125 /* ConstructorType */, GenericTypeSyntax.prototype.__kind = 126 /* GenericType */, TypeQuerySyntax.prototype.__kind = 127 /* TypeQuery */, InterfaceDeclarationSyntax.prototype.__kind = 128 /* InterfaceDeclaration */, FunctionDeclarationSyntax.prototype.__kind = 129 /* FunctionDeclaration */, ModuleDeclarationSyntax.prototype.__kind = 130 /* ModuleDeclaration */, ClassDeclarationSyntax.prototype.__kind = 131 /* ClassDeclaration */, EnumDeclarationSyntax.prototype.__kind = 132 /* EnumDeclaration */, ImportDeclarationSyntax.prototype.__kind = 133 /* ImportDeclaration */, ExportAssignmentSyntax.prototype.__kind = 134 /* ExportAssignment */, MemberFunctionDeclarationSyntax.prototype.__kind = 135 /* MemberFunctionDeclaration */, MemberVariableDeclarationSyntax.prototype.__kind = 136 /* MemberVariableDeclaration */, ConstructorDeclarationSyntax.prototype.__kind = 137 /* ConstructorDeclaration */, IndexMemberDeclarationSyntax.prototype.__kind = 138 /* IndexMemberDeclaration */, GetAccessorSyntax.prototype.__kind = 139 /* GetAccessor */, SetAccessorSyntax.prototype.__kind = 140 /* SetAccessor */, PropertySignatureSyntax.prototype.__kind = 141 /* PropertySignature */, CallSignatureSyntax.prototype.__kind = 142 /* CallSignature */, ConstructSignatureSyntax.prototype.__kind = 143 /* ConstructSignature */, IndexSignatureSyntax.prototype.__kind = 144 /* IndexSignature */, MethodSignatureSyntax.prototype.__kind = 145 /* MethodSignature */, BlockSyntax.prototype.__kind = 146 /* Block */, IfStatementSyntax.prototype.__kind = 147 /* IfStatement */, VariableStatementSyntax.prototype.__kind = 148 /* VariableStatement */, ExpressionStatementSyntax.prototype.__kind = 149 /* ExpressionStatement */, ReturnStatementSyntax.prototype.__kind = 150 /* ReturnStatement */, SwitchStatementSyntax.prototype.__kind = 151 /* SwitchStatement */, BreakStatementSyntax.prototype.__kind = 152 /* BreakStatement */, ContinueStatementSyntax.prototype.__kind = 153 /* ContinueStatement */, ForStatementSyntax.prototype.__kind = 154 /* ForStatement */, ForInStatementSyntax.prototype.__kind = 155 /* ForInStatement */, EmptyStatementSyntax.prototype.__kind = 156 /* EmptyStatement */, ThrowStatementSyntax.prototype.__kind = 157 /* ThrowStatement */, WhileStatementSyntax.prototype.__kind = 158 /* WhileStatement */, TryStatementSyntax.prototype.__kind = 159 /* TryStatement */, LabeledStatementSyntax.prototype.__kind = 160 /* LabeledStatement */, DoStatementSyntax.prototype.__kind = 161 /* DoStatement */, DebuggerStatementSyntax.prototype.__kind = 162 /* DebuggerStatement */, WithStatementSyntax.prototype.__kind = 163 /* WithStatement */, DeleteExpressionSyntax.prototype.__kind = 170 /* DeleteExpression */, TypeOfExpressionSyntax.prototype.__kind = 171 /* TypeOfExpression */, VoidExpressionSyntax.prototype.__kind = 172 /* VoidExpression */, ConditionalExpressionSyntax.prototype.__kind = 186 /* ConditionalExpression */, MemberAccessExpressionSyntax.prototype.__kind = 212 /* MemberAccessExpression */, InvocationExpressionSyntax.prototype.__kind = 213 /* InvocationExpression */, ArrayLiteralExpressionSyntax.prototype.__kind = 214 /* ArrayLiteralExpression */, ObjectLiteralExpressionSyntax.prototype.__kind = 215 /* ObjectLiteralExpression */, ObjectCreationExpressionSyntax.prototype.__kind = 216 /* ObjectCreationExpression */, ParenthesizedExpressionSyntax.prototype.__kind = 217 /* ParenthesizedExpression */, ParenthesizedArrowFunctionExpressionSyntax.prototype.__kind = 218 /* ParenthesizedArrowFunctionExpression */, SimpleArrowFunctionExpressionSyntax.prototype.__kind = 219 /* SimpleArrowFunctionExpression */, CastExpressionSyntax.prototype.__kind = 220 /* CastExpression */, ElementAccessExpressionSyntax.prototype.__kind = 221 /* ElementAccessExpression */, FunctionExpressionSyntax.prototype.__kind = 222 /* FunctionExpression */, OmittedExpressionSyntax.prototype.__kind = 223 /* OmittedExpression */, VariableDeclarationSyntax.prototype.__kind = 224 /* VariableDeclaration */, VariableDeclaratorSyntax.prototype.__kind = 225 /* VariableDeclarator */, ArgumentListSyntax.prototype.__kind = 226 /* ArgumentList */, ParameterListSyntax.prototype.__kind = 227 /* ParameterList */, TypeArgumentListSyntax.prototype.__kind = 228 /* TypeArgumentList */, TypeParameterListSyntax.prototype.__kind = 229 /* TypeParameterList */, EqualsValueClauseSyntax.prototype.__kind = 232 /* EqualsValueClause */, CaseSwitchClauseSyntax.prototype.__kind = 233 /* CaseSwitchClause */, DefaultSwitchClauseSyntax.prototype.__kind = 234 /* DefaultSwitchClause */, ElseClauseSyntax.prototype.__kind = 235 /* ElseClause */, CatchClauseSyntax.prototype.__kind = 236 /* CatchClause */, FinallyClauseSyntax.prototype.__kind = 237 /* FinallyClause */, TypeParameterSyntax.prototype.__kind = 238 /* TypeParameter */, ConstraintSyntax.prototype.__kind = 239 /* Constraint */, SimplePropertyAssignmentSyntax.prototype.__kind = 240 /* SimplePropertyAssignment */, FunctionPropertyAssignmentSyntax.prototype.__kind = 241 /* FunctionPropertyAssignment */, ParameterSyntax.prototype.__kind = 242 /* Parameter */, EnumElementSyntax.prototype.__kind = 243 /* EnumElement */, TypeAnnotationSyntax.prototype.__kind = 244 /* TypeAnnotation */, ExternalModuleReferenceSyntax.prototype.__kind = 245 /* ExternalModuleReference */, ModuleNameModuleReferenceSyntax.prototype.__kind = 246 /* ModuleNameModuleReference */; + })(Syntax.Concrete || (Syntax.Concrete = {})); + var Concrete = Syntax.Concrete; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.syntaxDiagnosticsTime = 0; + var SyntaxTree = (function () { + function SyntaxTree(isConcrete, sourceUnit, isDeclaration, diagnostics, fileName, text, languageVersion) { + this.text = text; + this._allDiagnostics = null; + this._isConcrete = isConcrete; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = text.lineMap(); + this._languageVersion = languageVersion; + sourceUnit.syntaxTree = this; + } + SyntaxTree.prototype.isConcrete = function () { + return this._isConcrete; + }; + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + var diagnostics = []; + TypeScript.visitNodeOrToken(new GrammarCheckerWalker(this, diagnostics), this.sourceUnit()); + return diagnostics; + }; + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + var start = new Date().getTime(); + this._allDiagnostics = this.computeDiagnostics(); + TypeScript.syntaxDiagnosticsTime += new Date().getTime() - start; + } + return this._allDiagnostics; + }; + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + SyntaxTree.prototype.languageVersion = function () { + return this._languageVersion; + }; + SyntaxTree.prototype.cacheSyntaxTreeInfo = function () { + var sourceUnit = this.sourceUnit(); + var firstToken = firstSyntaxTreeToken(this); + var leadingTrivia = firstToken.leadingTrivia(this.text); + this._isExternalModule = externalModuleIndicatorSpanWorker(this, firstToken) !== null; + var amdDependencies = []; + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); + } + } + } + this._amdDependencies = amdDependencies; + }; + SyntaxTree.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s* 0) { + var modifiers = parameter.modifiers; + for (var i = 0, n = modifiers.length; i < n; i++) { + var modifier = modifiers[i]; + if (this.checkParameterAccessibilityModifier(parameterList, modifier, i)) { + return true; + } + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifier = function (parameterList, modifier, modifierIndex) { + if (modifier.kind() !== 57 /* PublicKeyword */ && modifier.kind() !== 55 /* PrivateKeyword */) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_parameter, [modifier.text()]); + return true; + } + else { + if (modifierIndex > 0) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkForTrailingComma = function (list) { + if (TypeScript.childCount(list) === 0 || TypeScript.childCount(list) % 2 === 1) { + return false; + } + var child = TypeScript.childAt(list, TypeScript.childCount(list) - 1); + this.pushDiagnostic(child, TypeScript.DiagnosticCode.Trailing_comma_not_allowed); + return true; + }; + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, reportToken, listKind) { + if (TypeScript.childCount(list) > 0) { + return false; + } + this.pushDiagnostic(reportToken, TypeScript.DiagnosticCode._0_list_cannot_be_empty, [listKind]); + return true; + }; + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingComma(node.parameters)) { + return; + } + _super.prototype.visitParameterList.call(this, node); + }; + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingComma(node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, node.extendsOrImplementsKeyword, TypeScript.SyntaxFacts.getText(node.extendsOrImplementsKeyword.kind()))) { + return; + } + _super.prototype.visitHeritageClause.call(this, node); + }; + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingComma(node.arguments)) { + return; + } + _super.prototype.visitArgumentList.call(this, node); + }; + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForAtLeastOneElement(node, node.variableDeclarators, node.varKeyword, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.variable_declaration, null)) || this.checkForTrailingComma(node.variableDeclarators)) { + return; + } + _super.prototype.visitVariableDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingComma(node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, node.lessThanToken, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_argument, null))) { + return; + } + _super.prototype.visitTypeArgumentList.call(this, node); + }; + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingComma(node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, node.lessThanToken, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_parameter, null))) { + return; + } + _super.prototype.visitTypeParameterList.call(this, node); + }; + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + if (node.parameters.length !== 1) { + this.pushDiagnostic(node.openBracketToken, TypeScript.DiagnosticCode.Index_signature_must_have_exactly_one_parameter); + return true; + } + var parameter = node.parameters[0]; + if (parameter.dotDotDotToken) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.Index_signatures_cannot_have_rest_parameters); + return true; + } + else if (parameter.modifiers.length > 0) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_accessibility_modifiers); + return true; + } + else if (parameter.questionToken) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_a_question_mark); + return true; + } + else if (parameter.equalsValueClause) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_an_initializer); + return true; + } + else if (!parameter.typeAnnotation) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.Index_signature_parameter_must_have_a_type_annotation); + return true; + } + else if (parameter.typeAnnotation.type.kind() !== 69 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 67 /* NumberKeyword */) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.Index_signature_parameter_type_must_be_string_or_number); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + return; + } + if (!node.typeAnnotation) { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Index_signature_must_have_a_type_annotation); + return; + } + _super.prototype.visitIndexSignature.call(this, node); + }; + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + for (var i = 0, n = node.heritageClauses.length; i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses[i]; + if (heritageClause.extendsOrImplementsKeyword.kind() === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic(heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + if (seenImplementsClause) { + this.pushDiagnostic(heritageClause, TypeScript.DiagnosticCode.extends_clause_must_precede_implements_clause); + return true; + } + if (heritageClause.typeNames.length > 1) { + this.pushDiagnostic(heritageClause, TypeScript.DiagnosticCode.Classes_can_only_extend_a_single_class); + return true; + } + seenExtendsClause = true; + } + else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.kind() === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic(heritageClause, TypeScript.DiagnosticCode.implements_clause_already_seen); + return true; + } + seenImplementsClause = true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + if (declareToken) { + this.pushDiagnostic(declareToken, TypeScript.DiagnosticCode.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, reportToken, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + this.pushDiagnostic(reportToken, TypeScript.DiagnosticCode.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + return true; + } + } + }; + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.identifier, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node)) { + return; + } + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var seenExtendsClause = false; + for (var i = 0, n = node.heritageClauses.length; i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses[i]; + if (heritageClause.extendsOrImplementsKeyword.kind() === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic(heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + seenExtendsClause = true; + } + else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.kind() === 51 /* ImplementsKeyword */); + this.pushDiagnostic(heritageClause, TypeScript.DiagnosticCode.Interface_declaration_cannot_have_implements_clause); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + for (var i = 0, n = modifiers.length; i < n; i++) { + var modifier = modifiers[i]; + if (modifier.kind() === 63 /* DeclareKeyword */) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode.A_declare_modifier_cannot_be_used_with_an_interface_declaration); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + return; + } + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + for (var i = 0, n = list.length; i < n; i++) { + var modifier = list[i]; + if (modifier.kind() === 57 /* PublicKeyword */ || modifier.kind() === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + if (seenStaticModifier) { + var previousToken = list[i - 1]; + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [modifier.text(), previousToken.text()]); + return true; + } + seenAccessibilityModifier = true; + } + else if (modifier.kind() === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return true; + } + seenStaticModifier = true; + } + else { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_class_element, [modifier.text()]); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + return; + } + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + return; + } + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.checkGetAccessorParameter = function (node) { + if (node.callSignature.parameterList.parameters.length !== 0) { + this.pushDiagnostic(node.propertyName, TypeScript.DiagnosticCode.get_accessor_cannot_have_parameters); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitIndexMemberDeclaration = function (node) { + if (this.checkIndexMemberModifiers(node)) { + return; + } + _super.prototype.visitIndexMemberDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.checkIndexMemberModifiers = function (node) { + if (node.modifiers.length > 0) { + this.pushDiagnostic(TypeScript.childAt(node.modifiers, 0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, reportToken, languageVersion, diagnosticKey) { + if (this.syntaxTree.languageVersion() < languageVersion) { + this.pushDiagnostic(reportToken, diagnosticKey); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitObjectLiteralExpression = function (node) { + var savedInObjectLiteralExpression = this.inObjectLiteralExpression; + this.inObjectLiteralExpression = true; + _super.prototype.visitObjectLiteralExpression.call(this, node); + this.inObjectLiteralExpression = savedInObjectLiteralExpression; + }; + GrammarCheckerWalker.prototype.visitGetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.propertyName, 1 /* ES5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkForDisallowedAccessorTypeParameters(node.callSignature) || this.checkGetAccessorParameter(node)) { + return; + } + _super.prototype.visitGetAccessor.call(this, node); + }; + GrammarCheckerWalker.prototype.checkForDisallowedSetAccessorTypeAnnotation = function (accessor) { + if (accessor.callSignature.typeAnnotation) { + this.pushDiagnostic(accessor.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_set_accessor); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkForDisallowedAccessorTypeParameters = function (callSignature) { + if (callSignature.typeParameterList !== null) { + this.pushDiagnostic(callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_an_accessor); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkForAccessorDeclarationInAmbientContext = function (accessor) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic(accessor, TypeScript.DiagnosticCode.Accessors_are_not_allowed_in_ambient_contexts); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkSetAccessorParameter = function (node) { + var parameters = node.callSignature.parameterList.parameters; + if (TypeScript.childCount(parameters) !== 1) { + this.pushDiagnostic(node.propertyName, TypeScript.DiagnosticCode.set_accessor_must_have_exactly_one_parameter); + return true; + } + var parameter = parameters[0]; + if (parameter.questionToken) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_be_optional); + return true; + } + if (parameter.equalsValueClause) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_have_an_initializer); + return true; + } + if (parameter.dotDotDotToken) { + this.pushDiagnostic(parameter, TypeScript.DiagnosticCode.set_accessor_cannot_have_rest_parameter); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitSetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.propertyName, 1 /* ES5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkForDisallowedAccessorTypeParameters(node.callSignature) || this.checkForDisallowedSetAccessorTypeAnnotation(node) || this.checkSetAccessorParameter(node)) { + return; + } + _super.prototype.visitSetAccessor.call(this, node); + }; + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.identifier, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + return; + } + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var previousValueWasComputed = false; + for (var i = 0, n = TypeScript.childCount(node.enumElements); i < n; i++) { + var child = TypeScript.childAt(node.enumElements, i); + if (i % 2 === 0) { + var enumElement = child; + if (!enumElement.equalsValueClause && previousValueWasComputed) { + this.pushDiagnostic(enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer); + return true; + } + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); + } + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitEnumElement = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + var expression = node.equalsValueClause.value; + if (!TypeScript.Syntax.isIntegerLiteral(expression)) { + this.pushDiagnostic(node.equalsValueClause.value, TypeScript.DiagnosticCode.Ambient_enum_elements_can_only_have_integer_literal_initializers); + return; + } + } + _super.prototype.visitEnumElement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.super_invocation_cannot_have_type_arguments); + } + _super.prototype.visitInvocationExpression.call(this, node); + }; + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var seenExportModifier = false; + var seenDeclareModifier = false; + for (var i = 0, n = modifiers.length; i < n; i++) { + var modifier = modifiers[i]; + if (modifier.kind() === 57 /* PublicKeyword */ || modifier.kind() === 55 /* PrivateKeyword */ || modifier.kind() === 58 /* StaticKeyword */) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_module_element, [modifier.text()]); + return true; + } + if (modifier.kind() === 63 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return; + } + seenDeclareModifier = true; + } + else if (modifier.kind() === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return; + } + if (seenDeclareModifier) { + this.pushDiagnostic(modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(63 /* DeclareKeyword */)]); + return; + } + seenExportModifier = true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + if (!node.stringLiteral) { + for (var i = 0, n = node.moduleElements.length; i < n; i++) { + var child = node.moduleElements[i]; + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.pushDiagnostic(importDeclaration, TypeScript.DiagnosticCode.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + } + } + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifierOnImportDeclaration = function (modifiers) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + if (declareToken) { + this.pushDiagnostic(declareToken, TypeScript.DiagnosticCode.A_declare_modifier_cannot_be_used_with_an_import_declaration); + return true; + } + }; + GrammarCheckerWalker.prototype.visitImportDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifierOnImportDeclaration(node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + return; + } + _super.prototype.visitImportDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.stringLiteral ? node.stringLiteral : TypeScript.firstToken(node.name), node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node)) { + return; + } + if (node.stringLiteral) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + this.pushDiagnostic(node.stringLiteral, TypeScript.DiagnosticCode.Only_ambient_modules_can_use_quoted_names); + return; + } + } + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + return; + } + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + for (var i = 0, n = node.moduleElements.length; i < n; i++) { + var child = node.moduleElements[i]; + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic(child, TypeScript.DiagnosticCode.Export_assignment_cannot_be_used_in_internal_modules); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.checkForBlockInAmbientContext(node)) { + return; + } + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + GrammarCheckerWalker.prototype.checkForBlockInAmbientContext = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + if (node.parent.kind() === 1 /* List */) { + this.pushDiagnostic(TypeScript.firstToken(node), TypeScript.DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts); + } + else { + this.pushDiagnostic(TypeScript.firstToken(node), TypeScript.DiagnosticCode.A_function_implementation_cannot_be_declared_in_an_ambient_context); + } + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic(TypeScript.firstToken(node), TypeScript.DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkBreakStatementTarget(node)) { + return; + } + _super.prototype.visitBreakStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkContinueStatementTarget(node)) { + return; + } + _super.prototype.visitContinueStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.checkBreakStatementTarget = function (node) { + if (node.identifier) { + var breakableLabels = this.getEnclosingLabels(node, true, false); + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { return TypeScript.tokenValueText(s.identifier) === TypeScript.tokenValueText(node.identifier); })) { + var breakableLabels = this.getEnclosingLabels(node, true, true); + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { return TypeScript.tokenValueText(s.identifier) === TypeScript.tokenValueText(node.identifier); })) { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary); + } + else { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Jump_target_not_found); + } + return true; + } + } + else if (!this.inIterationStatement(node, false) && !this.inSwitchStatement(node)) { + if (this.inIterationStatement(node, true)) { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary); + } + else { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement); + } + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.inSwitchStatement = function (ast) { + while (ast) { + if (ast.kind() === 151 /* SwitchStatement */) { + return true; + } + if (TypeScript.SyntaxUtilities.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + ast = ast.parent; + } + return false; + }; + GrammarCheckerWalker.prototype.isIterationStatement = function (ast) { + switch (ast.kind()) { + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.inIterationStatement = function (element, crossFunctions) { + while (element) { + if (this.isIterationStatement(element)) { + return true; + } + if (!crossFunctions && TypeScript.SyntaxUtilities.isAnyFunctionExpressionOrDeclaration(element)) { + return false; + } + element = element.parent; + } + return false; + }; + GrammarCheckerWalker.prototype.getEnclosingLabels = function (element, breakable, crossFunctions) { + var result = []; + element = element.parent; + while (element) { + if (element.kind() === 160 /* LabeledStatement */) { + var labeledStatement = element; + if (breakable) { + result.push(labeledStatement); + } + else { + if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { + result.push(labeledStatement); + } + } + } + if (!crossFunctions && TypeScript.SyntaxUtilities.isAnyFunctionExpressionOrDeclaration(element)) { + break; + } + element = element.parent; + } + return result; + }; + GrammarCheckerWalker.prototype.labelIsOnContinuableConstruct = function (statement) { + switch (statement.kind()) { + case 160 /* LabeledStatement */: + return this.labelIsOnContinuableConstruct(statement.statement); + case 158 /* WhileStatement */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 161 /* DoStatement */: + return true; + default: + return false; + } + }; + GrammarCheckerWalker.prototype.checkContinueStatementTarget = function (node) { + if (!this.inIterationStatement(node, false)) { + if (this.inIterationStatement(node, true)) { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary); + } + else { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement); + } + return true; + } + else if (node.identifier) { + var continuableLabels = this.getEnclosingLabels(node, false, false); + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { return TypeScript.tokenValueText(s.identifier) === TypeScript.tokenValueText(node.identifier); })) { + var continuableLabels = this.getEnclosingLabels(node, false, true); + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { return TypeScript.tokenValueText(s.identifier) === TypeScript.tokenValueText(node.identifier); })) { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary); + } + else { + this.pushDiagnostic(node, TypeScript.DiagnosticCode.Jump_target_not_found); + } + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitDebuggerStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitDoStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitEmptyStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitExpressionStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node) || this.checkForInLeftHandSideExpression(node)) { + return; + } + _super.prototype.visitForInStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.checkForInLeftHandSideExpression = function (node) { + if (node.left && !TypeScript.SyntaxUtilities.isLeftHandSizeExpression(node.left)) { + this.pushDiagnostic(node.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_in_for_in_statement); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.length > 1) { + this.pushDiagnostic(node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitForStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitIfStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInvalidLabelIdentifier(node)) { + return; + } + _super.prototype.visitLabeledStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.checkForInvalidLabelIdentifier = function (node) { + var labelIdentifier = TypeScript.tokenValueText(node.identifier); + var breakableLabels = this.getEnclosingLabels(node, true, false); + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { return TypeScript.tokenValueText(s.identifier) === labelIdentifier; }); + if (matchingLabel) { + this.pushDiagnostic(node.identifier, TypeScript.DiagnosticCode.Duplicate_identifier_0, [labelIdentifier]); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForReturnStatementNotInFunctionBody(node)) { + return; + } + _super.prototype.visitReturnStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.checkForReturnStatementNotInFunctionBody = function (node) { + for (var element = node; element; element = element.parent) { + if (TypeScript.SyntaxUtilities.isAnyFunctionExpressionOrDeclaration(element)) { + return false; + } + } + this.pushDiagnostic(TypeScript.firstToken(node), TypeScript.DiagnosticCode.return_statement_must_be_contained_within_a_function_body); + return true; + }; + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitSwitchStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitThrowStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitTryStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + return; + } + _super.prototype.visitWhileStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForWithInStrictMode(node)) { + return; + } + _super.prototype.visitWithStatement.call(this, node); + }; + GrammarCheckerWalker.prototype.checkForWithInStrictMode = function (node) { + if (TypeScript.parsedInStrictMode(node)) { + this.pushDiagnostic(TypeScript.firstToken(node), TypeScript.DiagnosticCode.with_statements_are_not_allowed_in_strict_mode); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock || this.inObjectLiteralExpression) { + if (modifiers.length > 0) { + this.pushDiagnostic(TypeScript.childAt(modifiers, 0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.identifier, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedEvalOrArguments(node, node.identifier)) { + return; + } + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.visitFunctionExpression = function (node) { + if (this.checkForDisallowedEvalOrArguments(node, node.identifier)) { + return; + } + _super.prototype.visitFunctionExpression.call(this, node); + }; + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration.varKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + return; + } + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + for (var i = 0, n = TypeScript.childCount(list); i < n; i++) { + var child = TypeScript.childAt(list, i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic(child, TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(kind)]); + } + } + return false; + }; + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 78 /* SemicolonToken */)) { + return; + } + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + GrammarCheckerWalker.prototype.visitVariableDeclarator = function (node) { + if (this.checkVariableDeclaratorInitializer(node) || this.checkVariableDeclaratorIdentifier(node)) { + return; + } + _super.prototype.visitVariableDeclarator.call(this, node); + }; + GrammarCheckerWalker.prototype.checkVariableDeclaratorIdentifier = function (node) { + if (node.parent.kind() !== 136 /* MemberVariableDeclaration */) { + if (this.checkForDisallowedEvalOrArguments(node, node.propertyName)) { + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkVariableDeclaratorInitializer = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + this.pushDiagnostic(TypeScript.firstToken(node.equalsValueClause.value), TypeScript.DiagnosticCode.Initializers_are_not_allowed_in_ambient_contexts); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { + return; + } + _super.prototype.visitConstructorDeclaration.call(this, node); + }; + GrammarCheckerWalker.prototype.checkConstructorModifiers = function (modifiers) { + for (var i = 0, n = modifiers.length; i < n; i++) { + var child = modifiers[i]; + if (child.kind() !== 57 /* PublicKeyword */) { + this.pushDiagnostic(child, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [TypeScript.SyntaxFacts.getText(child.kind())]); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + if (node.callSignature.typeParameterList) { + this.pushDiagnostic(node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + if (node.callSignature.typeAnnotation) { + this.pushDiagnostic(node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitBinaryExpression = function (node) { + if (this.checkIllegalAssignment(node)) { + return; + } + _super.prototype.visitBinaryExpression.call(this, node); + }; + GrammarCheckerWalker.prototype.visitPrefixUnaryExpression = function (node) { + if (TypeScript.parsedInStrictMode(node) && this.isPreIncrementOrDecrementExpression(node) && this.isEvalOrArguments(node.operand)) { + this.pushDiagnostic(node.operatorToken, TypeScript.DiagnosticCode.Invalid_use_of_0_in_strict_mode, [this.getEvalOrArguments(node.operand)]); + } + _super.prototype.visitPrefixUnaryExpression.call(this, node); + }; + GrammarCheckerWalker.prototype.visitPostfixUnaryExpression = function (node) { + if (TypeScript.parsedInStrictMode(node) && this.isEvalOrArguments(node.operand)) { + this.pushDiagnostic(node.operatorToken, TypeScript.DiagnosticCode.Invalid_use_of_0_in_strict_mode, [this.getEvalOrArguments(node.operand)]); + } + _super.prototype.visitPostfixUnaryExpression.call(this, node); + }; + GrammarCheckerWalker.prototype.visitParameter = function (node) { + if (this.checkForDisallowedEvalOrArguments(node, node.identifier)) { + return; + } + _super.prototype.visitParameter.call(this, node); + }; + GrammarCheckerWalker.prototype.checkForDisallowedEvalOrArguments = function (node, token) { + if (token) { + if (TypeScript.parsedInStrictMode(node) && this.isEvalOrArguments(token)) { + this.pushDiagnostic(token, TypeScript.DiagnosticCode.Invalid_use_of_0_in_strict_mode, [this.getEvalOrArguments(token)]); + return true; + } + } + return false; + }; + GrammarCheckerWalker.prototype.isPreIncrementOrDecrementExpression = function (node) { + switch (node.kind()) { + case 169 /* PreDecrementExpression */: + case 168 /* PreIncrementExpression */: + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.visitDeleteExpression = function (node) { + if (TypeScript.parsedInStrictMode(node) && node.expression.kind() === 11 /* IdentifierName */) { + this.pushDiagnostic(TypeScript.firstToken(node), TypeScript.DiagnosticCode.delete_cannot_be_called_on_an_identifier_in_strict_mode); + return; + } + _super.prototype.visitDeleteExpression.call(this, node); + }; + GrammarCheckerWalker.prototype.checkIllegalAssignment = function (node) { + if (TypeScript.parsedInStrictMode(node) && TypeScript.SyntaxFacts.isAssignmentOperatorToken(node.operatorToken.kind()) && this.isEvalOrArguments(node.left)) { + this.pushDiagnostic(node.operatorToken, TypeScript.DiagnosticCode.Invalid_use_of_0_in_strict_mode, [this.getEvalOrArguments(node.left)]); + return true; + } + return false; + }; + GrammarCheckerWalker.prototype.getEvalOrArguments = function (expr) { + if (expr.kind() === 11 /* IdentifierName */) { + var text = TypeScript.tokenValueText(expr); + if (text === "eval" || text === "arguments") { + return text; + } + } + return null; + }; + GrammarCheckerWalker.prototype.isEvalOrArguments = function (expr) { + return this.getEvalOrArguments(expr) !== null; + }; + GrammarCheckerWalker.prototype.visitConstraint = function (node) { + if (this.checkConstraintType(node)) { + return; + } + _super.prototype.visitConstraint.call(this, node); + }; + GrammarCheckerWalker.prototype.checkConstraintType = function (node) { + if (!TypeScript.SyntaxFacts.isType(node.typeOrExpression.kind())) { + this.pushDiagnostic(node.typeOrExpression, TypeScript.DiagnosticCode.Type_expected); + return true; + } + return false; + }; + return GrammarCheckerWalker; + })(TypeScript.SyntaxWalker); + function firstSyntaxTreeToken(syntaxTree) { + var scanner = TypeScript.Scanner.createScanner(syntaxTree.languageVersion(), syntaxTree.text, function () { + }); + return scanner.scan(false); + } + function externalModuleIndicatorSpan(syntaxTree) { + var firstToken = firstSyntaxTreeToken(syntaxTree); + return externalModuleIndicatorSpanWorker(syntaxTree, firstToken); + } + TypeScript.externalModuleIndicatorSpan = externalModuleIndicatorSpan; + function externalModuleIndicatorSpanWorker(syntaxTree, firstToken) { + var leadingTrivia = firstToken.leadingTrivia(syntaxTree.text); + return implicitImportSpan(leadingTrivia) || topLevelImportOrExportSpan(syntaxTree.sourceUnit()); + } + TypeScript.externalModuleIndicatorSpanWorker = externalModuleIndicatorSpanWorker; + function implicitImportSpan(sourceUnitLeadingTrivia) { + for (var i = 0, n = sourceUnitLeadingTrivia.count(); i < n; i++) { + var trivia = sourceUnitLeadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var span = implicitImportSpanWorker(trivia); + if (span) { + return span; + } + } + } + return null; + } + function implicitImportSpanWorker(trivia) { + var implicitImportRegEx = /^(\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(trivia.fullText()); + if (match) { + return new TypeScript.TextSpan(trivia.fullStart(), trivia.fullWidth()); + } + return null; + } + function topLevelImportOrExportSpan(node) { + for (var i = 0, n = node.moduleElements.length; i < n; i++) { + var moduleElement = node.moduleElements[i]; + var _firstToken = TypeScript.firstToken(moduleElement); + if (_firstToken !== null && _firstToken.kind() === 47 /* ExportKeyword */) { + return new TypeScript.TextSpan(TypeScript.start(_firstToken), TypeScript.width(_firstToken)); + } + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var literal = importDecl.moduleReference.stringLiteral; + return new TypeScript.TextSpan(TypeScript.start(literal), TypeScript.width(literal)); + } + } + } + return null; + } +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + }; + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* ES3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } + else if (languageVersion === 1 /* ES5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } + else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* ES3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } + else if (languageVersion === 1 /* ES5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } + else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + Unicode.unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + Unicode.unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (IncrementalParser) { + function createParserSource(oldSyntaxTree, textChangeRange, text) { + var fileName = oldSyntaxTree.fileName(); + var languageVersion = oldSyntaxTree.languageVersion(); + var _scannerParserSource; + var _changeRange; + var _changeRangeNewSpan; + var _changeDelta = 0; + var _oldSourceUnitCursor = getSyntaxCursor(); + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + var _outstandingRewindPointCount = 0; + if (oldSourceUnit.moduleElements.length > 0) { + _oldSourceUnitCursor.pushElement(TypeScript.childAt(oldSourceUnit.moduleElements, 0), 0); + } + _changeRange = extendToAffectedRange(textChangeRange, oldSourceUnit); + _changeRangeNewSpan = _changeRange.newSpan(); + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert((TypeScript.fullWidth(oldSourceUnit) - _changeRange.span().length() + _changeRange.newLength()) === text.length()); + } + _scannerParserSource = TypeScript.Scanner.createParserSource(oldSyntaxTree.fileName(), text, oldSyntaxTree.languageVersion()); + function release() { + _scannerParserSource.release(); + _scannerParserSource = null; + _oldSourceUnitCursor = null; + _outstandingRewindPointCount = 0; + } + function extendToAffectedRange(changeRange, sourceUnit) { + var maxLookahead = 1; + var start = changeRange.span().start(); + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = TypeScript.findToken(sourceUnit, start); + var position = token.fullStart(); + start = Math.max(0, position - 1); + } + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + return new TypeScript.TextChangeRange(finalSpan, finalLength); + } + function absolutePosition() { + return _scannerParserSource.absolutePosition(); + } + function tokenDiagnostics() { + return _scannerParserSource.tokenDiagnostics(); + } + function getRewindPoint() { + var rewindPoint = _scannerParserSource.getRewindPoint(); + var oldSourceUnitCursorClone = cloneSyntaxCursor(_oldSourceUnitCursor); + rewindPoint.changeDelta = _changeDelta; + rewindPoint.changeRange = _changeRange; + rewindPoint.oldSourceUnitCursor = _oldSourceUnitCursor; + _oldSourceUnitCursor = oldSourceUnitCursorClone; + _outstandingRewindPointCount++; + return rewindPoint; + } + function rewind(rewindPoint) { + _changeRange = rewindPoint.changeRange; + _changeDelta = rewindPoint.changeDelta; + returnSyntaxCursor(_oldSourceUnitCursor); + _oldSourceUnitCursor = rewindPoint.oldSourceUnitCursor; + rewindPoint.oldSourceUnitCursor = null; + _scannerParserSource.rewind(rewindPoint); + } + function releaseRewindPoint(rewindPoint) { + if (rewindPoint.oldSourceUnitCursor !== null) { + returnSyntaxCursor(rewindPoint.oldSourceUnitCursor); + } + _scannerParserSource.releaseRewindPoint(rewindPoint); + _outstandingRewindPointCount--; + TypeScript.Debug.assert(_outstandingRewindPointCount >= 0); + } + function isPinned() { + return _outstandingRewindPointCount > 0; + } + function canReadFromOldSourceUnit() { + if (isPinned()) { + return false; + } + if (_changeRange !== null && _changeRangeNewSpan.intersectsWithPosition(absolutePosition())) { + return false; + } + syncCursorToNewTextIfBehind(); + return _changeDelta === 0 && !_oldSourceUnitCursor.isFinished(); + } + function updateTokens(nodeOrToken) { + var position = absolutePosition(); + var tokenWasMoved = isPastChangeRange() && TypeScript.fullStart(nodeOrToken) !== position; + if (tokenWasMoved) { + setTokenFullStartWalker.position = position; + TypeScript.visitNodeOrToken(setTokenFullStartWalker, nodeOrToken); + } + } + function currentNode() { + if (canReadFromOldSourceUnit()) { + var node = tryGetNodeFromOldSourceUnit(); + if (node !== null) { + updateTokens(node); + return node; + } + } + return null; + } + function currentToken() { + if (canReadFromOldSourceUnit()) { + var token = tryGetTokenFromOldSourceUnit(); + if (token !== null) { + updateTokens(token); + return token; + } + } + return _scannerParserSource.currentToken(); + } + function currentContextualToken() { + return _scannerParserSource.currentContextualToken(); + } + function syncCursorToNewTextIfBehind() { + while (true) { + if (_oldSourceUnitCursor.isFinished()) { + break; + } + if (_changeDelta >= 0) { + break; + } + var currentNodeOrToken = _oldSourceUnitCursor.currentNodeOrToken(); + if (TypeScript.isNode(currentNodeOrToken) && (TypeScript.fullWidth(currentNodeOrToken) > Math.abs(_changeDelta))) { + _oldSourceUnitCursor.moveToFirstChild(); + } + else { + _oldSourceUnitCursor.moveToNextSibling(); + _changeDelta += TypeScript.fullWidth(currentNodeOrToken); + } + } + } + function intersectsWithChangeRangeSpanInOriginalText(start, length) { + return !isPastChangeRange() && _changeRange.span().intersectsWith(start, length); + } + function tryGetNodeFromOldSourceUnit() { + while (true) { + var node = _oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + if (!intersectsWithChangeRangeSpanInOriginalText(absolutePosition(), TypeScript.fullWidth(node))) { + var isIncrementallyUnusuable = TypeScript.isIncrementallyUnusable(node); + if (!isIncrementallyUnusuable) { + return node; + } + } + _oldSourceUnitCursor.moveToFirstChild(); + } + } + function canReuseTokenFromOldSourceUnit(position, token) { + if (token !== null) { + if (!intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable() && !TypeScript.Scanner.isContextualToken(token)) { + return true; + } + } + } + return false; + } + function tryGetTokenFromOldSourceUnit() { + var token = _oldSourceUnitCursor.currentToken(); + return canReuseTokenFromOldSourceUnit(absolutePosition(), token) ? token : null; + } + function peekToken(n) { + if (canReadFromOldSourceUnit()) { + var token = tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + return _scannerParserSource.peekToken(n); + } + function tryPeekTokenFromOldSourceUnit(n) { + var cursorClone = cloneSyntaxCursor(_oldSourceUnitCursor); + var token = tryPeekTokenFromOldSourceUnitWorker(n); + returnSyntaxCursor(_oldSourceUnitCursor); + _oldSourceUnitCursor = cursorClone; + return token; + } + function tryPeekTokenFromOldSourceUnitWorker(n) { + var currentPosition = absolutePosition(); + _oldSourceUnitCursor.moveToFirstToken(); + for (var i = 0; i < n; i++) { + var interimToken = _oldSourceUnitCursor.currentToken(); + if (!canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + currentPosition += interimToken.fullWidth(); + _oldSourceUnitCursor.moveToNextSibling(); + } + var token = _oldSourceUnitCursor.currentToken(); + return canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + } + function consumeNode(node) { + _oldSourceUnitCursor.moveToNextSibling(); + var _absolutePosition = absolutePosition() + TypeScript.fullWidth(node); + _scannerParserSource.resetToPosition(_absolutePosition); + } + function consumeToken(currentToken) { + if (_oldSourceUnitCursor.currentToken() === currentToken) { + _oldSourceUnitCursor.moveToNextSibling(); + var _absolutePosition = absolutePosition() + currentToken.fullWidth(); + _scannerParserSource.resetToPosition(_absolutePosition); + } + else { + _changeDelta -= currentToken.fullWidth(); + _scannerParserSource.consumeToken(currentToken); + if (!isPastChangeRange()) { + if (absolutePosition() >= _changeRangeNewSpan.end()) { + _changeDelta += _changeRange.newLength() - _changeRange.span().length(); + _changeRange = null; + } + } + } + } + function isPastChangeRange() { + return _changeRange === null; + } + return { + text: text, + fileName: fileName, + languageVersion: languageVersion, + currentNode: currentNode, + currentToken: currentToken, + currentContextualToken: currentContextualToken, + peekToken: peekToken, + consumeNode: consumeNode, + consumeToken: consumeToken, + getRewindPoint: getRewindPoint, + rewind: rewind, + releaseRewindPoint: releaseRewindPoint, + tokenDiagnostics: tokenDiagnostics, + release: release + }; + } + function createSyntaxCursorPiece(element, indexInParent) { + return { element: element, indexInParent: indexInParent }; + } + var syntaxCursorPool = []; + var syntaxCursorPoolCount = 0; + function returnSyntaxCursor(cursor) { + cursor.clean(); + syntaxCursorPool[syntaxCursorPoolCount] = cursor; + syntaxCursorPoolCount++; + } + function getSyntaxCursor() { + var cursor = syntaxCursorPoolCount > 0 ? syntaxCursorPool[syntaxCursorPoolCount - 1] : createSyntaxCursor(); + if (syntaxCursorPoolCount > 0) { + syntaxCursorPoolCount--; + syntaxCursorPool[syntaxCursorPoolCount] = null; + } + return cursor; + } + function cloneSyntaxCursor(cursor) { + var newCursor = getSyntaxCursor(); + newCursor.deepCopyFrom(cursor); + return newCursor; + } + function createSyntaxCursor() { + var pieces = []; + var currentPieceIndex = -1; + function clean() { + for (var i = 0, n = pieces.length; i < n; i++) { + var piece = pieces[i]; + if (piece.element === null) { + break; + } + piece.element = null; + piece.indexInParent = -1; + } + currentPieceIndex = -1; + } + function deepCopyFrom(other) { + for (var i = 0, n = other.pieces.length; i < n; i++) { + var piece = other.pieces[i]; + if (piece.element === null) { + break; + } + pushElement(piece.element, piece.indexInParent); + } + } + function isFinished() { + return currentPieceIndex < 0; + } + function currentNodeOrToken() { + if (isFinished()) { + return null; + } + var result = pieces[currentPieceIndex].element; + return result; + } + function currentNode() { + var element = currentNodeOrToken(); + return TypeScript.isNode(element) ? element : null; + } + function moveToFirstChild() { + var nodeOrToken = currentNodeOrToken(); + if (nodeOrToken === null) { + return; + } + if (TypeScript.isToken(nodeOrToken)) { + return; + } + for (var i = 0, n = TypeScript.childCount(nodeOrToken); i < n; i++) { + var child = TypeScript.childAt(nodeOrToken, i); + if (child !== null && !TypeScript.isShared(child)) { + pushElement(child, i); + moveToFirstChildIfList(); + return; + } + } + moveToNextSibling(); + } + function moveToNextSibling() { + while (!isFinished()) { + var currentPiece = pieces[currentPieceIndex]; + var parent = currentPiece.element.parent; + for (var i = currentPiece.indexInParent + 1, n = TypeScript.childCount(parent); i < n; i++) { + var sibling = TypeScript.childAt(parent, i); + if (sibling !== null && !TypeScript.isShared(sibling)) { + currentPiece.element = sibling; + currentPiece.indexInParent = i; + moveToFirstChildIfList(); + return; + } + } + currentPiece.element = null; + currentPiece.indexInParent = -1; + currentPieceIndex--; + } + } + function moveToFirstChildIfList() { + var element = pieces[currentPieceIndex].element; + if (TypeScript.isList(element) || TypeScript.isSeparatedList(element)) { + pushElement(TypeScript.childAt(element, 0), 0); + } + } + function pushElement(element, indexInParent) { + currentPieceIndex++; + if (currentPieceIndex === pieces.length) { + pieces.push(createSyntaxCursorPiece(element, indexInParent)); + } + else { + var piece = pieces[currentPieceIndex]; + piece.element = element; + piece.indexInParent = indexInParent; + } + } + function moveToFirstToken() { + while (!isFinished()) { + var element = pieces[currentPieceIndex].element; + if (TypeScript.isNode(element)) { + moveToFirstChild(); + continue; + } + return; + } + } + function currentToken() { + moveToFirstToken(); + var element = currentNodeOrToken(); + return element === null ? null : element; + } + return { + pieces: pieces, + clean: clean, + isFinished: isFinished, + moveToFirstChild: moveToFirstChild, + moveToFirstToken: moveToFirstToken, + moveToNextSibling: moveToNextSibling, + currentNodeOrToken: currentNodeOrToken, + currentNode: currentNode, + currentToken: currentToken, + pushElement: pushElement, + deepCopyFrom: deepCopyFrom + }; + } + var SetTokenFullStartWalker = (function (_super) { + __extends(SetTokenFullStartWalker, _super); + function SetTokenFullStartWalker() { + _super.apply(this, arguments); + } + SetTokenFullStartWalker.prototype.visitToken = function (token) { + var position = this.position; + token.setFullStart(position); + this.position = position + token.fullWidth(); + }; + return SetTokenFullStartWalker; + })(TypeScript.SyntaxWalker); + var setTokenFullStartWalker = new SetTokenFullStartWalker(); + function parse(oldSyntaxTree, textChangeRange, newText) { + TypeScript.Debug.assert(oldSyntaxTree.isConcrete(), "Can only incrementally parse a concrete syntax tree."); + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + return TypeScript.Parser.parseSource(createParserSource(oldSyntaxTree, textChangeRange, newText), oldSyntaxTree.isDeclaration()); + } + IncrementalParser.parse = parse; + })(TypeScript.IncrementalParser || (TypeScript.IncrementalParser = {})); + var IncrementalParser = TypeScript.IncrementalParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + var OutliningElementsCollector = (function (_super) { + __extends(OutliningElementsCollector, _super); + function OutliningElementsCollector() { + _super.call(this, OutliningElementsCollector.MaximumDepth); + this.inObjectLiteralExpression = false; + this.elements = []; + } + OutliningElementsCollector.prototype.visitClassDeclaration = function (node) { + this.addOutlineRange(node, node.openBraceToken, node.closeBraceToken); + _super.prototype.visitClassDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitInterfaceDeclaration = function (node) { + this.addOutlineRange(node, node.body.openBraceToken, node.body.closeBraceToken); + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitModuleDeclaration = function (node) { + this.addOutlineRange(node, node.openBraceToken, node.closeBraceToken); + _super.prototype.visitModuleDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitEnumDeclaration = function (node) { + this.addOutlineRange(node, node.openBraceToken, node.closeBraceToken); + _super.prototype.visitEnumDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitFunctionDeclaration = function (node) { + this.addOutlineRange(node, node.block, node.block); + _super.prototype.visitFunctionDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitFunctionExpression = function (node) { + this.addOutlineRange(node, node.block, node.block); + _super.prototype.visitFunctionExpression.call(this, node); + }; + OutliningElementsCollector.prototype.visitConstructorDeclaration = function (node) { + this.addOutlineRange(node, node.block, node.block); + _super.prototype.visitConstructorDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitMemberFunctionDeclaration = function (node) { + this.addOutlineRange(node, node.block, node.block); + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + OutliningElementsCollector.prototype.visitGetAccessor = function (node) { + if (!this.inObjectLiteralExpression) { + this.addOutlineRange(node, node.block, node.block); + } + _super.prototype.visitGetAccessor.call(this, node); + }; + OutliningElementsCollector.prototype.visitSetAccessor = function (node) { + if (!this.inObjectLiteralExpression) { + this.addOutlineRange(node, node.block, node.block); + } + _super.prototype.visitSetAccessor.call(this, node); + }; + OutliningElementsCollector.prototype.visitObjectLiteralExpression = function (node) { + var savedInObjectLiteralExpression = this.inObjectLiteralExpression; + this.inObjectLiteralExpression = true; + _super.prototype.visitObjectLiteralExpression.call(this, node); + this.inObjectLiteralExpression = savedInObjectLiteralExpression; + }; + OutliningElementsCollector.prototype.addOutlineRange = function (node, startElement, endElement) { + if (startElement && endElement && !TypeScript.isShared(startElement) && !TypeScript.isShared(endElement)) { + var start = TypeScript.start(startElement); + var end = TypeScript.end(endElement); + this.elements.push(TypeScript.TextSpan.fromBounds(start, end)); + } + }; + OutliningElementsCollector.collectElements = function (node) { + var collector = new OutliningElementsCollector(); + TypeScript.visitNodeOrToken(collector, node); + return collector.elements; + }; + OutliningElementsCollector.MaximumDepth = 10; + return OutliningElementsCollector; + })(TypeScript.DepthLimitedWalker); + Services.OutliningElementsCollector = OutliningElementsCollector; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + var GetScriptLexicalStructureWalker = (function (_super) { + __extends(GetScriptLexicalStructureWalker, _super); + function GetScriptLexicalStructureWalker(fileName) { + _super.call(this); + this.fileName = fileName; + this.nameStack = []; + this.kindStack = []; + this.parentScopes = []; + this.currentScope = this.createScope(); + } + GetScriptLexicalStructureWalker.prototype.createScope = function () { + return { + items: TypeScript.createIntrinsicsObject(), + childScopes: TypeScript.createIntrinsicsObject(), + childScopeNames: [], + itemNames: [] + }; + }; + GetScriptLexicalStructureWalker.prototype.pushNewContainerScope = function (containerName, kind) { + TypeScript.Debug.assert(containerName, "No scope name provided"); + var key = kind + "+" + containerName; + this.nameStack.push(containerName); + this.kindStack.push(kind); + var parentScope = this.currentScope; + this.parentScopes.push(parentScope); + var scope = ts.lookUp(parentScope.childScopes, key); + if (!scope) { + scope = this.createScope(); + parentScope.childScopes[key] = scope; + parentScope.childScopeNames.push(key); + } + this.currentScope = scope; + return parentScope; + }; + GetScriptLexicalStructureWalker.prototype.popScope = function () { + TypeScript.Debug.assert(this.parentScopes.length > 0, "No parent scopes to return to"); + this.currentScope = this.parentScopes.pop(); + this.kindStack.pop(); + this.nameStack.pop(); + }; + GetScriptLexicalStructureWalker.prototype.collectItems = function (items, scope) { + var _this = this; + if (scope === void 0) { scope = this.currentScope; } + scope.itemNames.forEach(function (item) { + items.push(scope.items[item]); + }); + scope.childScopeNames.forEach(function (childScope) { + _this.collectItems(items, scope.childScopes[childScope]); + }); + }; + GetScriptLexicalStructureWalker.getListsOfAllScriptLexicalStructure = function (items, fileName, unit) { + var visitor = new GetScriptLexicalStructureWalker(fileName); + TypeScript.visitNodeOrToken(visitor, unit); + visitor.collectItems(items); + }; + GetScriptLexicalStructureWalker.prototype.createItem = function (node, modifiers, kind, name) { + var key = kind + "+" + name; + if (ts.lookUp(this.currentScope.items, key) !== undefined) { + this.addAdditionalSpan(node, key); + return; + } + var item = { + name: name, + kind: kind, + matchKind: ts.MatchKind.exact, + fileName: this.fileName, + kindModifiers: this.getKindModifiers(modifiers), + minChar: TypeScript.start(node), + limChar: TypeScript.end(node), + containerName: this.nameStack.join("."), + containerKind: this.kindStack.length === 0 ? "" : TypeScript.ArrayUtilities.last(this.kindStack) + }; + this.currentScope.items[key] = item; + this.currentScope.itemNames.push(key); + }; + GetScriptLexicalStructureWalker.prototype.addAdditionalSpan = function (node, key) { + var item = ts.lookUp(this.currentScope.items, key); + TypeScript.Debug.assert(item !== undefined); + var start = TypeScript.start(node); + var span = { + minChar: start, + limChar: start + TypeScript.width(node) + }; + if (item.additionalSpans) { + item.additionalSpans.push(span); + } + else { + item.additionalSpans = [span]; + } + }; + GetScriptLexicalStructureWalker.prototype.getKindModifiers = function (modifiers) { + var result = []; + for (var i = 0, n = modifiers.length; i < n; i++) { + result.push(modifiers[i].text()); + } + return result.length > 0 ? result.join(',') : ts.ScriptElementKindModifier.none; + }; + GetScriptLexicalStructureWalker.prototype.visitModuleDeclaration = function (node) { + var names = this.getModuleNames(node); + this.visitModuleDeclarationWorker(node, names, 0); + }; + GetScriptLexicalStructureWalker.prototype.visitModuleDeclarationWorker = function (node, names, nameIndex) { + if (nameIndex === names.length) { + _super.prototype.visitModuleDeclaration.call(this, node); + } + else { + var name = names[nameIndex]; + var kind = ts.ScriptElementKind.moduleElement; + this.createItem(node, node.modifiers, kind, name); + this.pushNewContainerScope(name, kind); + this.visitModuleDeclarationWorker(node, names, nameIndex + 1); + this.popScope(); + } + }; + GetScriptLexicalStructureWalker.prototype.getModuleNames = function (node) { + var result = []; + if (node.stringLiteral) { + result.push(node.stringLiteral.text()); + } + else { + this.getModuleNamesHelper(node.name, result); + } + return result; + }; + GetScriptLexicalStructureWalker.prototype.getModuleNamesHelper = function (name, result) { + if (name.kind() === 121 /* QualifiedName */) { + var qualifiedName = name; + this.getModuleNamesHelper(qualifiedName.left, result); + result.push(qualifiedName.right.text()); + } + else { + result.push(name.text()); + } + }; + GetScriptLexicalStructureWalker.prototype.visitClassDeclaration = function (node) { + var name = node.identifier.text(); + var kind = ts.ScriptElementKind.classElement; + this.createItem(node, node.modifiers, kind, name); + this.pushNewContainerScope(name, kind); + _super.prototype.visitClassDeclaration.call(this, node); + this.popScope(); + }; + GetScriptLexicalStructureWalker.prototype.visitInterfaceDeclaration = function (node) { + var name = node.identifier.text(); + var kind = ts.ScriptElementKind.interfaceElement; + this.createItem(node, node.modifiers, kind, name); + this.pushNewContainerScope(name, kind); + _super.prototype.visitInterfaceDeclaration.call(this, node); + this.popScope(); + }; + GetScriptLexicalStructureWalker.prototype.visitObjectType = function (node) { + if (node.parent.kind() === 128 /* InterfaceDeclaration */) { + _super.prototype.visitObjectType.call(this, node); + } + }; + GetScriptLexicalStructureWalker.prototype.visitEnumDeclaration = function (node) { + var name = node.identifier.text(); + var kind = ts.ScriptElementKind.enumElement; + this.createItem(node, node.modifiers, kind, name); + this.pushNewContainerScope(name, kind); + _super.prototype.visitEnumDeclaration.call(this, node); + this.popScope(); + }; + GetScriptLexicalStructureWalker.prototype.visitConstructorDeclaration = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.constructorImplementationElement, "constructor"); + var parameters = node.callSignature.parameterList.parameters; + if (parameters) { + for (var i = 0, n = parameters.length; i < n; i++) { + var parameter = parameters[i]; + TypeScript.Debug.assert(parameter.kind() === 242 /* Parameter */); + if (TypeScript.SyntaxUtilities.containsToken(parameter.modifiers, 57 /* PublicKeyword */) || TypeScript.SyntaxUtilities.containsToken(parameter.modifiers, 55 /* PrivateKeyword */)) { + this.createItem(node, parameter.modifiers, ts.ScriptElementKind.memberVariableElement, parameter.identifier.text()); + } + } + } + }; + GetScriptLexicalStructureWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.createItem(node, node.modifiers, ts.ScriptElementKind.memberFunctionElement, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitGetAccessor = function (node) { + this.createItem(node, node.modifiers, ts.ScriptElementKind.memberGetAccessorElement, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitSetAccessor = function (node) { + this.createItem(node, node.modifiers, ts.ScriptElementKind.memberSetAccessorElement, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitVariableDeclarator = function (node) { + var modifiers = node.parent.kind() === 136 /* MemberVariableDeclaration */ ? node.parent.modifiers : TypeScript.Syntax.emptyList(); + var kind = node.parent.kind() === 136 /* MemberVariableDeclaration */ ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.variableElement; + this.createItem(node, modifiers, kind, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitIndexSignature = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.indexSignatureElement, "[]"); + }; + GetScriptLexicalStructureWalker.prototype.visitEnumElement = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.memberVariableElement, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitCallSignature = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.callSignatureElement, "()"); + }; + GetScriptLexicalStructureWalker.prototype.visitConstructSignature = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.constructSignatureElement, "new()"); + }; + GetScriptLexicalStructureWalker.prototype.visitMethodSignature = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.memberFunctionElement, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitPropertySignature = function (node) { + this.createItem(node, TypeScript.Syntax.emptyList(), ts.ScriptElementKind.memberVariableElement, node.propertyName.text()); + }; + GetScriptLexicalStructureWalker.prototype.visitFunctionDeclaration = function (node) { + if (TypeScript.width(node.identifier) > 0) { + this.createItem(node, node.modifiers, ts.ScriptElementKind.functionElement, node.identifier.text()); + } + }; + GetScriptLexicalStructureWalker.prototype.visitBlock = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitIfStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitExpressionStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitThrowStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitReturnStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitSwitchStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitWithStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitTryStatement = function (node) { + }; + GetScriptLexicalStructureWalker.prototype.visitLabeledStatement = function (node) { + }; + return GetScriptLexicalStructureWalker; + })(TypeScript.SyntaxWalker); + Services.GetScriptLexicalStructureWalker = GetScriptLexicalStructureWalker; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + var BraceMatcher = (function () { + function BraceMatcher() { + } + BraceMatcher.getMatchSpans = function (syntaxTree, position) { + var result = []; + var currentToken = TypeScript.findToken(syntaxTree.sourceUnit(), position); + BraceMatcher.getMatchingCloseBrace(currentToken, position, result); + BraceMatcher.getMatchingOpenBrace(currentToken, position, result); + return result; + }; + BraceMatcher.getMatchingCloseBrace = function (currentToken, position, result) { + if (TypeScript.start(currentToken) === position) { + var closingBraceKind = BraceMatcher.getMatchingCloseBraceTokenKind(currentToken); + if (closingBraceKind !== null) { + var parentElement = currentToken.parent; + var currentPosition = TypeScript.fullStart(currentToken.parent); + for (var i = 0, n = TypeScript.childCount(parentElement); i < n; i++) { + var element = TypeScript.childAt(parentElement, i); + if (element !== null && TypeScript.fullWidth(element) > 0) { + if (element.kind() === closingBraceKind) { + var range1 = new TypeScript.TextSpan(position, TypeScript.width(currentToken)); + var range2 = new TypeScript.TextSpan(currentPosition + TypeScript.leadingTriviaWidth(element), TypeScript.width(element)); + result.push(range1, range2); + break; + } + currentPosition += TypeScript.fullWidth(element); + } + } + } + } + }; + BraceMatcher.getMatchingOpenBrace = function (currentToken, position, result) { + if (currentToken.fullStart() === position) { + currentToken = TypeScript.previousToken(currentToken); + } + if (currentToken !== null && TypeScript.start(currentToken) === (position - 1)) { + var openBraceKind = BraceMatcher.getMatchingOpenBraceTokenKind(currentToken); + if (openBraceKind !== null) { + var parentElement = currentToken.parent; + var currentPosition = TypeScript.fullStart(currentToken.parent) + TypeScript.fullWidth(parentElement); + for (var i = TypeScript.childCount(parentElement) - 1; i >= 0; i--) { + var element = TypeScript.childAt(parentElement, i); + if (element !== null && TypeScript.fullWidth(element) > 0) { + if (element.kind() === openBraceKind) { + var range1 = new TypeScript.TextSpan(position - 1, TypeScript.width(currentToken)); + var range2 = new TypeScript.TextSpan(currentPosition - TypeScript.lastToken(element).trailingTriviaWidth() - TypeScript.width(element), TypeScript.width(element)); + result.push(range1, range2); + break; + } + currentPosition -= TypeScript.fullWidth(element); + } + } + } + } + }; + BraceMatcher.getMatchingCloseBraceTokenKind = function (positionedElement) { + var element = positionedElement !== null && positionedElement; + switch (element.kind()) { + case 70 /* OpenBraceToken */: + return 71 /* CloseBraceToken */; + case 72 /* OpenParenToken */: + return 73 /* CloseParenToken */; + case 74 /* OpenBracketToken */: + return 75 /* CloseBracketToken */; + case 80 /* LessThanToken */: + return TypeScript.SyntaxUtilities.isAngleBracket(positionedElement) ? 81 /* GreaterThanToken */ : null; + } + return null; + }; + BraceMatcher.getMatchingOpenBraceTokenKind = function (positionedElement) { + var element = positionedElement !== null && positionedElement; + switch (element.kind()) { + case 71 /* CloseBraceToken */: + return 70 /* OpenBraceToken */; + case 73 /* CloseParenToken */: + return 72 /* OpenParenToken */; + case 75 /* CloseBracketToken */: + return 74 /* OpenBracketToken */; + case 81 /* GreaterThanToken */: + return TypeScript.SyntaxUtilities.isAngleBracket(positionedElement) ? 80 /* LessThanToken */ : null; + } + return null; + }; + return BraceMatcher; + })(); + Services.BraceMatcher = BraceMatcher; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Breakpoints) { + function createBreakpointSpanInfo(parentElement) { + var childElements = []; + for (var _i = 1; _i < arguments.length; _i++) { + childElements[_i - 1] = arguments[_i]; + } + if (!parentElement) { + return null; + } + if (childElements.length == 0) { + return { + minChar: TypeScript.start(parentElement), + limChar: TypeScript.end(parentElement) + }; + } + var start; + var end; + for (var i = 0; i < childElements.length; i++) { + var element = childElements[i]; + if (element && !TypeScript.isShared(element)) { + if (start == undefined) { + start = TypeScript.start(element); + } + end = TypeScript.end(element); + } + } + return { + minChar: start, + limChar: end + }; + } + function createBreakpointSpanInfoWithLimChar(startElement, limChar) { + return { + minChar: TypeScript.start(startElement), + limChar: limChar + }; + } + var BreakpointResolver = (function () { + function BreakpointResolver(posLine, lineMap) { + this.posLine = posLine; + this.lineMap = lineMap; + } + BreakpointResolver.prototype.breakpointSpanOfToken = function (positionedToken) { + switch (positionedToken.kind()) { + case 70 /* OpenBraceToken */: + return this.breakpointSpanOfOpenBrace(positionedToken); + case 71 /* CloseBraceToken */: + return this.breakpointSpanOfCloseBrace(positionedToken); + case 79 /* CommaToken */: + return this.breakpointSpanOfComma(positionedToken); + case 78 /* SemicolonToken */: + case 10 /* EndOfFileToken */: + return this.breakpointSpanIfStartsOnSameLine(TypeScript.previousToken(positionedToken)); + case 73 /* CloseParenToken */: + return this.breakpointSpanOfCloseParen(positionedToken); + case 22 /* DoKeyword */: + var parentElement = positionedToken.parent; + if (parentElement && parentElement.kind() == 161 /* DoStatement */) { + return this.breakpointSpanIfStartsOnSameLine(TypeScript.nextToken(positionedToken)); + } + break; + } + return this.breakpointSpanOfContainingNode(positionedToken); + }; + BreakpointResolver.prototype.breakpointSpanOfOpenBrace = function (openBraceToken) { + var container = TypeScript.Syntax.containingNode(openBraceToken); + if (container) { + var originalContainer = container; + if (container && container.kind() == 146 /* Block */) { + container = TypeScript.Syntax.containingNode(container); + if (!container) { + container = originalContainer; + } + } + switch (container.kind()) { + case 146 /* Block */: + if (!this.canHaveBreakpointInBlock(container)) { + return null; + } + return this.breakpointSpanOfFirstStatementInBlock(container); + break; + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 222 /* FunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + if (!this.canHaveBreakpointInDeclaration(container)) { + return null; + } + if (this.posLine != this.lineMap.getLineNumberFromPosition(TypeScript.start(container))) { + return this.breakpointSpanOfFirstChildOfSyntaxList(this.getSyntaxListOfDeclarationWithElements(container)); + } + else { + return this.breakpointSpanOf(container); + } + case 132 /* EnumDeclaration */: + if (!this.canHaveBreakpointInDeclaration(container)) { + return null; + } + if (this.posLine != this.lineMap.getLineNumberFromPosition(TypeScript.start(container))) { + return this.breakpointSpanOfFirstEnumElement(container); + } + else { + return this.breakpointSpanOf(container); + } + case 147 /* IfStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 236 /* CatchClause */: + if (this.posLine != this.lineMap.getLineNumberFromPosition(TypeScript.start(container))) { + return this.breakpointSpanOfFirstStatementInBlock(originalContainer); + } + else { + return this.breakpointSpanOf(container); + } + case 161 /* DoStatement */: + return this.breakpointSpanOfFirstStatementInBlock(originalContainer); + case 154 /* ForStatement */: + if (this.posLine != this.lineMap.getLineNumberFromPosition(TypeScript.start(container))) { + return this.breakpointSpanOfFirstStatementInBlock(originalContainer); + } + else { + return this.breakpointSpanOf(TypeScript.previousToken(openBraceToken)); + } + case 235 /* ElseClause */: + case 233 /* CaseSwitchClause */: + case 234 /* DefaultSwitchClause */: + case 163 /* WithStatement */: + case 159 /* TryStatement */: + case 237 /* FinallyClause */: + return this.breakpointSpanOfFirstStatementInBlock(originalContainer); + case 151 /* SwitchStatement */: + if (this.posLine != this.lineMap.getLineNumberFromPosition(TypeScript.start(container))) { + return this.breakpointSpanOfFirstStatementOfFirstCaseClause(container); + } + else { + return this.breakpointSpanOf(container); + } + } + } + return null; + }; + BreakpointResolver.prototype.breakpointSpanOfCloseBrace = function (closeBraceToken) { + var container = TypeScript.Syntax.containingNode(closeBraceToken); + if (container) { + var originalContainer = container; + if (container.kind() == 146 /* Block */) { + container = TypeScript.Syntax.containingNode(container); + if (!container) { + container = originalContainer; + } + } + switch (container.kind()) { + case 146 /* Block */: + if (!this.canHaveBreakpointInBlock(container)) { + return null; + } + return this.breakpointSpanOfLastStatementInBlock(container); + break; + case 130 /* ModuleDeclaration */: + if (!this.canHaveBreakpointInDeclaration(container)) { + return null; + } + var moduleSyntax = container; + if (moduleSyntax.moduleElements && moduleSyntax.moduleElements.length > 0) { + return createBreakpointSpanInfo(closeBraceToken); + } + else { + return null; + } + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 222 /* FunctionExpression */: + if (!this.canHaveBreakpointInDeclaration(container)) { + return null; + } + return createBreakpointSpanInfo(closeBraceToken); + case 132 /* EnumDeclaration */: + if (!this.canHaveBreakpointInDeclaration(container)) { + return null; + } + return createBreakpointSpanInfo(closeBraceToken); + case 147 /* IfStatement */: + case 235 /* ElseClause */: + case 155 /* ForInStatement */: + case 154 /* ForStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + case 233 /* CaseSwitchClause */: + case 234 /* DefaultSwitchClause */: + case 163 /* WithStatement */: + case 159 /* TryStatement */: + case 236 /* CatchClause */: + case 237 /* FinallyClause */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + return this.breakpointSpanOfLastStatementInBlock(originalContainer); + case 151 /* SwitchStatement */: + return this.breakpointSpanOfLastStatementOfLastCaseClause(container); + } + } + return null; + }; + BreakpointResolver.prototype.breakpointSpanOfComma = function (commaToken) { + var commaParent = commaToken.parent; + if (TypeScript.isSeparatedList(commaParent)) { + var grandParent = commaParent.parent; + if (grandParent) { + switch (grandParent.kind()) { + case 224 /* VariableDeclaration */: + case 132 /* EnumDeclaration */: + case 227 /* ParameterList */: + var index = TypeScript.Syntax.childIndex(commaParent, commaToken); + if (index > 0) { + var child = TypeScript.childAt(commaParent, index - 1); + return this.breakpointSpanOf(child); + } + if (grandParent.kind() == 132 /* EnumDeclaration */) { + return null; + } + break; + } + } + } + return this.breakpointSpanOfContainingNode(commaToken); + }; + BreakpointResolver.prototype.breakpointSpanOfCloseParen = function (closeParenToken) { + var closeParenParent = closeParenToken.parent; + if (closeParenParent) { + switch (closeParenParent.kind()) { + case 154 /* ForStatement */: + case 227 /* ParameterList */: + return this.breakpointSpanOf(TypeScript.previousToken(closeParenToken)); + } + } + return this.breakpointSpanOfContainingNode(closeParenToken); + }; + BreakpointResolver.prototype.canHaveBreakpointInBlock = function (blockNode) { + if (!blockNode || TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(blockNode)) { + return false; + } + var blockSyntax = blockNode; + return blockSyntax.statements && blockSyntax.statements.length != 0; + }; + BreakpointResolver.prototype.breakpointSpanOfFirstStatementInBlock = function (blockNode) { + if (!blockNode) { + return null; + } + var blockSyntax = blockNode; + var statementsNode = blockSyntax.statements; + if (!statementsNode || statementsNode.length == 0) { + return null; + } + var firstStatement = TypeScript.childAt(statementsNode, 0); + if (firstStatement && firstStatement.kind() == 146 /* Block */) { + if (this.canHaveBreakpointInBlock(firstStatement)) { + return this.breakpointSpanOfFirstStatementInBlock(firstStatement); + } + return null; + } + else { + return this.breakpointSpanOf(firstStatement); + } + }; + BreakpointResolver.prototype.breakpointSpanOfLastStatementInBlock = function (blockNode) { + if (!blockNode) { + return null; + } + var blockSyntax = blockNode; + var statementsNode = blockSyntax.statements; + if (!statementsNode || statementsNode.length == 0) { + return null; + } + var lastStatement = TypeScript.childAt(statementsNode, statementsNode.length - 1); + if (lastStatement && lastStatement.kind() == 146 /* Block */) { + if (this.canHaveBreakpointInBlock(lastStatement)) { + return this.breakpointSpanOfLastStatementInBlock(lastStatement); + } + return null; + } + else { + return this.breakpointSpanOf(lastStatement); + } + }; + BreakpointResolver.prototype.breakpointSpanOfFirstChildOfSyntaxList = function (positionedList) { + if (!positionedList) { + return null; + } + var listSyntax = positionedList; + if (listSyntax.length == 0) { + return null; + } + var firstStatement = TypeScript.childAt(positionedList, 0); + if (firstStatement && firstStatement.kind() == 146 /* Block */) { + if (this.canHaveBreakpointInBlock(firstStatement)) { + return this.breakpointSpanOfFirstStatementInBlock(firstStatement); + } + return null; + } + else { + return this.breakpointSpanOf(firstStatement); + } + }; + BreakpointResolver.prototype.breakpointSpanOfLastChildOfSyntaxList = function (positionedList) { + if (!positionedList) { + return null; + } + var listSyntax = positionedList; + if (listSyntax.length == 0) { + return null; + } + var lastStatement = TypeScript.childAt(positionedList, 0); + if (lastStatement && lastStatement.kind() == 146 /* Block */) { + if (this.canHaveBreakpointInBlock(lastStatement)) { + return this.breakpointSpanOfLastStatementInBlock(lastStatement); + } + return null; + } + else { + return this.breakpointSpanOf(lastStatement); + } + }; + BreakpointResolver.prototype.breakpointSpanOfNode = function (positionedNode) { + var node = positionedNode; + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 222 /* FunctionExpression */: + return this.breakpointSpanOfDeclarationWithElements(positionedNode); + case 225 /* VariableDeclarator */: + return this.breakpointSpanOfVariableDeclarator(positionedNode); + case 224 /* VariableDeclaration */: + return this.breakpointSpanOfVariableDeclaration(positionedNode); + case 148 /* VariableStatement */: + return this.breakpointSpanOfVariableStatement(positionedNode); + case 242 /* Parameter */: + return this.breakpointSpanOfParameter(positionedNode); + case 136 /* MemberVariableDeclaration */: + return this.breakpointSpanOfMemberVariableDeclaration(positionedNode); + case 133 /* ImportDeclaration */: + return this.breakpointSpanOfImportDeclaration(positionedNode); + case 132 /* EnumDeclaration */: + return this.breakpointSpanOfEnumDeclaration(positionedNode); + case 243 /* EnumElement */: + return this.breakpointSpanOfEnumElement(positionedNode); + case 147 /* IfStatement */: + return this.breakpointSpanOfIfStatement(positionedNode); + case 235 /* ElseClause */: + return this.breakpointSpanOfElseClause(positionedNode); + case 155 /* ForInStatement */: + return this.breakpointSpanOfForInStatement(positionedNode); + case 154 /* ForStatement */: + return this.breakpointSpanOfForStatement(positionedNode); + case 158 /* WhileStatement */: + return this.breakpointSpanOfWhileStatement(positionedNode); + case 161 /* DoStatement */: + return this.breakpointSpanOfDoStatement(positionedNode); + case 151 /* SwitchStatement */: + return this.breakpointSpanOfSwitchStatement(positionedNode); + case 233 /* CaseSwitchClause */: + return this.breakpointSpanOfCaseSwitchClause(positionedNode); + case 234 /* DefaultSwitchClause */: + return this.breakpointSpanOfDefaultSwitchClause(positionedNode); + case 163 /* WithStatement */: + return this.breakpointSpanOfWithStatement(positionedNode); + case 159 /* TryStatement */: + return this.breakpointSpanOfTryStatement(positionedNode); + case 236 /* CatchClause */: + return this.breakpointSpanOfCatchClause(positionedNode); + case 237 /* FinallyClause */: + return this.breakpointSpanOfFinallyClause(positionedNode); + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.breakpointSpanOfParenthesizedArrowFunctionExpression(positionedNode); + case 219 /* SimpleArrowFunctionExpression */: + return this.breakpointSpanOfSimpleArrowFunctionExpression(positionedNode); + default: + if (TypeScript.SyntaxUtilities.isStatement(node)) { + return this.breakpointSpanOfStatement(positionedNode); + } + else { + return this.breakpointOfExpression(positionedNode); + } + } + }; + BreakpointResolver.prototype.isExpressionOfArrowExpressions = function (expression) { + if (!expression) { + return false; + } + var expressionParent = expression.parent; + if (expressionParent) { + if (expressionParent.kind() == 218 /* ParenthesizedArrowFunctionExpression */) { + var parenthesizedArrowExpression = expressionParent; + var expressionOfParenthesizedArrowExpression = parenthesizedArrowExpression.expression; + return expressionOfParenthesizedArrowExpression == expression; + } + else if (expressionParent.kind() == 219 /* SimpleArrowFunctionExpression */) { + var simpleArrowExpression = expressionParent; + var expressionOfSimpleArrowExpression = simpleArrowExpression.expression; + return expressionOfSimpleArrowExpression == expression; + } + else if (expressionParent.kind() == 173 /* CommaExpression */) { + return this.isExpressionOfArrowExpressions(expressionParent); + } + } + return false; + }; + BreakpointResolver.prototype.isInitializerOfForStatement = function (expressionNode) { + if (!expressionNode) { + return false; + } + var expressionParent = expressionNode.parent; + if (expressionParent && expressionParent.kind() == 154 /* ForStatement */) { + var expression = expressionNode; + var forStatement = expressionParent; + var initializer = forStatement.initializer; + return initializer === expression; + } + else if (expressionParent && expressionParent.kind() == 173 /* CommaExpression */) { + return this.isInitializerOfForStatement(expressionParent); + } + return false; + }; + BreakpointResolver.prototype.isConditionOfForStatement = function (expressionNode) { + if (!expressionNode) { + return false; + } + var expressionParent = expressionNode.parent; + if (expressionParent && expressionParent.kind() == 154 /* ForStatement */) { + var expression = expressionNode; + var forStatement = expressionParent; + var condition = forStatement.condition; + return condition === expression; + } + else if (expressionParent && expressionParent.kind() == 173 /* CommaExpression */) { + return this.isConditionOfForStatement(expressionParent); + } + return false; + }; + BreakpointResolver.prototype.isIncrememtorOfForStatement = function (expressionNode) { + if (!expressionNode) { + return false; + } + var expressionParent = expressionNode.parent; + if (expressionParent && expressionParent.kind() == 154 /* ForStatement */) { + var expression = expressionNode; + var forStatement = expressionParent; + var incrementor = forStatement.incrementor; + return incrementor === expression; + } + else if (expressionParent && expressionParent.kind() == 173 /* CommaExpression */) { + return this.isIncrememtorOfForStatement(expressionParent); + } + return false; + }; + BreakpointResolver.prototype.breakpointOfLeftOfCommaExpression = function (commaExpressionNode) { + var commaExpression = commaExpressionNode; + return this.breakpointSpanOf(commaExpression.left); + }; + BreakpointResolver.prototype.breakpointOfExpression = function (expressionNode) { + if (this.isInitializerOfForStatement(expressionNode) || this.isConditionOfForStatement(expressionNode) || this.isIncrememtorOfForStatement(expressionNode)) { + if (expressionNode.kind() == 173 /* CommaExpression */) { + return this.breakpointOfLeftOfCommaExpression(expressionNode); + } + return createBreakpointSpanInfo(expressionNode); + } + if (this.isExpressionOfArrowExpressions(expressionNode)) { + if (expressionNode.kind() == 173 /* CommaExpression */) { + return this.breakpointOfLeftOfCommaExpression(expressionNode); + } + return createBreakpointSpanInfo(expressionNode); + } + if (expressionNode.kind() == 134 /* ExportAssignment */) { + var exportAssignmentSyntax = expressionNode; + return createBreakpointSpanInfo(expressionNode, exportAssignmentSyntax.exportKeyword, exportAssignmentSyntax.equalsToken, exportAssignmentSyntax.identifier); + } + return this.breakpointSpanOfContainingNode(expressionNode); + }; + BreakpointResolver.prototype.breakpointSpanOfStatement = function (statementNode) { + var statement = statementNode; + if (statement.kind() == 156 /* EmptyStatement */) { + return null; + } + var containingNode = TypeScript.Syntax.containingNode(statementNode); + if (TypeScript.SyntaxUtilities.isStatement(containingNode)) { + var useNodeForBreakpoint = false; + switch (containingNode.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 146 /* Block */: + case 147 /* IfStatement */: + case 235 /* ElseClause */: + case 155 /* ForInStatement */: + case 154 /* ForStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + case 151 /* SwitchStatement */: + case 233 /* CaseSwitchClause */: + case 234 /* DefaultSwitchClause */: + case 163 /* WithStatement */: + case 159 /* TryStatement */: + case 236 /* CatchClause */: + case 237 /* FinallyClause */: + case 146 /* Block */: + useNodeForBreakpoint = true; + } + if (!useNodeForBreakpoint) { + return this.breakpointSpanOfContainingNode(statementNode); + } + } + switch (statement.kind()) { + case 149 /* ExpressionStatement */: + var expressionSyntax = statement; + return createBreakpointSpanInfo(expressionSyntax.expression); + case 150 /* ReturnStatement */: + var returnStatementSyntax = statement; + return createBreakpointSpanInfo(statementNode, returnStatementSyntax.returnKeyword, returnStatementSyntax.expression); + case 157 /* ThrowStatement */: + var throwStatementSyntax = statement; + return createBreakpointSpanInfo(statementNode, throwStatementSyntax.throwKeyword, throwStatementSyntax.expression); + case 152 /* BreakStatement */: + var breakStatementSyntax = statement; + return createBreakpointSpanInfo(statementNode, breakStatementSyntax.breakKeyword, breakStatementSyntax.identifier); + case 153 /* ContinueStatement */: + var continueStatementSyntax = statement; + return createBreakpointSpanInfo(statementNode, continueStatementSyntax.continueKeyword, continueStatementSyntax.identifier); + case 162 /* DebuggerStatement */: + var debuggerStatementSyntax = statement; + return createBreakpointSpanInfo(debuggerStatementSyntax.debuggerKeyword); + case 160 /* LabeledStatement */: + var labeledStatementSyntax = statement; + return this.breakpointSpanOf(labeledStatementSyntax.statement); + } + return null; + }; + BreakpointResolver.prototype.getSyntaxListOfDeclarationWithElements = function (positionedNode) { + var node = positionedNode; + var elementsList; + var block; + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + elementsList = node.moduleElements; + break; + case 131 /* ClassDeclaration */: + elementsList = node.classElements; + break; + case 129 /* FunctionDeclaration */: + block = node.block; + break; + case 137 /* ConstructorDeclaration */: + block = node.block; + break; + case 135 /* MemberFunctionDeclaration */: + block = node.block; + break; + case 139 /* GetAccessor */: + block = node.block; + break; + case 140 /* SetAccessor */: + block = node.block; + break; + case 222 /* FunctionExpression */: + block = node.block; + break; + case 218 /* ParenthesizedArrowFunctionExpression */: + block = node.block; + break; + case 219 /* SimpleArrowFunctionExpression */: + block = node.block; + break; + default: + throw TypeScript.Errors.argument('positionNode', 'unknown node kind in getSyntaxListOfDeclarationWithElements'); + } + var parentElement = positionedNode; + if (block) { + parentElement = block; + elementsList = block.statements; + } + return elementsList; + }; + BreakpointResolver.prototype.canHaveBreakpointInDeclaration = function (positionedNode) { + return positionedNode && !TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(positionedNode); + }; + BreakpointResolver.prototype.breakpointSpanOfDeclarationWithElements = function (positionedNode) { + if (!this.canHaveBreakpointInDeclaration(positionedNode)) { + return null; + } + var node = positionedNode; + var moduleSyntax = positionedNode; + if ((TypeScript.SyntaxUtilities.isModuleElement(node) && TypeScript.Syntax.containingNode(positionedNode).kind() != 120 /* SourceUnit */) || TypeScript.SyntaxUtilities.isClassElement(node) || (moduleSyntax.kind() == 130 /* ModuleDeclaration */ && moduleSyntax.name && moduleSyntax.name.kind() == 121 /* QualifiedName */)) { + return createBreakpointSpanInfo(positionedNode); + } + else { + return this.breakpointSpanOfFirstChildOfSyntaxList(this.getSyntaxListOfDeclarationWithElements(positionedNode)); + } + }; + BreakpointResolver.prototype.canHaveBreakpointInVariableDeclarator = function (varDeclaratorNode) { + if (!varDeclaratorNode || TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(varDeclaratorNode)) { + return false; + } + var varDeclaratorSyntax = varDeclaratorNode; + return !!varDeclaratorSyntax.equalsValueClause; + }; + BreakpointResolver.prototype.breakpointSpanOfVariableDeclarator = function (varDeclaratorNode) { + if (!this.canHaveBreakpointInVariableDeclarator(varDeclaratorNode)) { + return null; + } + var container = TypeScript.Syntax.containingNode(varDeclaratorNode); + if (container && container.kind() == 224 /* VariableDeclaration */) { + var parentDeclaratorsList = varDeclaratorNode.parent; + if (parentDeclaratorsList && TypeScript.childAt(parentDeclaratorsList, 0) == varDeclaratorNode) { + return this.breakpointSpanOfVariableDeclaration(container); + } + if (this.canHaveBreakpointInVariableDeclarator(varDeclaratorNode)) { + return createBreakpointSpanInfo(varDeclaratorNode); + } + else { + return null; + } + } + else if (container) { + return this.breakpointSpanOfMemberVariableDeclaration(container); + } + return null; + }; + BreakpointResolver.prototype.canHaveBreakpointInVariableDeclaration = function (varDeclarationNode) { + if (!varDeclarationNode || TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(varDeclarationNode)) { + return false; + } + var varDeclarationSyntax = varDeclarationNode; + var containerChildren = varDeclarationSyntax.variableDeclarators; + if (!containerChildren || TypeScript.childCount(containerChildren) == 0) { + return false; + } + var child = TypeScript.childAt(containerChildren, 0); + if (TypeScript.isNode(child)) { + return this.canHaveBreakpointInVariableDeclarator(child); + } + return false; + }; + BreakpointResolver.prototype.breakpointSpanOfVariableDeclaration = function (varDeclarationNode) { + if (!this.canHaveBreakpointInDeclaration(varDeclarationNode)) { + return null; + } + var container = TypeScript.Syntax.containingNode(varDeclarationNode); + var varDeclarationSyntax = varDeclarationNode; + var varDeclarators = varDeclarationSyntax.variableDeclarators; + var varDeclaratorsCount = TypeScript.childCount(varDeclarators); + if (container && container.kind() == 148 /* VariableStatement */) { + return this.breakpointSpanOfVariableStatement(container); + } + if (this.canHaveBreakpointInVariableDeclaration(varDeclarationNode)) { + return createBreakpointSpanInfoWithLimChar(varDeclarationNode, TypeScript.end(TypeScript.childAt(varDeclarators, 0))); + } + else { + return null; + } + }; + BreakpointResolver.prototype.canHaveBreakpointInVariableStatement = function (varStatementNode) { + if (!varStatementNode || TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(varStatementNode)) { + return false; + } + var variableStatement = varStatementNode; + return this.canHaveBreakpointInVariableDeclaration(variableStatement.variableDeclaration); + }; + BreakpointResolver.prototype.breakpointSpanOfVariableStatement = function (varStatementNode) { + if (!this.canHaveBreakpointInVariableStatement(varStatementNode)) { + return null; + } + var variableStatement = varStatementNode; + var variableDeclaration = variableStatement.variableDeclaration; + var varDeclarationSyntax = variableDeclaration; + var varDeclarators = varDeclarationSyntax.variableDeclarators; + return createBreakpointSpanInfoWithLimChar(varStatementNode, TypeScript.end(TypeScript.childAt(varDeclarators, 0))); + }; + BreakpointResolver.prototype.breakpointSpanOfParameter = function (parameterNode) { + if (parameterNode.parent.kind() === 219 /* SimpleArrowFunctionExpression */) { + return this.breakpointSpanOfNode(parameterNode.parent); + } + if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(parameterNode)) { + return null; + } + var parameterSyntax = parameterNode; + if (parameterSyntax.dotDotDotToken || parameterSyntax.equalsValueClause || parameterSyntax.modifiers.length > 0) { + return createBreakpointSpanInfo(parameterNode); + } + else { + return null; + } + }; + BreakpointResolver.prototype.breakpointSpanOfMemberVariableDeclaration = function (memberVarDeclarationNode) { + if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(memberVarDeclarationNode)) { + return null; + } + var memberVariableDeclaration = memberVarDeclarationNode; + if (this.canHaveBreakpointInVariableDeclarator(memberVariableDeclaration.variableDeclarator)) { + return createBreakpointSpanInfo(memberVarDeclarationNode, memberVariableDeclaration.modifiers, memberVariableDeclaration.variableDeclarator); + } + else { + return null; + } + }; + BreakpointResolver.prototype.breakpointSpanOfImportDeclaration = function (importDeclarationNode) { + if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(importDeclarationNode)) { + return null; + } + var importSyntax = importDeclarationNode; + return createBreakpointSpanInfo(importDeclarationNode, importSyntax.modifiers, importSyntax.importKeyword, importSyntax.identifier, importSyntax.equalsToken, importSyntax.moduleReference); + }; + BreakpointResolver.prototype.breakpointSpanOfEnumDeclaration = function (enumDeclarationNode) { + if (!this.canHaveBreakpointInDeclaration(enumDeclarationNode)) { + return null; + } + return createBreakpointSpanInfo(enumDeclarationNode); + }; + BreakpointResolver.prototype.breakpointSpanOfFirstEnumElement = function (enumDeclarationNode) { + var enumDeclarationSyntax = enumDeclarationNode; + var enumElements = enumDeclarationSyntax.enumElements; + if (enumElements && TypeScript.childCount(enumElements)) { + return this.breakpointSpanOf(TypeScript.childAt(enumElements, 0)); + } + return null; + }; + BreakpointResolver.prototype.breakpointSpanOfEnumElement = function (enumElementNode) { + if (TypeScript.SyntaxUtilities.isAmbientDeclarationSyntax(enumElementNode)) { + return null; + } + return createBreakpointSpanInfo(enumElementNode); + }; + BreakpointResolver.prototype.breakpointSpanOfIfStatement = function (ifStatementNode) { + var ifStatement = ifStatementNode; + return createBreakpointSpanInfo(ifStatementNode, ifStatement.ifKeyword, ifStatement.openParenToken, ifStatement.condition, ifStatement.closeParenToken); + }; + BreakpointResolver.prototype.breakpointSpanOfElseClause = function (elseClauseNode) { + var elseClause = elseClauseNode; + return this.breakpointSpanOf(elseClause.statement); + }; + BreakpointResolver.prototype.breakpointSpanOfForInStatement = function (forInStatementNode) { + var forInStatement = forInStatementNode; + return createBreakpointSpanInfo(forInStatementNode, forInStatement.forKeyword, forInStatement.openParenToken, forInStatement.variableDeclaration, forInStatement.left, forInStatement.inKeyword, forInStatement.expression, forInStatement.closeParenToken); + }; + BreakpointResolver.prototype.breakpointSpanOfForStatement = function (forStatementNode) { + var forStatement = forStatementNode; + return this.breakpointSpanOf(forStatement.variableDeclaration ? forStatement.variableDeclaration : forStatement.initializer); + }; + BreakpointResolver.prototype.breakpointSpanOfWhileStatement = function (whileStatementNode) { + var whileStatement = whileStatementNode; + return createBreakpointSpanInfo(whileStatementNode, whileStatement.whileKeyword, whileStatement.openParenToken, whileStatement.condition, whileStatement.closeParenToken); + }; + BreakpointResolver.prototype.breakpointSpanOfDoStatement = function (doStatementNode) { + var doStatement = doStatementNode; + return createBreakpointSpanInfo(doStatementNode, doStatement.whileKeyword, doStatement.openParenToken, doStatement.condition, doStatement.closeParenToken); + }; + BreakpointResolver.prototype.breakpointSpanOfSwitchStatement = function (switchStatementNode) { + var switchStatement = switchStatementNode; + return createBreakpointSpanInfo(switchStatementNode, switchStatement.switchKeyword, switchStatement.openParenToken, switchStatement.expression, switchStatement.closeParenToken); + }; + BreakpointResolver.prototype.breakpointSpanOfFirstStatementOfFirstCaseClause = function (switchStatementNode) { + var switchStatement = switchStatementNode; + if (switchStatement.switchClauses && switchStatement.switchClauses.length == 0) { + return null; + } + var switchClauses = switchStatement.switchClauses; + if (switchClauses.length == 0) { + return null; + } + var firstCaseClause = switchClauses[0]; + var statements = firstCaseClause.statements; + return this.breakpointSpanOfFirstChildOfSyntaxList(statements); + }; + BreakpointResolver.prototype.breakpointSpanOfLastStatementOfLastCaseClause = function (switchStatementNode) { + var switchStatement = switchStatementNode; + if (switchStatement.switchClauses && switchStatement.switchClauses.length == 0) { + return null; + } + var switchClauses = switchStatement.switchClauses; + if (switchClauses.length == 0) { + return null; + } + var lastClauseNode = switchClauses[switchClauses.length - 1]; + var statements = lastClauseNode.statements; + return this.breakpointSpanOfLastChildOfSyntaxList(statements); + }; + BreakpointResolver.prototype.breakpointSpanOfCaseSwitchClause = function (caseClauseNode) { + var caseSwitchClause = caseClauseNode; + return this.breakpointSpanOfFirstChildOfSyntaxList(caseSwitchClause.statements); + }; + BreakpointResolver.prototype.breakpointSpanOfDefaultSwitchClause = function (defaultSwithClauseNode) { + var defaultSwitchClause = defaultSwithClauseNode; + return this.breakpointSpanOfFirstChildOfSyntaxList(defaultSwitchClause.statements); + }; + BreakpointResolver.prototype.breakpointSpanOfWithStatement = function (withStatementNode) { + var withStatement = withStatementNode; + return this.breakpointSpanOf(withStatement.statement); + }; + BreakpointResolver.prototype.breakpointSpanOfTryStatement = function (tryStatementNode) { + var tryStatement = tryStatementNode; + return this.breakpointSpanOfFirstStatementInBlock(tryStatement.block); + }; + BreakpointResolver.prototype.breakpointSpanOfCatchClause = function (catchClauseNode) { + var catchClause = catchClauseNode; + return createBreakpointSpanInfo(catchClauseNode, catchClause.catchKeyword, catchClause.openParenToken, catchClause.identifier, catchClause.typeAnnotation, catchClause.closeParenToken); + }; + BreakpointResolver.prototype.breakpointSpanOfFinallyClause = function (finallyClauseNode) { + var finallyClause = finallyClauseNode; + return this.breakpointSpanOfFirstStatementInBlock(finallyClause.block); + }; + BreakpointResolver.prototype.breakpointSpanOfParenthesizedArrowFunctionExpression = function (arrowFunctionExpression) { + if (arrowFunctionExpression.block) { + return this.breakpointSpanOfFirstStatementInBlock(arrowFunctionExpression.block); + } + else { + return this.breakpointSpanOf(arrowFunctionExpression.expression); + } + }; + BreakpointResolver.prototype.breakpointSpanOfSimpleArrowFunctionExpression = function (arrowFunctionExpression) { + if (arrowFunctionExpression.block) { + return this.breakpointSpanOfFirstStatementInBlock(arrowFunctionExpression.block); + } + else { + return this.breakpointSpanOf(arrowFunctionExpression.expression); + } + }; + BreakpointResolver.prototype.breakpointSpanOfContainingNode = function (positionedElement) { + var current = positionedElement.parent; + while (!TypeScript.isNode(current)) { + current = current.parent; + } + return this.breakpointSpanOf(current); + }; + BreakpointResolver.prototype.breakpointSpanIfStartsOnSameLine = function (positionedElement) { + if (positionedElement && this.posLine == this.lineMap.getLineNumberFromPosition(TypeScript.start(positionedElement))) { + return this.breakpointSpanOf(positionedElement); + } + return null; + }; + BreakpointResolver.prototype.breakpointSpanOf = function (positionedElement) { + if (!positionedElement) { + return null; + } + for (var containingNode = TypeScript.Syntax.containingNode(positionedElement); containingNode != null; containingNode = TypeScript.Syntax.containingNode(containingNode)) { + if (containingNode.kind() == 244 /* TypeAnnotation */) { + return this.breakpointSpanIfStartsOnSameLine(containingNode); + } + } + var element = positionedElement; + if (TypeScript.isNode(element)) { + return this.breakpointSpanOfNode(positionedElement); + } + if (TypeScript.isToken(element)) { + return this.breakpointSpanOfToken(positionedElement); + } + return this.breakpointSpanOfContainingNode(positionedElement); + }; + return BreakpointResolver; + })(); + function getBreakpointLocation(syntaxTree, askedPos) { + if (TypeScript.isDTSFile(syntaxTree.fileName())) { + return null; + } + var sourceUnit = syntaxTree.sourceUnit(); + var positionedToken = TypeScript.findToken(sourceUnit, askedPos); + var lineMap = syntaxTree.lineMap(); + var posLine = lineMap.getLineNumberFromPosition(askedPos); + var tokenStartLine = lineMap.getLineNumberFromPosition(TypeScript.start(positionedToken)); + if (posLine < tokenStartLine) { + return null; + } + var breakpointResolver = new BreakpointResolver(posLine, lineMap); + return breakpointResolver.breakpointSpanOf(positionedToken); + } + Breakpoints.getBreakpointLocation = getBreakpointLocation; + })(Services.Breakpoints || (Services.Breakpoints = {})); + var Breakpoints = Services.Breakpoints; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfTokenAtPosition(syntaxTree, position, options) { + var token = TypeScript.findToken(syntaxTree.sourceUnit(), position); + return columnForStartOfTokenAtPosition(syntaxTree, position, options) + TypeScript.width(token); + } + Indentation.columnForEndOfTokenAtPosition = columnForEndOfTokenAtPosition; + function columnForStartOfTokenAtPosition(syntaxTree, position, options) { + var token = TypeScript.findToken(syntaxTree.sourceUnit(), position); + var firstTokenInLine = TypeScript.Syntax.firstTokenInLineContainingPosition(syntaxTree, token.fullStart()); + var leadingTextInReverse = []; + var current = token; + while (current !== firstTokenInLine) { + current = TypeScript.previousToken(current); + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } + else { + leadingTextInReverse.push(current.fullText()); + } + } + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfTokenAtPosition = columnForStartOfTokenAtPosition; + function columnForStartOfFirstTokenInLineContainingPosition(syntaxTree, position, options) { + var firstTokenInLine = TypeScript.Syntax.firstTokenInLineContainingPosition(syntaxTree, position); + var leadingTextInReverse = []; + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingPosition = columnForStartOfFirstTokenInLineContainingPosition; + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + if (lineSegments.length > 0) { + break; + } + } + leadingTextInReverse.push(trivia.fullText()); + } + } + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + return column; + } + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } + else { + column++; + } + } + return column; + } + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = Math.max(0, column); + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var TextSnapshot = (function () { + function TextSnapshot(snapshot) { + this.snapshot = snapshot; + this.lines = []; + } + TextSnapshot.prototype.getText = function (span) { + return this.snapshot.substr(span.start(), span.length()); + }; + TextSnapshot.prototype.getLineNumberFromPosition = function (position) { + return this.snapshot.lineMap().getLineNumberFromPosition(position); + }; + TextSnapshot.prototype.getLineFromPosition = function (position) { + var lineNumber = this.getLineNumberFromPosition(position); + return this.getLineFromLineNumber(lineNumber); + }; + TextSnapshot.prototype.getLineFromLineNumber = function (lineNumber) { + var line = this.lines[lineNumber]; + if (line === undefined) { + line = this.getLineFromLineNumberWorker(lineNumber); + this.lines[lineNumber] = line; + } + return line; + }; + TextSnapshot.prototype.getLineFromLineNumberWorker = function (lineNumber) { + var lineMap = this.snapshot.lineMap().lineStarts(); + var lineMapIndex = lineNumber; + if (lineMapIndex < 0 || lineMapIndex >= lineMap.length) + throw new Error(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Invalid_line_number_0, [lineMapIndex])); + var start = lineMap[lineMapIndex]; + var end; + var endIncludingLineBreak; + var lineBreak = ""; + if (lineMapIndex == lineMap.length) { + end = endIncludingLineBreak = this.snapshot.length(); + } + else { + endIncludingLineBreak = (lineMapIndex >= lineMap.length - 1 ? this.snapshot.length() : lineMap[lineMapIndex + 1]); + for (var p = endIncludingLineBreak - 1; p >= start; p--) { + var c = this.snapshot.substr(p, 1); + if (c != "\r" && c != "\n") { + break; + } + } + end = p + 1; + lineBreak = this.snapshot.substr(end, endIncludingLineBreak - end); + } + var result = new Formatting.TextSnapshotLine(this, lineNumber, start, end, lineBreak); + return result; + }; + return TextSnapshot; + })(); + Formatting.TextSnapshot = TextSnapshot; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var TextSnapshotLine = (function () { + function TextSnapshotLine(_snapshot, _lineNumber, _start, _end, _lineBreak) { + this._snapshot = _snapshot; + this._lineNumber = _lineNumber; + this._start = _start; + this._end = _end; + this._lineBreak = _lineBreak; + } + TextSnapshotLine.prototype.snapshot = function () { + return this._snapshot; + }; + TextSnapshotLine.prototype.start = function () { + return new Formatting.SnapshotPoint(this._snapshot, this._start); + }; + TextSnapshotLine.prototype.startPosition = function () { + return this._start; + }; + TextSnapshotLine.prototype.end = function () { + return new Formatting.SnapshotPoint(this._snapshot, this._end); + }; + TextSnapshotLine.prototype.endPosition = function () { + return this._end; + }; + TextSnapshotLine.prototype.endIncludingLineBreak = function () { + return new Formatting.SnapshotPoint(this._snapshot, this._end + this._lineBreak.length); + }; + TextSnapshotLine.prototype.endIncludingLineBreakPosition = function () { + return this._end + this._lineBreak.length; + }; + TextSnapshotLine.prototype.length = function () { + return this._end - this._start; + }; + TextSnapshotLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + TextSnapshotLine.prototype.getText = function () { + return this._snapshot.getText(TypeScript.TextSpan.fromBounds(this._start, this._end)); + }; + return TextSnapshotLine; + })(); + Formatting.TextSnapshotLine = TextSnapshotLine; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var SnapshotPoint = (function () { + function SnapshotPoint(snapshot, position) { + this.snapshot = snapshot; + this.position = position; + } + SnapshotPoint.prototype.getContainingLine = function () { + return this.snapshot.getLineFromPosition(this.position); + }; + SnapshotPoint.prototype.add = function (offset) { + return new SnapshotPoint(this.snapshot, this.position + offset); + }; + return SnapshotPoint; + })(); + Formatting.SnapshotPoint = SnapshotPoint; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var FormattingContext = (function () { + function FormattingContext(snapshot, formattingRequestKind) { + this.snapshot = snapshot; + this.formattingRequestKind = formattingRequestKind; + this.currentTokenSpan = null; + this.nextTokenSpan = null; + this.contextNode = null; + this.currentTokenParent = null; + this.nextTokenParent = null; + this.contextNodeAllOnSameLine = null; + this.nextNodeAllOnSameLine = null; + this.tokensAreOnSameLine = null; + this.contextNodeBlockIsOnOneLine = null; + this.nextNodeBlockIsOnOneLine = null; + TypeScript.Debug.assert(this.snapshot != null, "snapshot is null"); + } + FormattingContext.prototype.updateContext = function (currentTokenSpan, currentTokenParent, nextTokenSpan, nextTokenParent, commonParent) { + TypeScript.Debug.assert(currentTokenSpan != null, "currentTokenSpan is null"); + TypeScript.Debug.assert(currentTokenParent != null, "currentTokenParent is null"); + TypeScript.Debug.assert(nextTokenSpan != null, "nextTokenSpan is null"); + TypeScript.Debug.assert(nextTokenParent != null, "nextTokenParent is null"); + TypeScript.Debug.assert(commonParent != null, "commonParent is null"); + this.currentTokenSpan = currentTokenSpan; + this.currentTokenParent = currentTokenParent; + this.nextTokenSpan = nextTokenSpan; + this.nextTokenParent = nextTokenParent; + this.contextNode = commonParent; + this.contextNodeAllOnSameLine = null; + this.nextNodeAllOnSameLine = null; + this.tokensAreOnSameLine = null; + this.contextNodeBlockIsOnOneLine = null; + this.nextNodeBlockIsOnOneLine = null; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === null) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === null) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === null) { + var startLine = this.snapshot.getLineNumberFromPosition(this.currentTokenSpan.start()); + var endLine = this.snapshot.getLineNumberFromPosition(this.nextTokenSpan.start()); + this.tokensAreOnSameLine = (startLine == endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === null) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === null) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.snapshot.getLineNumberFromPosition(node.start()); + var endLine = this.snapshot.getLineNumberFromPosition(node.end()); + return startLine == endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var block = node.node(); + return this.snapshot.getLineNumberFromPosition(TypeScript.end(block.openBraceToken)) === this.snapshot.getLineNumberFromPosition(TypeScript.start(block.closeBraceToken)); + }; + return FormattingContext; + })(); + Formatting.FormattingContext = FormattingContext; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var FormattingManager = (function () { + function FormattingManager(syntaxTree, snapshot, rulesProvider, editorOptions) { + this.syntaxTree = syntaxTree; + this.snapshot = snapshot; + this.rulesProvider = rulesProvider; + this.options = new TypeScript.FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter); + } + FormattingManager.prototype.formatSelection = function (minChar, limChar) { + var span = TypeScript.TextSpan.fromBounds(minChar, limChar); + return this.formatSpan(span, 1 /* FormatSelection */); + }; + FormattingManager.prototype.formatDocument = function (minChar, limChar) { + var span = TypeScript.TextSpan.fromBounds(minChar, limChar); + return this.formatSpan(span, 0 /* FormatDocument */); + }; + FormattingManager.prototype.formatOnPaste = function (minChar, limChar) { + var span = TypeScript.TextSpan.fromBounds(minChar, limChar); + return this.formatSpan(span, 5 /* FormatOnPaste */); + }; + FormattingManager.prototype.formatOnSemicolon = function (caretPosition) { + var sourceUnit = this.syntaxTree.sourceUnit(); + var semicolonPositionedToken = TypeScript.findToken(sourceUnit, caretPosition - 1); + if (semicolonPositionedToken.kind() === 78 /* SemicolonToken */) { + var current = semicolonPositionedToken; + while (current.parent !== null && TypeScript.end(current.parent) === TypeScript.end(semicolonPositionedToken) && current.parent.kind() !== 1 /* List */) { + current = current.parent; + } + var span = new TypeScript.TextSpan(TypeScript.fullStart(current), TypeScript.fullWidth(current)); + return this.formatSpan(span, 3 /* FormatOnSemicolon */); + } + return []; + }; + FormattingManager.prototype.formatOnClosingCurlyBrace = function (caretPosition) { + var sourceUnit = this.syntaxTree.sourceUnit(); + var closeBracePositionedToken = TypeScript.findToken(sourceUnit, caretPosition - 1); + if (closeBracePositionedToken.kind() === 71 /* CloseBraceToken */) { + var current = closeBracePositionedToken; + while (current.parent !== null && TypeScript.end(current.parent) === TypeScript.end(closeBracePositionedToken) && current.parent.kind() !== 1 /* List */) { + current = current.parent; + } + var span = new TypeScript.TextSpan(TypeScript.fullStart(current), TypeScript.fullWidth(current)); + return this.formatSpan(span, 4 /* FormatOnClosingCurlyBrace */); + } + return []; + }; + FormattingManager.prototype.formatOnEnter = function (caretPosition) { + var lineNumber = this.snapshot.getLineNumberFromPosition(caretPosition); + if (lineNumber > 0) { + var prevLine = this.snapshot.getLineFromLineNumber(lineNumber - 1); + var currentLine = this.snapshot.getLineFromLineNumber(lineNumber); + var span = TypeScript.TextSpan.fromBounds(prevLine.startPosition(), currentLine.endPosition()); + return this.formatSpan(span, 2 /* FormatOnEnter */); + } + return []; + }; + FormattingManager.prototype.formatSpan = function (span, formattingRequestKind) { + var startLine = this.snapshot.getLineFromPosition(span.start()); + span = TypeScript.TextSpan.fromBounds(startLine.startPosition(), span.end()); + var result = []; + var formattingEdits = Formatting.Formatter.getEdits(span, this.syntaxTree.sourceUnit(), this.options, true, this.snapshot, this.rulesProvider, formattingRequestKind); + formattingEdits.forEach(function (item) { + result.push({ + minChar: item.position, + limChar: item.position + item.length, + text: item.replaceWith + }); + }); + return result; + }; + return FormattingManager; + })(); + Formatting.FormattingManager = FormattingManager; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnPaste"] = 5] = "FormatOnPaste"; + })(Formatting.FormattingRequestKind || (Formatting.FormattingRequestKind = {})); + var FormattingRequestKind = Formatting.FormattingRequestKind; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var Rule = (function () { + function Rule(Descriptor, Operation, Flag) { + if (Flag === void 0) { Flag = 0 /* None */; } + this.Descriptor = Descriptor; + this.Operation = Operation; + this.Flag = Flag; + } + Rule.prototype.toString = function () { + return "[desc=" + this.Descriptor + "," + "operation=" + this.Operation + "," + "flag=" + this.Flag + "]"; + }; + return Rule; + })(); + Formatting.Rule = Rule; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 0] = "Ignore"; + RuleAction[RuleAction["Space"] = 1] = "Space"; + RuleAction[RuleAction["NewLine"] = 2] = "NewLine"; + RuleAction[RuleAction["Delete"] = 3] = "Delete"; + })(Formatting.RuleAction || (Formatting.RuleAction = {})); + var RuleAction = Formatting.RuleAction; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var RuleDescriptor = (function () { + function RuleDescriptor(LeftTokenRange, RightTokenRange) { + this.LeftTokenRange = LeftTokenRange; + this.RightTokenRange = RightTokenRange; + } + RuleDescriptor.prototype.toString = function () { + return "[leftRange=" + this.LeftTokenRange + "," + "rightRange=" + this.RightTokenRange + "]"; + }; + RuleDescriptor.create1 = function (left, right) { + return RuleDescriptor.create4(Formatting.Shared.TokenRange.FromToken(left), Formatting.Shared.TokenRange.FromToken(right)); + }; + RuleDescriptor.create2 = function (left, right) { + return RuleDescriptor.create4(left, Formatting.Shared.TokenRange.FromToken(right)); + }; + RuleDescriptor.create3 = function (left, right) { + return RuleDescriptor.create4(Formatting.Shared.TokenRange.FromToken(left), right); + }; + RuleDescriptor.create4 = function (left, right) { + return new RuleDescriptor(left, right); + }; + return RuleDescriptor; + })(); + Formatting.RuleDescriptor = RuleDescriptor; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(Formatting.RuleFlags || (Formatting.RuleFlags = {})); + var RuleFlags = Formatting.RuleFlags; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var RuleOperation = (function () { + function RuleOperation() { + this.Context = null; + this.Action = null; + } + RuleOperation.prototype.toString = function () { + return "[context=" + this.Context + "," + "action=" + this.Action + "]"; + }; + RuleOperation.create1 = function (action) { + return RuleOperation.create2(Formatting.RuleOperationContext.Any, action); + }; + RuleOperation.create2 = function (context, action) { + var result = new RuleOperation(); + result.Context = context; + result.Action = action; + return result; + }; + return RuleOperation; + })(); + Formatting.RuleOperation = RuleOperation; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var RuleOperationContext = (function () { + function RuleOperationContext() { + var funcs = []; + for (var _i = 0; _i < arguments.length; _i++) { + funcs[_i - 0] = arguments[_i]; + } + this.customContextChecks = funcs; + } + RuleOperationContext.prototype.IsAny = function () { + return this == RuleOperationContext.Any; + }; + RuleOperationContext.prototype.InContext = function (context) { + if (this.IsAny()) { + return true; + } + for (var i = 0, len = this.customContextChecks.length; i < len; i++) { + if (!this.customContextChecks[i](context)) { + return false; + } + } + return true; + }; + RuleOperationContext.Any = new RuleOperationContext(); + return RuleOperationContext; + })(); + Formatting.RuleOperationContext = RuleOperationContext; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var Rules = (function () { + function Rules() { + this.IgnoreBeforeComment = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.Any, Formatting.Shared.TokenRange.Comments), Formatting.RuleOperation.create1(0 /* Ignore */)); + this.IgnoreAfterLineComment = new Formatting.Rule(Formatting.RuleDescriptor.create3(7 /* SingleLineCommentTrivia */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create1(0 /* Ignore */)); + this.NoSpaceBeforeSemicolon = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 78 /* SemicolonToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeColon = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 106 /* ColonToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 3 /* Delete */)); + this.NoSpaceBeforeQMark = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 105 /* QuestionToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 3 /* Delete */)); + this.SpaceAfterColon = new Formatting.Rule(Formatting.RuleDescriptor.create3(106 /* ColonToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 1 /* Space */)); + this.SpaceAfterQMark = new Formatting.Rule(Formatting.RuleDescriptor.create3(105 /* QuestionToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 1 /* Space */)); + this.SpaceAfterSemicolon = new Formatting.Rule(Formatting.RuleDescriptor.create3(78 /* SemicolonToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.SpaceAfterCloseBrace = new Formatting.Rule(Formatting.RuleDescriptor.create3(71 /* CloseBraceToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), 1 /* Space */)); + this.SpaceBetweenCloseBraceAndElse = new Formatting.Rule(Formatting.RuleDescriptor.create1(71 /* CloseBraceToken */, 23 /* ElseKeyword */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.SpaceBetweenCloseBraceAndWhile = new Formatting.Rule(Formatting.RuleDescriptor.create1(71 /* CloseBraceToken */, 42 /* WhileKeyword */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.NoSpaceAfterCloseBrace = new Formatting.Rule(Formatting.RuleDescriptor.create3(71 /* CloseBraceToken */, Formatting.Shared.TokenRange.FromTokens([73 /* CloseParenToken */, 75 /* CloseBracketToken */, 79 /* CommaToken */, 78 /* SemicolonToken */])), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeDot = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 76 /* DotToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterDot = new Formatting.Rule(Formatting.RuleDescriptor.create3(76 /* DotToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeOpenBracket = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 74 /* OpenBracketToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterOpenBracket = new Formatting.Rule(Formatting.RuleDescriptor.create3(74 /* OpenBracketToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeCloseBracket = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 75 /* CloseBracketToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterCloseBracket = new Formatting.Rule(Formatting.RuleDescriptor.create3(75 /* CloseBracketToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.FunctionOpenBraceLeftTokenRange = Formatting.Shared.TokenRange.AnyIncludingMultilineComments; + this.SpaceBeforeOpenBraceInFunction = new Formatting.Rule(Formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 1 /* Space */), 1 /* CanDeleteNewLines */); + this.TypeScriptOpenBraceLeftTokenRange = Formatting.Shared.TokenRange.FromTokens([11 /* IdentifierName */, 6 /* MultiLineCommentTrivia */]); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new Formatting.Rule(Formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 1 /* Space */), 1 /* CanDeleteNewLines */); + this.ControlOpenBraceLeftTokenRange = Formatting.Shared.TokenRange.FromTokens([73 /* CloseParenToken */, 6 /* MultiLineCommentTrivia */, 22 /* DoKeyword */, 38 /* TryKeyword */, 25 /* FinallyKeyword */, 23 /* ElseKeyword */]); + this.SpaceBeforeOpenBraceInControl = new Formatting.Rule(Formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 1 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceAfterOpenBrace = new Formatting.Rule(Formatting.RuleDescriptor.create3(70 /* OpenBraceToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 1 /* Space */)); + this.SpaceBeforeCloseBrace = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 71 /* CloseBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 1 /* Space */)); + this.NoSpaceBetweenEmptyBraceBrackets = new Formatting.Rule(Formatting.RuleDescriptor.create1(70 /* OpenBraceToken */, 71 /* CloseBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), 3 /* Delete */)); + this.NewLineAfterOpenBraceInBlockContext = new Formatting.Rule(Formatting.RuleDescriptor.create3(70 /* OpenBraceToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 2 /* NewLine */)); + this.NewLineBeforeCloseBraceInBlockContext = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.AnyIncludingMultilineComments, 71 /* CloseBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 2 /* NewLine */)); + this.NoSpaceAfterUnaryPrefixOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.UnaryPrefixOperators, Formatting.Shared.TokenRange.UnaryPrefixExpressions), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 3 /* Delete */)); + this.NoSpaceAfterUnaryPreincrementOperator = new Formatting.Rule(Formatting.RuleDescriptor.create3(93 /* PlusPlusToken */, Formatting.Shared.TokenRange.UnaryPreincrementExpressions), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterUnaryPredecrementOperator = new Formatting.Rule(Formatting.RuleDescriptor.create3(94 /* MinusMinusToken */, Formatting.Shared.TokenRange.UnaryPredecrementExpressions), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeUnaryPostincrementOperator = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.UnaryPostincrementExpressions, 93 /* PlusPlusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 94 /* MinusMinusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new Formatting.Rule(Formatting.RuleDescriptor.create1(93 /* PlusPlusToken */, 89 /* PlusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new Formatting.Rule(Formatting.RuleDescriptor.create1(89 /* PlusToken */, 89 /* PlusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterAddWhenFollowedByPreincrement = new Formatting.Rule(Formatting.RuleDescriptor.create1(89 /* PlusToken */, 93 /* PlusPlusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new Formatting.Rule(Formatting.RuleDescriptor.create1(94 /* MinusMinusToken */, 90 /* MinusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new Formatting.Rule(Formatting.RuleDescriptor.create1(90 /* MinusToken */, 90 /* MinusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new Formatting.Rule(Formatting.RuleDescriptor.create1(90 /* MinusToken */, 94 /* MinusMinusToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.NoSpaceBeforeComma = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 79 /* CommaToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.SpaceAfterCertainKeywords = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.FromTokens([40 /* VarKeyword */, 36 /* ThrowKeyword */, 31 /* NewKeyword */, 21 /* DeleteKeyword */, 33 /* ReturnKeyword */, 39 /* TypeOfKeyword */]), Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncCall = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext), 3 /* Delete */)); + this.SpaceAfterFunctionInFuncDecl = new Formatting.Rule(Formatting.RuleDescriptor.create3(27 /* FunctionKeyword */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 1 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncDecl = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), 3 /* Delete */)); + this.SpaceAfterVoidOperator = new Formatting.Rule(Formatting.RuleDescriptor.create3(41 /* VoidKeyword */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), 1 /* Space */)); + this.NoSpaceBetweenReturnAndSemicolon = new Formatting.Rule(Formatting.RuleDescriptor.create1(33 /* ReturnKeyword */, 78 /* SemicolonToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.SpaceBetweenStatements = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.FromTokens([73 /* CloseParenToken */, 22 /* DoKeyword */, 23 /* ElseKeyword */, 16 /* CaseKeyword */]), Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), 1 /* Space */)); + this.SpaceAfterTryFinally = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.FromTokens([38 /* TryKeyword */, 25 /* FinallyKeyword */]), 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.SpaceAfterGetSetInMember = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.FromTokens([64 /* GetKeyword */, 68 /* SetKeyword */]), 11 /* IdentifierName */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 1 /* Space */)); + this.SpaceBeforeBinaryKeywordOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.Any, Formatting.Shared.TokenRange.BinaryKeywordOperators), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterBinaryKeywordOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.BinaryKeywordOperators, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.NoSpaceAfterConstructor = new Formatting.Rule(Formatting.RuleDescriptor.create1(62 /* ConstructorKeyword */, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterModuleImport = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.FromTokens([65 /* ModuleKeyword */, 66 /* RequireKeyword */]), 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.SpaceAfterCertainTypeScriptKeywords = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.FromTokens([44 /* ClassKeyword */, 63 /* DeclareKeyword */, 46 /* EnumKeyword */, 47 /* ExportKeyword */, 48 /* ExtendsKeyword */, 64 /* GetKeyword */, 51 /* ImplementsKeyword */, 49 /* ImportKeyword */, 52 /* InterfaceKeyword */, 65 /* ModuleKeyword */, 55 /* PrivateKeyword */, 57 /* PublicKeyword */, 68 /* SetKeyword */, 58 /* StaticKeyword */]), Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.SpaceBeforeCertainTypeScriptKeywords = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.Any, Formatting.Shared.TokenRange.FromTokens([48 /* ExtendsKeyword */, 51 /* ImplementsKeyword */])), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.SpaceAfterModuleName = new Formatting.Rule(Formatting.RuleDescriptor.create1(14 /* StringLiteral */, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsModuleDeclContext), 1 /* Space */)); + this.SpaceAfterArrow = new Formatting.Rule(Formatting.RuleDescriptor.create3(85 /* EqualsGreaterThanToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.NoSpaceAfterEllipsis = new Formatting.Rule(Formatting.RuleDescriptor.create1(77 /* DotDotDotToken */, 11 /* IdentifierName */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterOptionalParameters = new Formatting.Rule(Formatting.RuleDescriptor.create3(105 /* QuestionToken */, Formatting.Shared.TokenRange.FromTokens([73 /* CloseParenToken */, 79 /* CommaToken */])), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 3 /* Delete */)); + this.NoSpaceBeforeOpenAngularBracket = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.TypeNames, 80 /* LessThanToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), 3 /* Delete */)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new Formatting.Rule(Formatting.RuleDescriptor.create1(73 /* CloseParenToken */, 80 /* LessThanToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), 3 /* Delete */)); + this.NoSpaceAfterOpenAngularBracket = new Formatting.Rule(Formatting.RuleDescriptor.create3(80 /* LessThanToken */, Formatting.Shared.TokenRange.TypeNames), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), 3 /* Delete */)); + this.NoSpaceBeforeCloseAngularBracket = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 81 /* GreaterThanToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), 3 /* Delete */)); + this.NoSpaceAfterCloseAngularBracket = new Formatting.Rule(Formatting.RuleDescriptor.create3(81 /* GreaterThanToken */, Formatting.Shared.TokenRange.FromTokens([72 /* OpenParenToken */, 74 /* OpenBracketToken */, 81 /* GreaterThanToken */, 79 /* CommaToken */])), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), 3 /* Delete */)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new Formatting.Rule(Formatting.RuleDescriptor.create1(70 /* OpenBraceToken */, 71 /* CloseBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 3 /* Delete */)); + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, + this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, + this.SpaceAfterColon, + this.NoSpaceBeforeQMark, + this.SpaceAfterQMark, + this.NoSpaceBeforeDot, + this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, + this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, + this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, + this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, + this.SpaceAfterSubtractWhenFollowedByPredecrement, + this.NoSpaceAfterCloseBrace, + this.SpaceAfterOpenBrace, + this.SpaceBeforeCloseBrace, + this.NewLineBeforeCloseBraceInBlockContext, + this.SpaceAfterCloseBrace, + this.SpaceBetweenCloseBraceAndElse, + this.SpaceBetweenCloseBraceAndWhile, + this.NoSpaceBetweenEmptyBraceBrackets, + this.SpaceAfterFunctionInFuncDecl, + this.NewLineAfterOpenBraceInBlockContext, + this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenReturnAndSemicolon, + this.SpaceAfterCertainKeywords, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, + this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.NoSpaceAfterConstructor, + this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, + this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket + ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, + this.SpaceBeforeOpenBraceInFunction, + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterOpenBracket, + this.NoSpaceBeforeCloseBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, + this.SpaceAfterTryFinally + ]; + this.SpaceAfterComma = new Formatting.Rule(Formatting.RuleDescriptor.create3(79 /* CommaToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.NoSpaceAfterComma = new Formatting.Rule(Formatting.RuleDescriptor.create3(79 /* CommaToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.SpaceBeforeBinaryOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.Any, Formatting.Shared.TokenRange.BinaryOperators), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.SpaceAfterBinaryOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.BinaryOperators, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 1 /* Space */)); + this.NoSpaceBeforeBinaryOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.Any, Formatting.Shared.TokenRange.BinaryOperators), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 3 /* Delete */)); + this.NoSpaceAfterBinaryOperator = new Formatting.Rule(Formatting.RuleDescriptor.create4(Formatting.Shared.TokenRange.BinaryOperators, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 3 /* Delete */)); + this.SpaceAfterKeywordInControl = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Keywords, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsControlDeclContext), 1 /* Space */)); + this.NoSpaceAfterKeywordInControl = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Keywords, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsControlDeclContext), 3 /* Delete */)); + this.NewLineBeforeOpenBraceInFunction = new Formatting.Rule(Formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 2 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new Formatting.Rule(Formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 2 /* NewLine */), 1 /* CanDeleteNewLines */); + this.NewLineBeforeOpenBraceInControl = new Formatting.Rule(Formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 70 /* OpenBraceToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 2 /* NewLine */), 1 /* CanDeleteNewLines */); + this.SpaceAfterSemicolonInFor = new Formatting.Rule(Formatting.RuleDescriptor.create3(78 /* SemicolonToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 1 /* Space */)); + this.NoSpaceAfterSemicolonInFor = new Formatting.Rule(Formatting.RuleDescriptor.create3(78 /* SemicolonToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 3 /* Delete */)); + this.SpaceAfterOpenParen = new Formatting.Rule(Formatting.RuleDescriptor.create3(72 /* OpenParenToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.SpaceBeforeCloseParen = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 73 /* CloseParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 1 /* Space */)); + this.NoSpaceBetweenParens = new Formatting.Rule(Formatting.RuleDescriptor.create1(72 /* OpenParenToken */, 73 /* CloseParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceAfterOpenParen = new Formatting.Rule(Formatting.RuleDescriptor.create3(72 /* OpenParenToken */, Formatting.Shared.TokenRange.Any), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.NoSpaceBeforeCloseParen = new Formatting.Rule(Formatting.RuleDescriptor.create2(Formatting.Shared.TokenRange.Any, 73 /* CloseParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 3 /* Delete */)); + this.SpaceAfterAnonymousFunctionKeyword = new Formatting.Rule(Formatting.RuleDescriptor.create1(27 /* FunctionKeyword */, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 1 /* Space */)); + this.NoSpaceAfterAnonymousFunctionKeyword = new Formatting.Rule(Formatting.RuleDescriptor.create1(27 /* FunctionKeyword */, 72 /* OpenParenToken */), Formatting.RuleOperation.create2(new Formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 3 /* Delete */)); + } + Rules.prototype.getRuleName = function (rule) { + var o = this; + for (var name in o) { + if (o[name] === rule) { + return name; + } + } + throw new Error(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unknown_rule, null)); + }; + Rules.IsForContext = function (context) { + return context.contextNode.kind() === 154 /* ForStatement */; + }; + Rules.IsNotForContext = function (context) { + return !Rules.IsForContext(context); + }; + Rules.IsBinaryOpContext = function (context) { + switch (context.contextNode.kind()) { + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 186 /* ConditionalExpression */: + case 187 /* LogicalOrExpression */: + case 188 /* LogicalAndExpression */: + case 189 /* BitwiseOrExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 191 /* BitwiseAndExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return true; + case 133 /* ImportDeclaration */: + case 225 /* VariableDeclarator */: + case 232 /* EqualsValueClause */: + return context.currentTokenSpan.kind === 107 /* EqualsToken */ || context.nextTokenSpan.kind === 107 /* EqualsToken */; + case 155 /* ForInStatement */: + return context.currentTokenSpan.kind === 29 /* InKeyword */ || context.nextTokenSpan.kind === 29 /* InKeyword */; + } + return false; + }; + Rules.IsNotBinaryOpContext = function (context) { + return !Rules.IsBinaryOpContext(context); + }; + Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { + return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); + }; + Rules.IsBeforeMultilineBlockContext = function (context) { + return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + }; + Rules.IsMultilineBlockContext = function (context) { + return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + }; + Rules.IsSingleLineBlockContext = function (context) { + return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + }; + Rules.IsBlockContext = function (context) { + return Rules.NodeIsBlockContext(context.contextNode); + }; + Rules.IsBeforeBlockContext = function (context) { + return Rules.NodeIsBlockContext(context.nextTokenParent); + }; + Rules.NodeIsBlockContext = function (node) { + if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) { + return true; + } + switch (node.kind()) { + case 146 /* Block */: + case 151 /* SwitchStatement */: + case 215 /* ObjectLiteralExpression */: + return true; + } + return false; + }; + Rules.IsFunctionDeclContext = function (context) { + switch (context.contextNode.kind()) { + case 129 /* FunctionDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 145 /* MethodSignature */: + case 142 /* CallSignature */: + case 222 /* FunctionExpression */: + case 137 /* ConstructorDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 128 /* InterfaceDeclaration */: + return true; + } + return false; + }; + Rules.IsTypeScriptDeclWithBlockContext = function (context) { + return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); + }; + Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { + switch (node.kind()) { + case 131 /* ClassDeclaration */: + case 132 /* EnumDeclaration */: + case 122 /* ObjectType */: + case 130 /* ModuleDeclaration */: + return true; + } + return false; + }; + Rules.IsAfterCodeBlockContext = function (context) { + switch (context.currentTokenParent.kind()) { + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + case 132 /* EnumDeclaration */: + case 146 /* Block */: + case 151 /* SwitchStatement */: + return true; + } + return false; + }; + Rules.IsControlDeclContext = function (context) { + switch (context.contextNode.kind()) { + case 147 /* IfStatement */: + case 151 /* SwitchStatement */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 159 /* TryStatement */: + case 161 /* DoStatement */: + case 163 /* WithStatement */: + case 235 /* ElseClause */: + case 236 /* CatchClause */: + case 237 /* FinallyClause */: + return true; + default: + return false; + } + }; + Rules.IsObjectContext = function (context) { + return context.contextNode.kind() === 215 /* ObjectLiteralExpression */; + }; + Rules.IsFunctionCallContext = function (context) { + return context.contextNode.kind() === 213 /* InvocationExpression */; + }; + Rules.IsNewContext = function (context) { + return context.contextNode.kind() === 216 /* ObjectCreationExpression */; + }; + Rules.IsFunctionCallOrNewContext = function (context) { + return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); + }; + Rules.IsSameLineTokenContext = function (context) { + return context.TokensAreOnSameLine(); + }; + Rules.IsNotFormatOnEnter = function (context) { + return context.formattingRequestKind != 2 /* FormatOnEnter */; + }; + Rules.IsModuleDeclContext = function (context) { + return context.contextNode.kind() === 130 /* ModuleDeclaration */; + }; + Rules.IsObjectTypeContext = function (context) { + return context.contextNode.kind() === 122 /* ObjectType */ && context.contextNode.parent().kind() !== 128 /* InterfaceDeclaration */; + }; + Rules.IsTypeArgumentOrParameter = function (tokenKind, parentKind) { + return ((tokenKind === 80 /* LessThanToken */ || tokenKind === 81 /* GreaterThanToken */) && (parentKind === 229 /* TypeParameterList */ || parentKind === 228 /* TypeArgumentList */)); + }; + Rules.IsTypeArgumentOrParameterContext = function (context) { + return Rules.IsTypeArgumentOrParameter(context.currentTokenSpan.kind, context.currentTokenParent.kind()) || Rules.IsTypeArgumentOrParameter(context.nextTokenSpan.kind, context.nextTokenParent.kind()); + }; + Rules.IsVoidOpContext = function (context) { + return context.currentTokenSpan.kind === 41 /* VoidKeyword */ && context.currentTokenParent.kind() === 172 /* VoidExpression */; + }; + return Rules; + })(); + Formatting.Rules = Rules; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var RulesMap = (function () { + function RulesMap() { + this.map = []; + this.mapRowLength = 0; + } + RulesMap.create = function (rules) { + var result = new RulesMap(); + result.Initialize(rules); + return result; + }; + RulesMap.prototype.Initialize = function (rules) { + this.mapRowLength = TypeScript.SyntaxKind.LastToken + 1; + this.map = new Array(this.mapRowLength * this.mapRowLength); + var rulesBucketConstructionStateList = new Array(this.map.length); + this.FillRules(rules, rulesBucketConstructionStateList); + return this.map; + }; + RulesMap.prototype.FillRules = function (rules, rulesBucketConstructionStateList) { + var _this = this; + rules.forEach(function (rule) { + _this.FillRule(rule, rulesBucketConstructionStateList); + }); + }; + RulesMap.prototype.GetRuleBucketIndex = function (row, column) { + var rulesBucketIndex = (row * this.mapRowLength) + column; + return rulesBucketIndex; + }; + RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { + var _this = this; + var specificRule = rule.Descriptor.LeftTokenRange != Formatting.Shared.TokenRange.Any && rule.Descriptor.RightTokenRange != Formatting.Shared.TokenRange.Any; + rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { + rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { + var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); + var rulesBucket = _this.map[rulesBucketIndex]; + if (rulesBucket == undefined) { + rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); + } + rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); + }); + }); + }; + RulesMap.prototype.GetRule = function (context) { + var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); + var bucket = this.map[bucketIndex]; + if (bucket != null) { + for (var i = 0, len = bucket.Rules().length; i < len; i++) { + var rule = bucket.Rules()[i]; + if (rule.Operation.Context.InContext(context)) + return rule; + } + } + return null; + }; + return RulesMap; + })(); + Formatting.RulesMap = RulesMap; + var MaskBitSize = 5; + var Mask = 0x1f; + (function (RulesPosition) { + RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; + RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = MaskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; + })(Formatting.RulesPosition || (Formatting.RulesPosition = {})); + var RulesPosition = Formatting.RulesPosition; + var RulesBucketConstructionState = (function () { + function RulesBucketConstructionState() { + this.rulesInsertionIndexBitmap = 0; + } + RulesBucketConstructionState.prototype.GetInsertionIndex = function (maskPosition) { + var index = 0; + var pos = 0; + var indexBitmap = this.rulesInsertionIndexBitmap; + while (pos <= maskPosition) { + index += (indexBitmap & Mask); + indexBitmap >>= MaskBitSize; + pos += MaskBitSize; + } + return index; + }; + RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { + var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; + value++; + TypeScript.Debug.assert((value & Mask) == value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); + temp |= value << maskPosition; + this.rulesInsertionIndexBitmap = temp; + }; + return RulesBucketConstructionState; + })(); + Formatting.RulesBucketConstructionState = RulesBucketConstructionState; + var RulesBucket = (function () { + function RulesBucket() { + this.rules = []; + } + RulesBucket.prototype.Rules = function () { + return this.rules; + }; + RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { + var position; + if (rule.Operation.Action == 0 /* Ignore */) { + position = specificTokens ? 0 /* IgnoreRulesSpecific */ : RulesPosition.IgnoreRulesAny; + } + else if (!rule.Operation.Context.IsAny()) { + position = specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny; + } + else { + position = specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + } + var state = constructionState[rulesBucketIndex]; + if (state === undefined) { + state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); + } + var index = state.GetInsertionIndex(position); + this.rules.splice(index, 0, rule); + state.IncreaseInsertionIndex(position); + }; + return RulesBucket; + })(); + Formatting.RulesBucket = RulesBucket; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var RulesProvider = (function () { + function RulesProvider(logger) { + this.logger = logger; + this.globalRules = new Formatting.Rules(); + } + RulesProvider.prototype.getRuleName = function (rule) { + return this.globalRules.getRuleName(rule); + }; + RulesProvider.prototype.getRuleByName = function (name) { + return this.globalRules[name]; + }; + RulesProvider.prototype.getRulesMap = function () { + return this.rulesMap; + }; + RulesProvider.prototype.ensureUpToDate = function (options) { + var _this = this; + if (this.options == null || !ts.compareDataObjects(this.options, options)) { + var activeRules = TypeScript.timeFunction(this.logger, "RulesProvider: createActiveRules()", function () { + return _this.createActiveRules(options); + }); + var rulesMap = TypeScript.timeFunction(this.logger, "RulesProvider: RulesMap.create()", function () { + return Formatting.RulesMap.create(activeRules); + }); + this.activeRules = activeRules; + this.rulesMap = rulesMap; + this.options = ts.clone(options); + } + }; + RulesProvider.prototype.createActiveRules = function (options) { + var rules = this.globalRules.HighPriorityCommonRules.slice(0); + if (options.InsertSpaceAfterCommaDelimiter) { + rules.push(this.globalRules.SpaceAfterComma); + } + else { + rules.push(this.globalRules.NoSpaceAfterComma); + } + if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); + } + else { + rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); + } + if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + rules.push(this.globalRules.SpaceAfterKeywordInControl); + } + else { + rules.push(this.globalRules.NoSpaceAfterKeywordInControl); + } + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + rules.push(this.globalRules.SpaceAfterOpenParen); + rules.push(this.globalRules.SpaceBeforeCloseParen); + rules.push(this.globalRules.NoSpaceBetweenParens); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenParen); + rules.push(this.globalRules.NoSpaceBeforeCloseParen); + rules.push(this.globalRules.NoSpaceBetweenParens); + } + if (options.InsertSpaceAfterSemicolonInForStatements) { + rules.push(this.globalRules.SpaceAfterSemicolonInFor); + } + else { + rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); + } + if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + rules.push(this.globalRules.SpaceBeforeBinaryOperator); + rules.push(this.globalRules.SpaceAfterBinaryOperator); + } + else { + rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); + rules.push(this.globalRules.NoSpaceAfterBinaryOperator); + } + if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); + } + if (options.PlaceOpenBraceOnNewLineForFunctions) { + rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); + rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); + } + rules = rules.concat(this.globalRules.LowPriorityCommonRules); + return rules; + }; + return RulesProvider; + })(); + Formatting.RulesProvider = RulesProvider; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var TextEditInfo = (function () { + function TextEditInfo(position, length, replaceWith) { + this.position = position; + this.length = length; + this.replaceWith = replaceWith; + } + TextEditInfo.prototype.toString = function () { + return "[ position: " + this.position + ", length: " + this.length + ", replaceWith: '" + this.replaceWith + "' ]"; + }; + return TextEditInfo; + })(); + Formatting.TextEditInfo = TextEditInfo; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + (function (Shared) { + var TokenRangeAccess = (function () { + function TokenRangeAccess(from, to, except) { + this.tokens = []; + for (var token = from; token <= to; token++) { + if (except.indexOf(token) < 0) { + this.tokens.push(token); + } + } + } + TokenRangeAccess.prototype.GetTokens = function () { + return this.tokens; + }; + TokenRangeAccess.prototype.Contains = function (token) { + return this.tokens.indexOf(token) >= 0; + }; + TokenRangeAccess.prototype.toString = function () { + return "[tokenRangeStart=" + TypeScript.SyntaxKind[this.tokens[0]] + "," + "tokenRangeEnd=" + TypeScript.SyntaxKind[this.tokens[this.tokens.length - 1]] + "]"; + }; + return TokenRangeAccess; + })(); + Shared.TokenRangeAccess = TokenRangeAccess; + var TokenValuesAccess = (function () { + function TokenValuesAccess(tks) { + this.tokens = tks && tks.length ? tks : []; + } + TokenValuesAccess.prototype.GetTokens = function () { + return this.tokens; + }; + TokenValuesAccess.prototype.Contains = function (token) { + return this.tokens.indexOf(token) >= 0; + }; + return TokenValuesAccess; + })(); + Shared.TokenValuesAccess = TokenValuesAccess; + var TokenSingleValueAccess = (function () { + function TokenSingleValueAccess(token) { + this.token = token; + } + TokenSingleValueAccess.prototype.GetTokens = function () { + return [this.token]; + }; + TokenSingleValueAccess.prototype.Contains = function (tokenValue) { + return tokenValue == this.token; + }; + TokenSingleValueAccess.prototype.toString = function () { + return "[singleTokenKind=" + TypeScript.SyntaxKind[this.token] + "]"; + }; + return TokenSingleValueAccess; + })(); + Shared.TokenSingleValueAccess = TokenSingleValueAccess; + var TokenAllAccess = (function () { + function TokenAllAccess() { + } + TokenAllAccess.prototype.GetTokens = function () { + var result = []; + for (var token = TypeScript.SyntaxKind.FirstToken; token <= TypeScript.SyntaxKind.LastToken; token++) { + result.push(token); + } + return result; + }; + TokenAllAccess.prototype.Contains = function (tokenValue) { + return true; + }; + TokenAllAccess.prototype.toString = function () { + return "[allTokens]"; + }; + return TokenAllAccess; + })(); + Shared.TokenAllAccess = TokenAllAccess; + var TokenRange = (function () { + function TokenRange(tokenAccess) { + this.tokenAccess = tokenAccess; + } + TokenRange.FromToken = function (token) { + return new TokenRange(new TokenSingleValueAccess(token)); + }; + TokenRange.FromTokens = function (tokens) { + return new TokenRange(new TokenValuesAccess(tokens)); + }; + TokenRange.FromRange = function (f, to, except) { + if (except === void 0) { except = []; } + return new TokenRange(new TokenRangeAccess(f, to, except)); + }; + TokenRange.AllTokens = function () { + return new TokenRange(new TokenAllAccess()); + }; + TokenRange.prototype.GetTokens = function () { + return this.tokenAccess.GetTokens(); + }; + TokenRange.prototype.Contains = function (token) { + return this.tokenAccess.Contains(token); + }; + TokenRange.prototype.toString = function () { + return this.tokenAccess.toString(); + }; + TokenRange.Any = TokenRange.AllTokens(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([6 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(TypeScript.SyntaxKind.FirstKeyword, TypeScript.SyntaxKind.LastKeyword); + TokenRange.Operators = TokenRange.FromRange(78 /* SemicolonToken */, 119 /* SlashEqualsToken */); + TokenRange.BinaryOperators = TokenRange.FromRange(80 /* LessThanToken */, 119 /* SlashEqualsToken */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([29 /* InKeyword */, 30 /* InstanceOfKeyword */]); + TokenRange.ReservedKeywords = TokenRange.FromRange(TypeScript.SyntaxKind.FirstFutureReservedStrictKeyword, TypeScript.SyntaxKind.LastFutureReservedStrictKeyword); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([93 /* PlusPlusToken */, 94 /* MinusMinusToken */, 102 /* TildeToken */, 101 /* ExclamationToken */]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([13 /* NumericLiteral */, 11 /* IdentifierName */, 72 /* OpenParenToken */, 74 /* OpenBracketToken */, 70 /* OpenBraceToken */, 35 /* ThisKeyword */, 31 /* NewKeyword */]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([11 /* IdentifierName */, 72 /* OpenParenToken */, 35 /* ThisKeyword */, 31 /* NewKeyword */]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([11 /* IdentifierName */, 73 /* CloseParenToken */, 75 /* CloseBracketToken */, 31 /* NewKeyword */]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([11 /* IdentifierName */, 72 /* OpenParenToken */, 35 /* ThisKeyword */, 31 /* NewKeyword */]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([11 /* IdentifierName */, 73 /* CloseParenToken */, 75 /* CloseBracketToken */, 31 /* NewKeyword */]); + TokenRange.Comments = TokenRange.FromTokens([7 /* SingleLineCommentTrivia */, 6 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([11 /* IdentifierName */, 67 /* NumberKeyword */, 69 /* StringKeyword */, 61 /* BooleanKeyword */, 41 /* VoidKeyword */, 60 /* AnyKeyword */]); + return TokenRange; + })(); + Shared.TokenRange = TokenRange; + })(Formatting.Shared || (Formatting.Shared = {})); + var Shared = Formatting.Shared; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var TokenSpan = (function (_super) { + __extends(TokenSpan, _super); + function TokenSpan(kind, start, length) { + _super.call(this, start, length); + this.kind = kind; + } + return TokenSpan; + })(TypeScript.TextSpan); + Formatting.TokenSpan = TokenSpan; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var IndentationNodeContext = (function () { + function IndentationNodeContext(parent, node, fullStart, indentationAmount, childIndentationAmountDelta) { + this.update(parent, node, fullStart, indentationAmount, childIndentationAmountDelta); + } + IndentationNodeContext.prototype.parent = function () { + return this._parent; + }; + IndentationNodeContext.prototype.node = function () { + return this._node; + }; + IndentationNodeContext.prototype.fullStart = function () { + return this._fullStart; + }; + IndentationNodeContext.prototype.fullWidth = function () { + return TypeScript.fullWidth(this._node); + }; + IndentationNodeContext.prototype.start = function () { + return this._fullStart + TypeScript.leadingTriviaWidth(this._node); + }; + IndentationNodeContext.prototype.end = function () { + return this._fullStart + TypeScript.leadingTriviaWidth(this._node) + TypeScript.width(this._node); + }; + IndentationNodeContext.prototype.indentationAmount = function () { + return this._indentationAmount; + }; + IndentationNodeContext.prototype.childIndentationAmountDelta = function () { + return this._childIndentationAmountDelta; + }; + IndentationNodeContext.prototype.depth = function () { + return this._depth; + }; + IndentationNodeContext.prototype.kind = function () { + return this._node.kind(); + }; + IndentationNodeContext.prototype.hasSkippedOrMissingTokenChild = function () { + if (this._hasSkippedOrMissingTokenChild === null) { + this._hasSkippedOrMissingTokenChild = TypeScript.Syntax.nodeHasSkippedOrMissingTokens(this._node); + } + return this._hasSkippedOrMissingTokenChild; + }; + IndentationNodeContext.prototype.clone = function (pool) { + var parent = null; + if (this._parent) { + parent = this._parent.clone(pool); + } + return pool.getNode(parent, this._node, this._fullStart, this._indentationAmount, this._childIndentationAmountDelta); + }; + IndentationNodeContext.prototype.update = function (parent, node, fullStart, indentationAmount, childIndentationAmountDelta) { + this._parent = parent; + this._node = node; + this._fullStart = fullStart; + this._indentationAmount = indentationAmount; + this._childIndentationAmountDelta = childIndentationAmountDelta; + this._hasSkippedOrMissingTokenChild = null; + if (parent) { + this._depth = parent.depth() + 1; + } + else { + this._depth = 0; + } + }; + return IndentationNodeContext; + })(); + Formatting.IndentationNodeContext = IndentationNodeContext; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var IndentationNodeContextPool = (function () { + function IndentationNodeContextPool() { + this.nodes = []; + } + IndentationNodeContextPool.prototype.getNode = function (parent, node, fullStart, indentationLevel, childIndentationLevelDelta) { + if (this.nodes.length > 0) { + var cachedNode = this.nodes.pop(); + cachedNode.update(parent, node, fullStart, indentationLevel, childIndentationLevelDelta); + return cachedNode; + } + return new Formatting.IndentationNodeContext(parent, node, fullStart, indentationLevel, childIndentationLevelDelta); + }; + IndentationNodeContextPool.prototype.releaseNode = function (node, recursive) { + if (recursive === void 0) { recursive = false; } + this.nodes.push(node); + if (recursive) { + var parent = node.parent(); + if (parent) { + this.releaseNode(parent, recursive); + } + } + }; + return IndentationNodeContextPool; + })(); + Formatting.IndentationNodeContextPool = IndentationNodeContextPool; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var IndentationTrackingWalker = (function (_super) { + __extends(IndentationTrackingWalker, _super); + function IndentationTrackingWalker(textSpan, sourceUnit, snapshot, indentFirstToken, options) { + _super.call(this); + this.options = options; + this._position = 0; + this._parent = null; + this._indentationNodeContextPool = new Formatting.IndentationNodeContextPool(); + this._textSpan = textSpan; + this._text = sourceUnit.syntaxTree.text; + this._snapshot = snapshot; + this._parent = this._indentationNodeContextPool.getNode(null, sourceUnit, 0, 0, 0); + this._lastTriviaWasNewLine = indentFirstToken; + } + IndentationTrackingWalker.prototype.position = function () { + return this._position; + }; + IndentationTrackingWalker.prototype.parent = function () { + return this._parent; + }; + IndentationTrackingWalker.prototype.textSpan = function () { + return this._textSpan; + }; + IndentationTrackingWalker.prototype.snapshot = function () { + return this._snapshot; + }; + IndentationTrackingWalker.prototype.indentationNodeContextPool = function () { + return this._indentationNodeContextPool; + }; + IndentationTrackingWalker.prototype.forceIndentNextToken = function (tokenStart) { + this._lastTriviaWasNewLine = true; + this.forceRecomputeIndentationOfParent(tokenStart, true); + }; + IndentationTrackingWalker.prototype.forceSkipIndentingNextToken = function (tokenStart) { + this._lastTriviaWasNewLine = false; + this.forceRecomputeIndentationOfParent(tokenStart, false); + }; + IndentationTrackingWalker.prototype.indentToken = function (token, indentationAmount, commentIndentationAmount) { + throw TypeScript.Errors.abstract(); + }; + IndentationTrackingWalker.prototype.visitTokenInSpan = function (token) { + if (this._lastTriviaWasNewLine) { + var indentationAmount = this.getTokenIndentationAmount(token); + var commentIndentationAmount = this.getCommentIndentationAmount(token); + this.indentToken(token, indentationAmount, commentIndentationAmount); + } + }; + IndentationTrackingWalker.prototype.visitToken = function (token) { + var tokenSpan = new TypeScript.TextSpan(this._position, token.fullWidth()); + if (tokenSpan.intersectsWithTextSpan(this._textSpan)) { + this.visitTokenInSpan(token); + var trivia = token.trailingTrivia(); + this._lastTriviaWasNewLine = trivia.hasNewLine() && trivia.syntaxTriviaAt(trivia.count() - 1).kind() == 5 /* NewLineTrivia */; + } + this._position += token.fullWidth(); + }; + IndentationTrackingWalker.prototype.visitNode = function (node) { + var nodeSpan = new TypeScript.TextSpan(this._position, TypeScript.fullWidth(node)); + if (nodeSpan.intersectsWithTextSpan(this._textSpan)) { + var indentation = this.getNodeIndentation(node); + var currentParent = this._parent; + this._parent = this._indentationNodeContextPool.getNode(currentParent, node, this._position, indentation.indentationAmount, indentation.indentationAmountDelta); + TypeScript.visitNodeOrToken(this, node); + this._indentationNodeContextPool.releaseNode(this._parent); + this._parent = currentParent; + } + else { + this._position += TypeScript.fullWidth(node); + } + }; + IndentationTrackingWalker.prototype.getTokenIndentationAmount = function (token) { + if (TypeScript.firstToken(this._parent.node()) === token || token.kind() === 70 /* OpenBraceToken */ || token.kind() === 71 /* CloseBraceToken */ || token.kind() === 74 /* OpenBracketToken */ || token.kind() === 75 /* CloseBracketToken */ || (token.kind() === 42 /* WhileKeyword */ && this._parent.node().kind() == 161 /* DoStatement */)) { + return this._parent.indentationAmount(); + } + return (this._parent.indentationAmount() + this._parent.childIndentationAmountDelta()); + }; + IndentationTrackingWalker.prototype.getCommentIndentationAmount = function (token) { + if (token.kind() === 71 /* CloseBraceToken */ || token.kind() === 75 /* CloseBracketToken */) { + return (this._parent.indentationAmount() + this._parent.childIndentationAmountDelta()); + } + return this._parent.indentationAmount(); + }; + IndentationTrackingWalker.prototype.getNodeIndentation = function (node, newLineInsertedByFormatting) { + var parent = this._parent; + var parentIndentationAmount; + if (this._textSpan.containsPosition(parent.start())) { + parentIndentationAmount = parent.indentationAmount(); + } + else { + if (parent.kind() === 146 /* Block */ && !this.shouldIndentBlockInParent(this._parent.parent())) { + parent = this._parent.parent(); + } + var line = this._snapshot.getLineFromPosition(parent.start()).getText(); + var firstNonWhiteSpacePosition = TypeScript.Indentation.firstNonWhitespacePosition(line); + parentIndentationAmount = TypeScript.Indentation.columnForPositionInString(line, firstNonWhiteSpacePosition, this.options); + } + var parentIndentationAmountDelta = parent.childIndentationAmountDelta(); + var indentationAmount; + var indentationAmountDelta; + var parentNode = parent.node(); + switch (node.kind()) { + default: + indentationAmount = (parentIndentationAmount + parentIndentationAmountDelta); + indentationAmountDelta = 0; + break; + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + case 122 /* ObjectType */: + case 132 /* EnumDeclaration */: + case 151 /* SwitchStatement */: + case 215 /* ObjectLiteralExpression */: + case 137 /* ConstructorDeclaration */: + case 129 /* FunctionDeclaration */: + case 222 /* FunctionExpression */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 138 /* IndexMemberDeclaration */: + case 236 /* CatchClause */: + case 214 /* ArrayLiteralExpression */: + case 124 /* ArrayType */: + case 221 /* ElementAccessExpression */: + case 144 /* IndexSignature */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + case 163 /* WithStatement */: + case 233 /* CaseSwitchClause */: + case 234 /* DefaultSwitchClause */: + case 150 /* ReturnStatement */: + case 157 /* ThrowStatement */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 224 /* VariableDeclaration */: + case 134 /* ExportAssignment */: + case 213 /* InvocationExpression */: + case 216 /* ObjectCreationExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + indentationAmount = (parentIndentationAmount + parentIndentationAmountDelta); + indentationAmountDelta = this.options.indentSpaces; + break; + case 147 /* IfStatement */: + if (parent.kind() === 235 /* ElseClause */ && !TypeScript.SyntaxUtilities.isLastTokenOnLine(parentNode.elseKeyword, this._text)) { + indentationAmount = parentIndentationAmount; + } + else { + indentationAmount = (parentIndentationAmount + parentIndentationAmountDelta); + } + indentationAmountDelta = this.options.indentSpaces; + break; + case 235 /* ElseClause */: + indentationAmount = parentIndentationAmount; + indentationAmountDelta = this.options.indentSpaces; + break; + case 146 /* Block */: + if (this.shouldIndentBlockInParent(parent)) { + indentationAmount = parentIndentationAmount + parentIndentationAmountDelta; + } + else { + indentationAmount = parentIndentationAmount; + } + indentationAmountDelta = this.options.indentSpaces; + break; + } + if (parentNode) { + if (!newLineInsertedByFormatting) { + var parentStartLine = this._snapshot.getLineNumberFromPosition(parent.start()); + var currentNodeStartLine = this._snapshot.getLineNumberFromPosition(this._position + TypeScript.leadingTriviaWidth(node)); + if (parentStartLine === currentNodeStartLine || newLineInsertedByFormatting === false) { + indentationAmount = parentIndentationAmount; + indentationAmountDelta = Math.min(this.options.indentSpaces, parentIndentationAmountDelta + indentationAmountDelta); + } + } + } + return { + indentationAmount: indentationAmount, + indentationAmountDelta: indentationAmountDelta + }; + }; + IndentationTrackingWalker.prototype.shouldIndentBlockInParent = function (parent) { + switch (parent.kind()) { + case 120 /* SourceUnit */: + case 130 /* ModuleDeclaration */: + case 146 /* Block */: + case 233 /* CaseSwitchClause */: + case 234 /* DefaultSwitchClause */: + return true; + default: + return false; + } + }; + IndentationTrackingWalker.prototype.forceRecomputeIndentationOfParent = function (tokenStart, newLineAdded) { + var parent = this._parent; + if (parent.fullStart() === tokenStart) { + this._parent = parent.parent(); + var indentation = this.getNodeIndentation(parent.node(), newLineAdded); + parent.update(parent.parent(), parent.node(), parent.fullStart(), indentation.indentationAmount, indentation.indentationAmountDelta); + this._parent = parent; + } + }; + return IndentationTrackingWalker; + })(TypeScript.SyntaxWalker); + Formatting.IndentationTrackingWalker = IndentationTrackingWalker; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var MultipleTokenIndenter = (function (_super) { + __extends(MultipleTokenIndenter, _super); + function MultipleTokenIndenter(textSpan, sourceUnit, snapshot, indentFirstToken, options) { + _super.call(this, textSpan, sourceUnit, snapshot, indentFirstToken, options); + this._edits = []; + } + MultipleTokenIndenter.prototype.indentToken = function (token, indentationAmount, commentIndentationAmount) { + if (token.fullWidth() === 0) { + return; + } + if (this.parent().hasSkippedOrMissingTokenChild()) { + return; + } + var tokenSpan = new TypeScript.TextSpan(this.position() + token.leadingTriviaWidth(), TypeScript.width(token)); + if (!this.textSpan().containsTextSpan(tokenSpan)) { + return; + } + var indentationString = TypeScript.Indentation.indentationString(indentationAmount, this.options); + var commentIndentationString = TypeScript.Indentation.indentationString(commentIndentationAmount, this.options); + this.recordIndentationEditsForToken(token, indentationString, commentIndentationString); + }; + MultipleTokenIndenter.prototype.edits = function () { + return this._edits; + }; + MultipleTokenIndenter.prototype.recordEdit = function (position, length, replaceWith) { + this._edits.push(new Formatting.TextEditInfo(position, length, replaceWith)); + }; + MultipleTokenIndenter.prototype.recordIndentationEditsForToken = function (token, indentationString, commentIndentationString) { + var position = this.position(); + var indentNextTokenOrTrivia = true; + var leadingWhiteSpace = ""; + var triviaList = token.leadingTrivia(); + if (triviaList) { + for (var i = 0, length = triviaList.count(); i < length; i++, position += trivia.fullWidth()) { + var trivia = triviaList.syntaxTriviaAt(i); + if (!this.textSpan().containsTextSpan(new TypeScript.TextSpan(position, trivia.fullWidth()))) { + continue; + } + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.recordIndentationEditsForMultiLineComment(trivia, position, commentIndentationString, leadingWhiteSpace, !indentNextTokenOrTrivia); + indentNextTokenOrTrivia = false; + leadingWhiteSpace = ""; + break; + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + if (indentNextTokenOrTrivia) { + this.recordIndentationEditsForSingleLineOrSkippedText(trivia, position, commentIndentationString); + indentNextTokenOrTrivia = false; + } + break; + case 4 /* WhitespaceTrivia */: + var nextTrivia = length > i + 1 && triviaList.syntaxTriviaAt(i + 1); + var whiteSpaceIndentationString = nextTrivia && nextTrivia.isComment() ? commentIndentationString : indentationString; + if (indentNextTokenOrTrivia) { + if (!(nextTrivia && nextTrivia.isNewLine())) { + this.recordIndentationEditsForWhitespace(trivia, position, whiteSpaceIndentationString); + } + indentNextTokenOrTrivia = false; + } + leadingWhiteSpace += trivia.fullText(); + break; + case 5 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + leadingWhiteSpace = ""; + break; + default: + throw TypeScript.Errors.invalidOperation(); + } + } + } + if (token.kind() !== 10 /* EndOfFileToken */ && indentNextTokenOrTrivia) { + if (indentationString.length > 0) { + this.recordEdit(position, 0, indentationString); + } + } + }; + MultipleTokenIndenter.prototype.recordIndentationEditsForSingleLineOrSkippedText = function (trivia, fullStart, indentationString) { + if (indentationString.length > 0) { + this.recordEdit(fullStart, 0, indentationString); + } + }; + MultipleTokenIndenter.prototype.recordIndentationEditsForWhitespace = function (trivia, fullStart, indentationString) { + var text = trivia.fullText(); + if (indentationString === text) { + return; + } + this.recordEdit(fullStart, text.length, indentationString); + }; + MultipleTokenIndenter.prototype.recordIndentationEditsForMultiLineComment = function (trivia, fullStart, indentationString, leadingWhiteSpace, firstLineAlreadyIndented) { + var position = fullStart; + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length <= 1) { + if (!firstLineAlreadyIndented) { + this.recordIndentationEditsForSingleLineOrSkippedText(trivia, fullStart, indentationString); + } + return; + } + var whiteSpaceColumnsInFirstSegment = TypeScript.Indentation.columnForPositionInString(leadingWhiteSpace, leadingWhiteSpace.length, this.options); + var indentationColumns = TypeScript.Indentation.columnForPositionInString(indentationString, indentationString.length, this.options); + var startIndex = 0; + if (firstLineAlreadyIndented) { + startIndex = 1; + position += segments[0].length; + } + for (var i = startIndex; i < segments.length; i++) { + var segment = segments[i]; + this.recordIndentationEditsForSegment(segment, position, indentationColumns, whiteSpaceColumnsInFirstSegment); + position += segment.length; + } + }; + MultipleTokenIndenter.prototype.recordIndentationEditsForSegment = function (segment, fullStart, indentationColumns, whiteSpaceColumnsInFirstSegment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + var leadingWhiteSpaceColumns = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + var deltaFromFirstSegment = leadingWhiteSpaceColumns - whiteSpaceColumnsInFirstSegment; + var finalColumns = indentationColumns + deltaFromFirstSegment; + if (finalColumns < 0) { + finalColumns = 0; + } + var indentationString = TypeScript.Indentation.indentationString(finalColumns, this.options); + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return; + } + if (indentationString === segment.substring(0, firstNonWhitespacePosition)) { + return; + } + this.recordEdit(fullStart, firstNonWhitespacePosition, indentationString); + }; + return MultipleTokenIndenter; + })(Formatting.IndentationTrackingWalker); + Formatting.MultipleTokenIndenter = MultipleTokenIndenter; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var SingleTokenIndenter = (function (_super) { + __extends(SingleTokenIndenter, _super); + function SingleTokenIndenter(indentationPosition, sourceUnit, snapshot, indentFirstToken, options) { + _super.call(this, new TypeScript.TextSpan(indentationPosition, 1), sourceUnit, snapshot, indentFirstToken, options); + this.indentationAmount = null; + this.indentationPosition = indentationPosition; + } + SingleTokenIndenter.getIndentationAmount = function (position, sourceUnit, snapshot, options) { + var walker = new SingleTokenIndenter(position, sourceUnit, snapshot, true, options); + TypeScript.visitNodeOrToken(walker, sourceUnit); + return walker.indentationAmount; + }; + SingleTokenIndenter.prototype.indentToken = function (token, indentationAmount, commentIndentationAmount) { + if (token.fullWidth() === 0 || (this.indentationPosition - this.position() < token.leadingTriviaWidth())) { + this.indentationAmount = commentIndentationAmount; + } + else { + this.indentationAmount = indentationAmount; + } + }; + return SingleTokenIndenter; + })(Formatting.IndentationTrackingWalker); + Formatting.SingleTokenIndenter = SingleTokenIndenter; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + (function (Formatting) { + var Formatter = (function (_super) { + __extends(Formatter, _super); + function Formatter(textSpan, sourceUnit, indentFirstToken, options, snapshot, rulesProvider, formattingRequestKind) { + _super.call(this, textSpan, sourceUnit, snapshot, indentFirstToken, options); + this.previousTokenSpan = null; + this.previousTokenParent = null; + this.scriptHasErrors = false; + this.previousTokenParent = this.parent().clone(this.indentationNodeContextPool()); + this.rulesProvider = rulesProvider; + this.formattingRequestKind = formattingRequestKind; + this.formattingContext = new Formatting.FormattingContext(this.snapshot(), this.formattingRequestKind); + } + Formatter.getEdits = function (textSpan, sourceUnit, options, indentFirstToken, snapshot, rulesProvider, formattingRequestKind) { + var walker = new Formatter(textSpan, sourceUnit, indentFirstToken, options, snapshot, rulesProvider, formattingRequestKind); + TypeScript.visitNodeOrToken(walker, sourceUnit); + return walker.edits(); + }; + Formatter.prototype.visitTokenInSpan = function (token) { + if (token.fullWidth() !== 0) { + var tokenSpan = new TypeScript.TextSpan(this.position() + token.leadingTriviaWidth(), TypeScript.width(token)); + if (this.textSpan().containsTextSpan(tokenSpan)) { + this.processToken(token); + } + } + _super.prototype.visitTokenInSpan.call(this, token); + }; + Formatter.prototype.processToken = function (token) { + var position = this.position(); + if (token.leadingTriviaWidth() !== 0) { + this.processTrivia(token.leadingTrivia(), position); + position += token.leadingTriviaWidth(); + } + var currentTokenSpan = new Formatting.TokenSpan(token.kind(), position, TypeScript.width(token)); + if (!this.parent().hasSkippedOrMissingTokenChild()) { + if (this.previousTokenSpan) { + this.formatPair(this.previousTokenSpan, this.previousTokenParent, currentTokenSpan, this.parent()); + } + else { + this.trimWhitespaceInLineRange(this.getLineNumber(this.textSpan()), this.getLineNumber(currentTokenSpan)); + } + } + this.previousTokenSpan = currentTokenSpan; + if (this.previousTokenParent) { + this.indentationNodeContextPool().releaseNode(this.previousTokenParent, true); + } + this.previousTokenParent = this.parent().clone(this.indentationNodeContextPool()); + position += TypeScript.width(token); + if (token.trailingTriviaWidth() !== 0) { + this.processTrivia(token.trailingTrivia(), position); + } + }; + Formatter.prototype.processTrivia = function (triviaList, fullStart) { + var position = fullStart; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isComment() || trivia.isSkippedToken()) { + var currentTokenSpan = new Formatting.TokenSpan(trivia.kind(), position, trivia.fullWidth()); + if (this.textSpan().containsTextSpan(currentTokenSpan)) { + if (trivia.isComment() && this.previousTokenSpan) { + this.formatPair(this.previousTokenSpan, this.previousTokenParent, currentTokenSpan, this.parent()); + } + else { + var startLine = this.getLineNumber(this.previousTokenSpan || this.textSpan()); + this.trimWhitespaceInLineRange(startLine, this.getLineNumber(currentTokenSpan)); + } + this.previousTokenSpan = currentTokenSpan; + if (this.previousTokenParent) { + this.indentationNodeContextPool().releaseNode(this.previousTokenParent, true); + } + this.previousTokenParent = this.parent().clone(this.indentationNodeContextPool()); + } + } + position += trivia.fullWidth(); + } + }; + Formatter.prototype.findCommonParents = function (parent1, parent2) { + var shallowParent; + var shallowParentDepth; + var deepParent; + var deepParentDepth; + if (parent1.depth() < parent2.depth()) { + shallowParent = parent1; + shallowParentDepth = parent1.depth(); + deepParent = parent2; + deepParentDepth = parent2.depth(); + } + else { + shallowParent = parent2; + shallowParentDepth = parent2.depth(); + deepParent = parent1; + deepParentDepth = parent1.depth(); + } + TypeScript.Debug.assert(shallowParentDepth >= 0, "Expected shallowParentDepth >= 0"); + TypeScript.Debug.assert(deepParentDepth >= 0, "Expected deepParentDepth >= 0"); + TypeScript.Debug.assert(deepParentDepth >= shallowParentDepth, "Expected deepParentDepth >= shallowParentDepth"); + while (deepParentDepth > shallowParentDepth) { + deepParent = deepParent.parent(); + deepParentDepth--; + } + TypeScript.Debug.assert(deepParentDepth === shallowParentDepth, "Expected deepParentDepth === shallowParentDepth"); + while (deepParent.node() && shallowParent.node()) { + if (deepParent.node() === shallowParent.node()) { + return deepParent; + } + deepParent = deepParent.parent(); + shallowParent = shallowParent.parent(); + } + throw TypeScript.Errors.invalidOperation(); + }; + Formatter.prototype.formatPair = function (t1, t1Parent, t2, t2Parent) { + var token1Line = this.getLineNumber(t1); + var token2Line = this.getLineNumber(t2); + var commonParent = this.findCommonParents(t1Parent, t2Parent); + this.formattingContext.updateContext(t1, t1Parent, t2, t2Parent, commonParent); + var rule = this.rulesProvider.getRulesMap().GetRule(this.formattingContext); + if (rule != null) { + this.RecordRuleEdits(rule, t1, t2); + if ((rule.Operation.Action == 1 /* Space */ || rule.Operation.Action == 3 /* Delete */) && token1Line != token2Line) { + this.forceSkipIndentingNextToken(t2.start()); + } + if (rule.Operation.Action == 2 /* NewLine */ && token1Line == token2Line) { + this.forceIndentNextToken(t2.start()); + } + } + if (token1Line != token2Line && (!rule || (rule.Operation.Action != 3 /* Delete */ && rule.Flag != 1 /* CanDeleteNewLines */))) { + this.trimWhitespaceInLineRange(token1Line, token2Line, t1); + } + }; + Formatter.prototype.getLineNumber = function (span) { + return this.snapshot().getLineNumberFromPosition(span.start()); + }; + Formatter.prototype.trimWhitespaceInLineRange = function (startLine, endLine, token) { + for (var lineNumber = startLine; lineNumber < endLine; ++lineNumber) { + var line = this.snapshot().getLineFromLineNumber(lineNumber); + this.trimWhitespace(line, token); + } + }; + Formatter.prototype.trimWhitespace = function (line, token) { + if (token && (token.kind == 6 /* MultiLineCommentTrivia */ || token.kind == 7 /* SingleLineCommentTrivia */) && token.start() <= line.endPosition() && token.end() >= line.endPosition()) + return; + var text = line.getText(); + var index = 0; + for (index = text.length - 1; index >= 0; --index) { + if (!TypeScript.CharacterInfo.isWhitespace(text.charCodeAt(index))) { + break; + } + } + ++index; + if (index < text.length) { + this.recordEdit(line.startPosition() + index, line.length() - index, ""); + } + }; + Formatter.prototype.RecordRuleEdits = function (rule, t1, t2) { + if (rule.Operation.Action == 0 /* Ignore */) { + return; + } + var betweenSpan; + switch (rule.Operation.Action) { + case 3 /* Delete */: + { + betweenSpan = new TypeScript.TextSpan(t1.end(), t2.start() - t1.end()); + if (betweenSpan.length() > 0) { + this.recordEdit(betweenSpan.start(), betweenSpan.length(), ""); + return; + } + } + break; + case 2 /* NewLine */: + { + if (!(rule.Flag == 1 /* CanDeleteNewLines */ || this.getLineNumber(t1) == this.getLineNumber(t2))) { + return; + } + betweenSpan = new TypeScript.TextSpan(t1.end(), t2.start() - t1.end()); + var doEdit = false; + var betweenText = this.snapshot().getText(betweenSpan); + var lineFeedLoc = betweenText.indexOf(this.options.newLineCharacter); + if (lineFeedLoc < 0) { + doEdit = true; + } + else { + lineFeedLoc = betweenText.indexOf(this.options.newLineCharacter, lineFeedLoc + 1); + if (lineFeedLoc >= 0) { + doEdit = true; + } + } + if (doEdit) { + this.recordEdit(betweenSpan.start(), betweenSpan.length(), this.options.newLineCharacter); + return; + } + } + break; + case 1 /* Space */: + { + if (!(rule.Flag == 1 /* CanDeleteNewLines */ || this.getLineNumber(t1) == this.getLineNumber(t2))) { + return; + } + betweenSpan = new TypeScript.TextSpan(t1.end(), t2.start() - t1.end()); + if (betweenSpan.length() > 1 || this.snapshot().getText(betweenSpan) != " ") { + this.recordEdit(betweenSpan.start(), betweenSpan.length(), " "); + return; + } + } + break; + } + }; + return Formatter; + })(Formatting.MultipleTokenIndenter); + Formatting.Formatter = Formatter; + })(Services.Formatting || (Services.Formatting = {})); + var Formatting = Services.Formatting; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + var sizeInEvenBytes = (m + 7) & ~7; + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + BloomFilter.prototype.computeHash = function (key, seed) { + return TypeScript.Hash.computeMurmur2StringHashCode(key, seed); + }; + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + if (ts.lookUp(keys, name)) { + this.add(name); + } + } + }; + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + return true; + }; + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; + }; + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var NullLogger = (function () { + function NullLogger() { + } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var proto = "__proto__"; + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + this[proto] = null; + this[proto] = undefined; + } + return BlockIntrinsics; + })(); + function createIntrinsicsObject() { + return new BlockIntrinsics(); + } + TypeScript.createIntrinsicsObject = createIntrinsicsObject; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Comment = (function () { + function Comment(_trivia, endsLine, _start, _end) { + this._trivia = _trivia; + this.endsLine = endsLine; + this._start = _start; + this._end = _end; + } + Comment.prototype.start = function () { + return this._start; + }; + Comment.prototype.end = function () { + return this._end; + }; + Comment.prototype.fullText = function () { + return this._trivia.fullText(); + }; + Comment.prototype.kind = function () { + return this._trivia.kind(); + }; + Comment.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + return this._trivia.fullText() === ast._trivia.fullText() && this.endsLine === ast.endsLine; + }; + return Comment; + })(); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function walkListChildren(preAst, walker) { + for (var i = 0, n = preAst.length; i < n; i++) { + walker.walk(preAst[i]); + } + } + function walkThrowStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkPrefixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + function walkPostfixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + function walkDeleteExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkTypeArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArguments); + } + function walkTypeOfExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkVoidExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArgumentList); + walker.walk(preAst.arguments); + } + function walkArrayLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.expressions); + } + function walkSimplePropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.expression); + } + function walkFunctionPropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkGetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkSeparatedListChildren(preAst, walker) { + for (var i = 0, n = preAst.length; i < n; i++) { + walker.walk(preAst[i]); + } + } + function walkSetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkObjectLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.propertyAssignments); + } + function walkCastExpressionChildren(preAst, walker) { + walker.walk(preAst.type); + walker.walk(preAst.expression); + } + function walkParenthesizedExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkElementAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentExpression); + } + function walkMemberAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.name); + } + function walkQualifiedNameChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + function walkBinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + function walkEqualsValueClauseChildren(preAst, walker) { + walker.walk(preAst.value); + } + function walkTypeParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.constraint); + } + function walkTypeParameterListChildren(preAst, walker) { + walker.walk(preAst.typeParameters); + } + function walkGenericTypeChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.typeArgumentList); + } + function walkTypeAnnotationChildren(preAst, walker) { + walker.walk(preAst.type); + } + function walkTypeQueryChildren(preAst, walker) { + walker.walk(preAst.name); + } + function walkInvocationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + function walkObjectCreationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + function walkTrinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.whenTrue); + walker.walk(preAst.whenFalse); + } + function walkFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkFunctionTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + function walkParenthesizedArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + function walkSimpleArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.parameter); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + function walkMemberFunctionDeclarationChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkFuncDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkIndexMemberDeclarationChildren(preAst, walker) { + walker.walk(preAst.indexSignature); + } + function walkIndexSignatureChildren(preAst, walker) { + walker.walk(preAst.parameters); + walker.walk(preAst.typeAnnotation); + } + function walkCallSignatureChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + } + function walkConstraintChildren(preAst, walker) { + walker.walk(preAst.typeOrExpression); + } + function walkConstructorDeclarationChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + function walkConstructorTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + function walkConstructSignatureChildren(preAst, walker) { + walker.walk(preAst.callSignature); + } + function walkParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + function walkParameterListChildren(preAst, walker) { + walker.walk(preAst.parameters); + } + function walkPropertySignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + } + function walkVariableDeclaratorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + function walkMemberVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.variableDeclarator); + } + function walkMethodSignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + } + function walkReturnStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkForStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.initializer); + walker.walk(preAst.condition); + walker.walk(preAst.incrementor); + walker.walk(preAst.statement); + } + function walkForInStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.left); + walker.walk(preAst.expression); + walker.walk(preAst.statement); + } + function walkIfStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + walker.walk(preAst.elseClause); + } + function walkElseClauseChildren(preAst, walker) { + walker.walk(preAst.statement); + } + function walkWhileStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + function walkDoStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + function walkBlockChildren(preAst, walker) { + walker.walk(preAst.statements); + } + function walkVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.variableDeclarators); + } + function walkCaseSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.statements); + } + function walkDefaultSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.statements); + } + function walkSwitchStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.switchClauses); + } + function walkTryStatementChildren(preAst, walker) { + walker.walk(preAst.block); + walker.walk(preAst.catchClause); + walker.walk(preAst.finallyClause); + } + function walkCatchClauseChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + function walkExternalModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.stringLiteral); + } + function walkFinallyClauseChildren(preAst, walker) { + walker.walk(preAst.block); + } + function walkClassDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.classElements); + } + function walkScriptChildren(preAst, walker) { + walker.walk(preAst.moduleElements); + } + function walkHeritageClauseChildren(preAst, walker) { + walker.walk(preAst.typeNames); + } + function walkInterfaceDeclerationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.body); + } + function walkObjectTypeChildren(preAst, walker) { + walker.walk(preAst.typeMembers); + } + function walkArrayTypeChildren(preAst, walker) { + walker.walk(preAst.type); + } + function walkModuleDeclarationChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.stringLiteral); + walker.walk(preAst.moduleElements); + } + function walkModuleNameModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.moduleName); + } + function walkEnumDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.enumElements); + } + function walkEnumElementChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.equalsValueClause); + } + function walkImportDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.moduleReference); + } + function walkExportAssignmentChildren(preAst, walker) { + walker.walk(preAst.identifier); + } + function walkWithStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + function walkExpressionStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + function walkLabeledStatementChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.statement); + } + function walkVariableStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + } + var childrenWalkers = new Array(TypeScript.SyntaxKind.LastNode + 1); + for (var i = TypeScript.SyntaxKind.FirstToken, n = TypeScript.SyntaxKind.LastToken; i <= n; i++) { + childrenWalkers[i] = null; + } + for (var i = TypeScript.SyntaxKind.FirstTrivia, n = TypeScript.SyntaxKind.LastTrivia; i <= n; i++) { + childrenWalkers[i] = null; + } + childrenWalkers[175 /* AddAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[208 /* AddExpression */] = walkBinaryExpressionChildren; + childrenWalkers[180 /* AndAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[60 /* AnyKeyword */] = null; + childrenWalkers[226 /* ArgumentList */] = walkArgumentListChildren; + childrenWalkers[214 /* ArrayLiteralExpression */] = walkArrayLiteralExpressionChildren; + childrenWalkers[124 /* ArrayType */] = walkArrayTypeChildren; + childrenWalkers[219 /* SimpleArrowFunctionExpression */] = walkSimpleArrowFunctionExpressionChildren; + childrenWalkers[218 /* ParenthesizedArrowFunctionExpression */] = walkParenthesizedArrowFunctionExpressionChildren; + childrenWalkers[174 /* AssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[191 /* BitwiseAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[190 /* BitwiseExclusiveOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[166 /* BitwiseNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[189 /* BitwiseOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[146 /* Block */] = walkBlockChildren; + childrenWalkers[61 /* BooleanKeyword */] = null; + childrenWalkers[152 /* BreakStatement */] = null; + childrenWalkers[142 /* CallSignature */] = walkCallSignatureChildren; + childrenWalkers[233 /* CaseSwitchClause */] = walkCaseSwitchClauseChildren; + childrenWalkers[220 /* CastExpression */] = walkCastExpressionChildren; + childrenWalkers[236 /* CatchClause */] = walkCatchClauseChildren; + childrenWalkers[131 /* ClassDeclaration */] = walkClassDeclChildren; + childrenWalkers[173 /* CommaExpression */] = walkBinaryExpressionChildren; + childrenWalkers[186 /* ConditionalExpression */] = walkTrinaryExpressionChildren; + childrenWalkers[239 /* Constraint */] = walkConstraintChildren; + childrenWalkers[137 /* ConstructorDeclaration */] = walkConstructorDeclarationChildren; + childrenWalkers[143 /* ConstructSignature */] = walkConstructSignatureChildren; + childrenWalkers[153 /* ContinueStatement */] = null; + childrenWalkers[125 /* ConstructorType */] = walkConstructorTypeChildren; + childrenWalkers[162 /* DebuggerStatement */] = null; + childrenWalkers[234 /* DefaultSwitchClause */] = walkDefaultSwitchClauseChildren; + childrenWalkers[170 /* DeleteExpression */] = walkDeleteExpressionChildren; + childrenWalkers[178 /* DivideAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[206 /* DivideExpression */] = walkBinaryExpressionChildren; + childrenWalkers[161 /* DoStatement */] = walkDoStatementChildren; + childrenWalkers[221 /* ElementAccessExpression */] = walkElementAccessExpressionChildren; + childrenWalkers[235 /* ElseClause */] = walkElseClauseChildren; + childrenWalkers[156 /* EmptyStatement */] = null; + childrenWalkers[132 /* EnumDeclaration */] = walkEnumDeclarationChildren; + childrenWalkers[243 /* EnumElement */] = walkEnumElementChildren; + childrenWalkers[194 /* EqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[232 /* EqualsValueClause */] = walkEqualsValueClauseChildren; + childrenWalkers[192 /* EqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[181 /* ExclusiveOrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[134 /* ExportAssignment */] = walkExportAssignmentChildren; + childrenWalkers[149 /* ExpressionStatement */] = walkExpressionStatementChildren; + childrenWalkers[230 /* ExtendsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[245 /* ExternalModuleReference */] = walkExternalModuleReferenceChildren; + childrenWalkers[24 /* FalseKeyword */] = null; + childrenWalkers[237 /* FinallyClause */] = walkFinallyClauseChildren; + childrenWalkers[155 /* ForInStatement */] = walkForInStatementChildren; + childrenWalkers[154 /* ForStatement */] = walkForStatementChildren; + childrenWalkers[129 /* FunctionDeclaration */] = walkFuncDeclChildren; + childrenWalkers[222 /* FunctionExpression */] = walkFunctionExpressionChildren; + childrenWalkers[241 /* FunctionPropertyAssignment */] = walkFunctionPropertyAssignmentChildren; + childrenWalkers[123 /* FunctionType */] = walkFunctionTypeChildren; + childrenWalkers[126 /* GenericType */] = walkGenericTypeChildren; + childrenWalkers[139 /* GetAccessor */] = walkGetAccessorChildren; + childrenWalkers[197 /* GreaterThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[199 /* GreaterThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[147 /* IfStatement */] = walkIfStatementChildren; + childrenWalkers[231 /* ImplementsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[133 /* ImportDeclaration */] = walkImportDeclarationChildren; + childrenWalkers[138 /* IndexMemberDeclaration */] = walkIndexMemberDeclarationChildren; + childrenWalkers[144 /* IndexSignature */] = walkIndexSignatureChildren; + childrenWalkers[201 /* InExpression */] = walkBinaryExpressionChildren; + childrenWalkers[200 /* InstanceOfExpression */] = walkBinaryExpressionChildren; + childrenWalkers[128 /* InterfaceDeclaration */] = walkInterfaceDeclerationChildren; + childrenWalkers[213 /* InvocationExpression */] = walkInvocationExpressionChildren; + childrenWalkers[160 /* LabeledStatement */] = walkLabeledStatementChildren; + childrenWalkers[183 /* LeftShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[202 /* LeftShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[196 /* LessThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[198 /* LessThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[1 /* List */] = walkListChildren; + childrenWalkers[188 /* LogicalAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[167 /* LogicalNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[187 /* LogicalOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[212 /* MemberAccessExpression */] = walkMemberAccessExpressionChildren; + childrenWalkers[135 /* MemberFunctionDeclaration */] = walkMemberFunctionDeclarationChildren; + childrenWalkers[136 /* MemberVariableDeclaration */] = walkMemberVariableDeclarationChildren; + childrenWalkers[145 /* MethodSignature */] = walkMethodSignatureChildren; + childrenWalkers[130 /* ModuleDeclaration */] = walkModuleDeclarationChildren; + childrenWalkers[246 /* ModuleNameModuleReference */] = walkModuleNameModuleReferenceChildren; + childrenWalkers[179 /* ModuloAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[207 /* ModuloExpression */] = walkBinaryExpressionChildren; + childrenWalkers[177 /* MultiplyAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[205 /* MultiplyExpression */] = walkBinaryExpressionChildren; + childrenWalkers[11 /* IdentifierName */] = null; + childrenWalkers[165 /* NegateExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[0 /* None */] = null; + childrenWalkers[195 /* NotEqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[193 /* NotEqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[32 /* NullKeyword */] = null; + childrenWalkers[67 /* NumberKeyword */] = null; + childrenWalkers[13 /* NumericLiteral */] = null; + childrenWalkers[216 /* ObjectCreationExpression */] = walkObjectCreationExpressionChildren; + childrenWalkers[215 /* ObjectLiteralExpression */] = walkObjectLiteralExpressionChildren; + childrenWalkers[122 /* ObjectType */] = walkObjectTypeChildren; + childrenWalkers[223 /* OmittedExpression */] = null; + childrenWalkers[182 /* OrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[242 /* Parameter */] = walkParameterChildren; + childrenWalkers[227 /* ParameterList */] = walkParameterListChildren; + childrenWalkers[217 /* ParenthesizedExpression */] = walkParenthesizedExpressionChildren; + childrenWalkers[164 /* PlusExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[211 /* PostDecrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[210 /* PostIncrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[169 /* PreDecrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[168 /* PreIncrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[141 /* PropertySignature */] = walkPropertySignatureChildren; + childrenWalkers[121 /* QualifiedName */] = walkQualifiedNameChildren; + childrenWalkers[12 /* RegularExpressionLiteral */] = null; + childrenWalkers[150 /* ReturnStatement */] = walkReturnStatementChildren; + childrenWalkers[120 /* SourceUnit */] = walkScriptChildren; + childrenWalkers[2 /* SeparatedList */] = walkSeparatedListChildren; + childrenWalkers[140 /* SetAccessor */] = walkSetAccessorChildren; + childrenWalkers[184 /* SignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[203 /* SignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[240 /* SimplePropertyAssignment */] = walkSimplePropertyAssignmentChildren; + childrenWalkers[14 /* StringLiteral */] = null; + childrenWalkers[69 /* StringKeyword */] = null; + childrenWalkers[176 /* SubtractAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[209 /* SubtractExpression */] = walkBinaryExpressionChildren; + childrenWalkers[50 /* SuperKeyword */] = null; + childrenWalkers[151 /* SwitchStatement */] = walkSwitchStatementChildren; + childrenWalkers[35 /* ThisKeyword */] = null; + childrenWalkers[157 /* ThrowStatement */] = walkThrowStatementChildren; + childrenWalkers[3 /* TriviaList */] = null; + childrenWalkers[37 /* TrueKeyword */] = null; + childrenWalkers[159 /* TryStatement */] = walkTryStatementChildren; + childrenWalkers[244 /* TypeAnnotation */] = walkTypeAnnotationChildren; + childrenWalkers[228 /* TypeArgumentList */] = walkTypeArgumentListChildren; + childrenWalkers[171 /* TypeOfExpression */] = walkTypeOfExpressionChildren; + childrenWalkers[238 /* TypeParameter */] = walkTypeParameterChildren; + childrenWalkers[229 /* TypeParameterList */] = walkTypeParameterListChildren; + childrenWalkers[127 /* TypeQuery */] = walkTypeQueryChildren; + childrenWalkers[185 /* UnsignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[204 /* UnsignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[224 /* VariableDeclaration */] = walkVariableDeclarationChildren; + childrenWalkers[225 /* VariableDeclarator */] = walkVariableDeclaratorChildren; + childrenWalkers[148 /* VariableStatement */] = walkVariableStatementChildren; + childrenWalkers[172 /* VoidExpression */] = walkVoidExpressionChildren; + childrenWalkers[41 /* VoidKeyword */] = null; + childrenWalkers[158 /* WhileStatement */] = walkWhileStatementChildren; + childrenWalkers[163 /* WithStatement */] = walkWithStatementChildren; + for (var e in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.SyntaxKind[e])) { + TypeScript.Debug.assert(childrenWalkers[e] !== undefined, "Fix initWalkers: " + TypeScript.SyntaxKind[e]); + } + } + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.stopWalking = false; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + var SimplePreAstWalker = (function () { + function SimplePreAstWalker(pre, state) { + this.pre = pre; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePreAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + this.pre(ast, this.state); + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + }; + return SimplePreAstWalker; + })(); + var SimplePrePostAstWalker = (function () { + function SimplePrePostAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePrePostAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + this.pre(ast, this.state); + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + this.post(ast, this.state); + }; + return SimplePrePostAstWalker; + })(); + var NormalAstWalker = (function () { + function NormalAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + NormalAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + if (this.options.stopWalking) { + return; + } + this.pre(ast, this); + if (this.options.stopWalking) { + return; + } + if (this.options.goChildren) { + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + } + else { + this.options.goChildren = true; + } + if (this.post) { + this.post(ast, this); + } + }; + return NormalAstWalker; + })(); + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, state) { + new NormalAstWalker(pre, post, state).walk(ast); + }; + AstWalkerFactory.prototype.simpleWalk = function (ast, pre, post, state) { + if (post) { + new SimplePrePostAstWalker(pre, post, state).walk(ast); + } + else { + new SimplePreAstWalker(pre, state).walk(ast); + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + var globalAstWalkerFactory = new AstWalkerFactory(); + function getAstWalkerFactory() { + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (ASTHelpers) { + var sentinelEmptyArray = []; + function isValidAstNode(ast) { + return ast && !TypeScript.isShared(ast) && TypeScript.start(ast) !== -1 && TypeScript.end(ast) !== -1; + } + ASTHelpers.isValidAstNode = isValidAstNode; + function isValidSpan(ast) { + if (!ast) + return false; + if (ast.start() === -1 || ast.end() === -1) + return false; + return true; + } + ASTHelpers.isValidSpan = isValidSpan; + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (useTrailingTriviaAsLimChar === void 0) { useTrailingTriviaAsLimChar = true; } + if (forceInclusive === void 0) { forceInclusive = false; } + var top = null; + var pre = function (cur, walker) { + if (!TypeScript.isShared(cur) && isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && TypeScript.width(cur) === 0; + if (isInvalid1) { + walker.options.goChildren = false; + } + else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === TypeScript.end(script) + TypeScript.lastToken(script).trailingTriviaWidth(); + var minChar = TypeScript.start(cur); + var limChar = TypeScript.end(cur) + (useTrailingTriviaAsLimChar ? TypeScript.trailingTriviaWidth(cur) : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || TypeScript.end(cur) > TypeScript.start(cur)) { + if (top === null) { + top = cur; + } + else if (TypeScript.start(cur) >= TypeScript.start(top) && (TypeScript.end(cur) + (useTrailingTriviaAsLimChar ? TypeScript.trailingTriviaWidth(cur) : 0)) <= (TypeScript.end(top) + (useTrailingTriviaAsLimChar ? TypeScript.trailingTriviaWidth(top) : 0))) { + if (TypeScript.width(top) !== 0 || TypeScript.width(cur) !== 0) { + top = cur; + } + } + } + } + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + function getExtendsHeritageClause(clauses) { + return getHeritageClause(clauses, 230 /* ExtendsHeritageClause */); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + function getImplementsHeritageClause(clauses) { + return getHeritageClause(clauses, 231 /* ImplementsHeritageClause */); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var i = 0, n = clauses.length; i < n; i++) { + var child = clauses[i]; + if (child.typeNames.length > 0 && child.kind() === kind) { + return child; + } + } + } + return null; + } + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + function isCallExpressionTarget(ast) { + return !!getCallExpressionTarget(ast); + } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; + function getCallExpressionTarget(ast) { + if (!ast) { + return null; + } + var current = ast; + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + break; + } + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression ? current : null; + } + } + return null; + } + ASTHelpers.getCallExpressionTarget = getCallExpressionTarget; + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + case 145 /* MethodSignature */: + return ast.parent.propertyName === ast; + case 141 /* PropertySignature */: + return ast.parent.propertyName === ast; + } + return false; + } + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || ASTHelpers.isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + function getEnclosingMemberDeclaration(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + case 145 /* MethodSignature */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; + } + return null; + } + ASTHelpers.getEnclosingMemberDeclaration = getEnclosingMemberDeclaration; + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; + } + return false; + } + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + return false; + } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + function parentIsModuleDeclaration(ast) { + return ast.parent && ast.parent.kind() === 130 /* ModuleDeclaration */; + } + ASTHelpers.parentIsModuleDeclaration = parentIsModuleDeclaration; + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } + } + ASTHelpers.isDeclarationAST = isDeclarationAST; + function preComments(element, text) { + if (element) { + switch (element.kind()) { + case 148 /* VariableStatement */: + case 149 /* ExpressionStatement */: + case 131 /* ClassDeclaration */: + case 133 /* ImportDeclaration */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 132 /* EnumDeclaration */: + case 147 /* IfStatement */: + case 240 /* SimplePropertyAssignment */: + case 135 /* MemberFunctionDeclaration */: + case 128 /* InterfaceDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 150 /* ReturnStatement */: + case 137 /* ConstructorDeclaration */: + case 136 /* MemberVariableDeclaration */: + case 243 /* EnumElement */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 144 /* IndexSignature */: + case 141 /* PropertySignature */: + case 145 /* MethodSignature */: + case 241 /* FunctionPropertyAssignment */: + case 242 /* Parameter */: + return convertNodeLeadingComments(element, text); + } + } + return null; + } + ASTHelpers.preComments = preComments; + function postComments(element, text) { + if (element) { + switch (element.kind()) { + case 149 /* ExpressionStatement */: + return convertNodeTrailingComments(element, text, true); + case 148 /* VariableStatement */: + case 131 /* ClassDeclaration */: + case 133 /* ImportDeclaration */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 132 /* EnumDeclaration */: + case 147 /* IfStatement */: + case 240 /* SimplePropertyAssignment */: + case 135 /* MemberFunctionDeclaration */: + case 128 /* InterfaceDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 150 /* ReturnStatement */: + case 137 /* ConstructorDeclaration */: + case 136 /* MemberVariableDeclaration */: + case 243 /* EnumElement */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 144 /* IndexSignature */: + case 141 /* PropertySignature */: + case 145 /* MethodSignature */: + case 241 /* FunctionPropertyAssignment */: + case 242 /* Parameter */: + return convertNodeTrailingComments(element, text); + } + } + return null; + } + ASTHelpers.postComments = postComments; + function convertNodeTrailingComments(node, text, allowWithNewLine) { + if (allowWithNewLine === void 0) { allowWithNewLine = false; } + var _lastToken = TypeScript.lastToken(node); + if (_lastToken === null || !_lastToken.hasTrailingTrivia()) { + return null; + } + if (!allowWithNewLine && TypeScript.SyntaxUtilities.isLastTokenOnLine(_lastToken, text)) { + return null; + } + return convertComments(_lastToken.trailingTrivia(text), TypeScript.fullStart(node) + TypeScript.fullWidth(node) - _lastToken.trailingTriviaWidth(text)); + } + function convertNodeLeadingComments(element, text) { + if (element) { + return convertTokenLeadingComments(TypeScript.firstToken(element), text); + } + return null; + } + function convertTokenLeadingComments(token, text) { + if (token === null) { + return null; + } + return token.hasLeadingTrivia() ? convertComments(token.leadingTrivia(text), token.fullStart()) : null; + } + ASTHelpers.convertTokenLeadingComments = convertTokenLeadingComments; + function convertTokenTrailingComments(token, text) { + if (token === null) { + return null; + } + return token.hasTrailingTrivia() ? convertComments(token.trailingTrivia(text), TypeScript.fullEnd(token) - token.trailingTriviaWidth(text)) : null; + } + ASTHelpers.convertTokenTrailingComments = convertTokenTrailingComments; + function convertComments(triviaList, commentStartPosition) { + var result = null; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result = result || []; + result.push(convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + commentStartPosition += trivia.fullWidth(); + } + return result; + } + function convertComment(trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia, hasTrailingNewLine, commentStartPosition, commentStartPosition + trivia.fullWidth()); + return comment; + } + function docComments(ast, text) { + if (isDeclarationAST(ast)) { + var comments = null; + if (ast.kind() === 225 /* VariableDeclarator */) { + comments = TypeScript.ASTHelpers.preComments(getVariableStatement(ast), text); + } + else if (ast.kind() === 242 /* Parameter */) { + comments = TypeScript.ASTHelpers.preComments(ast, text); + if (!comments) { + var previousToken = TypeScript.findToken(TypeScript.syntaxTree(ast).sourceUnit(), TypeScript.firstToken(ast).fullStart() - 1); + if (previousToken && (previousToken.kind() === 72 /* OpenParenToken */ || previousToken.kind() === 79 /* CommaToken */)) { + comments = convertTokenTrailingComments(previousToken, text); + } + } + } + else { + comments = TypeScript.ASTHelpers.preComments(ast, text); + } + if (comments && comments.length > 0) { + return comments.filter(function (c) { return isDocComment(c); }); + } + } + return sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + return false; + } + ASTHelpers.isDocComment = isDocComment; + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return getParameterList(ast.callSignature); + case 140 /* SetAccessor */: + return getParameterList(ast.callSignature); + } + } + return null; + } + ASTHelpers.getParameterList = getParameterList; + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.callSignature); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + return null; + } + ASTHelpers.getType = getType; + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + return null; + } + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.Syntax.emptyList(); + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; + } + ast = ast.parent; + } + return null; + } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + function isEntireNameOfModuleDeclaration(nameAST) { + return parentIsModuleDeclaration(nameAST) && nameAST.parent.name === nameAST; + } + function getModuleDeclarationFromNameAST(ast) { + if (ast) { + switch (ast.kind()) { + case 14 /* StringLiteral */: + if (parentIsModuleDeclaration(ast) && ast.parent.stringLiteral === ast) { + return ast.parent; + } + return null; + case 11 /* IdentifierName */: + case 121 /* QualifiedName */: + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + break; + default: + return null; + } + for (ast = ast.parent; ast && ast.kind() === 121 /* QualifiedName */; ast = ast.parent) { + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + } + } + return null; + } + ASTHelpers.getModuleDeclarationFromNameAST = getModuleDeclarationFromNameAST; + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } + else if (ast.name.kind() === 121 /* QualifiedName */) { + return astName === ast.name.right; + } + else { + return astName === ast.name; + } + } + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); + } + else { + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); + } + } + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + function getModuleNames(name, result) { + result = result || []; + if (name.kind() === 121 /* QualifiedName */) { + getModuleNames(name.left, result); + result.push(name.right); + } + else { + result.push(name); + } + return result; + } + ASTHelpers.getModuleNames = getModuleNames; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (markerBaseLength === void 0) { markerBaseLength = 0; } + var result = memberName.prefix; + if (memberName.isString()) { + result += memberName.text; + } + else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + result += memberName.suffix; + return result; + }; + MemberName.create = function (arg1, arg2, arg3) { + if (typeof arg1 === "string") { + return new MemberNameString(arg1); + } + else { + var result = new MemberNameArray(); + if (arg2) + result.prefix = arg2; + if (arg3) + result.suffix = arg3; + result.entries.push(arg1); + return result; + } + }; + return MemberName; + })(); + TypeScript.MemberName = MemberName; + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.call(this); + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + MemberNameArray.prototype.addAll = function (entries) { + for (var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripStartAndEndQuotes(str) { + var firstCharCode = str && str.charCodeAt(0); + if (str && str.length >= 2 && firstCharCode === str.charCodeAt(str.length - 1) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + return str.substring(1, str.length - 1); + } + return str; + } + TypeScript.stripStartAndEndQuotes = stripStartAndEndQuotes; + function isSingleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 39 /* singleQuote */; + } + TypeScript.isSingleQuoted = isSingleQuoted; + function isDoubleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 34 /* doubleQuote */; + } + TypeScript.isDoubleQuoted = isDoubleQuoted; + function isQuoted(str) { + return isDoubleQuoted(str) || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + var switchToForwardSlashesRegEx = /\\/g; + function switchToForwardSlashes(path) { + return path.replace(switchToForwardSlashesRegEx, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + function trimModName(modName) { + if (modName.length > 5 && modName.substring(modName.length - 5, modName.length) === ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if (modName.length > 3 && modName.substring(modName.length - 3, modName.length) === ".ts") { + return modName.substring(0, modName.length - 3); + } + if (modName.length > 3 && modName.substring(modName.length - 3, modName.length) === ".js") { + return modName.substring(0, modName.length - 3); + } + return modName; + } + TypeScript.trimModName = trimModName; + function getDeclareFilePath(fname) { + return isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) === invariantExt; + } + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + function getPrettyName(modPath, quote, treatAsFileName) { + if (quote === void 0) { quote = true; } + if (treatAsFileName === void 0) { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripStartAndEndQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath, isAbsoultePathURL) { + if (isAbsoultePathURL === void 0) { isAbsoultePathURL = true; } + absoluteModPath = switchToForwardSlashes(absoluteModPath); + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + var joinStartIndex = 0; + for (; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if (fixedModComponents[joinStartIndex] !== modComponents[joinStartIndex]) { + break; + } + } + if (joinStartIndex !== 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for (; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if (fixedModComponents[joinStartIndex] !== "") { + relativePath = relativePath + "../"; + } + } + return relativePath + relativePathComponents.join("/"); + } + if (isAbsoultePathURL && absoluteModPath.indexOf("://") === -1) { + absoluteModPath = "file:///" + absoluteModPath; + } + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + function changePathToDTS(modPath) { + return trimModName(stripStartAndEndQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + function isRelative(path) { + return path.length > 0 && path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.length > 0 && (path.charAt(0) === "\\" || path.charAt(0) === "/" || (path.indexOf(":\\") !== -1) || (path.indexOf(":/") !== -1)); + } + TypeScript.isRooted = isRooted; + function getRootFilePath(outFname) { + if (outFname === "") { + return outFname; + } + else { + var isPath = outFname.indexOf("/") !== -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + function convertToDirectoryPath(dirPath) { + if (dirPath && dirPath.charAt(dirPath.length - 1) !== "/") { + dirPath += "/"; + } + return dirPath; + } + TypeScript.convertToDirectoryPath = convertToDirectoryPath; + var normalizePathRegEx = /^\\\\[^\\]/; + function normalizePath(path) { + if (normalizePathRegEx.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + normalizedParts.push(part); + } + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var ts; +(function (ts) { + var scanner = ts.createScanner(1 /* ES5 */); + var emptyArray = []; + function createNode(kind, pos, end, flags, parent) { + var node = new (ts.getNodeConstructor(kind))(); + node.pos = pos; + node.end = end; + node.flags = flags; + node.parent = parent; + return node; + } + var NodeObject = (function () { + function NodeObject() { + } + NodeObject.prototype.getSourceFile = function () { + var node = this; + while (node.kind !== 177 /* SourceFile */) + node = node.parent; + return node; + }; + NodeObject.prototype.getStart = function () { + return ts.getTokenPosOfNode(this); + }; + NodeObject.prototype.getFullStart = function () { + return this.pos; + }; + NodeObject.prototype.getEnd = function () { + return this.end; + }; + NodeObject.prototype.getWidth = function () { + return this.getEnd() - this.getStart(); + }; + NodeObject.prototype.getFullWidth = function () { + return this.end - this.getFullStart(); + }; + NodeObject.prototype.getLeadingTriviaWidth = function () { + return this.getStart() - this.pos; + }; + NodeObject.prototype.getFullText = function () { + return this.getSourceFile().text.substring(this.pos, this.end); + }; + NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { + scanner.setTextPos(pos); + while (pos < end) { + var token = scanner.scan(); + var textPos = scanner.getTextPos(); + var node = nodes.push(createNode(token, pos, textPos, 256 /* Synthetic */, this)); + pos = textPos; + } + return pos; + }; + NodeObject.prototype.createSyntaxList = function (nodes) { + var list = createNode(179 /* SyntaxList */, nodes.pos, nodes.end, 256 /* Synthetic */, this); + list._children = []; + var pos = nodes.pos; + for (var i = 0, len = nodes.length; i < len; i++) { + var node = nodes[i]; + if (pos < node.pos) { + pos = this.addSyntheticNodes(list._children, pos, node.pos); + } + list._children.push(node); + pos = node.end; + } + if (pos < nodes.end) { + this.addSyntheticNodes(list._children, pos, nodes.end); + } + return list; + }; + NodeObject.prototype.createChildren = function () { + var _this = this; + if (this.kind > 111 /* Missing */) { + scanner.setText(this.getSourceFile().text); + var children = []; + var pos = this.pos; + var processNode = function (node) { + if (pos < node.pos) { + pos = _this.addSyntheticNodes(children, pos, node.pos); + } + children.push(node); + pos = node.end; + }; + var processNodes = function (nodes) { + if (pos < nodes.pos) { + pos = _this.addSyntheticNodes(children, pos, nodes.pos); + } + children.push(_this.createSyntaxList(nodes)); + pos = nodes.end; + }; + ts.forEachChild(this, processNode, processNodes); + if (pos < this.end) { + this.addSyntheticNodes(children, pos, this.end); + } + scanner.setText(undefined); + } + this._children = children || emptyArray; + }; + NodeObject.prototype.getChildCount = function () { + if (!this._children) + this.createChildren(); + return this._children.length; + }; + NodeObject.prototype.getChildAt = function (index) { + if (!this._children) + this.createChildren(); + return this._children[index]; + }; + NodeObject.prototype.getChildren = function () { + if (!this._children) + this.createChildren(); + return this._children; + }; + NodeObject.prototype.getFirstToken = function () { + var children = this.getChildren(); + for (var i = 0; i < children.length; i++) { + var child = children[i]; + if (child.kind < 111 /* Missing */) + return child; + if (child.kind > 111 /* Missing */) + return child.getFirstToken(); + } + }; + NodeObject.prototype.getLastToken = function () { + var children = this.getChildren(); + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + if (child.kind < 111 /* Missing */) + return child; + if (child.kind > 111 /* Missing */) + return child.getLastToken(); + } + }; + return NodeObject; + })(); + var SymbolObject = (function () { + function SymbolObject(flags, name) { + this.flags = flags; + this.name = name; + } + SymbolObject.prototype.getFlags = function () { + return this.flags; + }; + SymbolObject.prototype.getName = function () { + return this.name; + }; + SymbolObject.prototype.getDeclarations = function () { + return this.declarations; + }; + return SymbolObject; + })(); + var TypeObject = (function () { + function TypeObject(checker, flags) { + this.checker = checker; + this.flags = flags; + } + TypeObject.prototype.getFlags = function () { + return this.flags; + }; + TypeObject.prototype.getSymbol = function () { + return this.symbol; + }; + TypeObject.prototype.getProperties = function () { + return this.checker.getPropertiesOfType(this); + }; + TypeObject.prototype.getApparentProperties = function () { + return this.checker.getAugmentedPropertiesOfApparentType(this); + }; + TypeObject.prototype.getCallSignatures = function () { + return this.checker.getSignaturesOfType(this, 0 /* Call */); + }; + TypeObject.prototype.getConstructSignatures = function () { + return this.checker.getSignaturesOfType(this, 1 /* Construct */); + }; + TypeObject.prototype.getStringIndexType = function () { + return this.checker.getIndexTypeOfType(this, 0 /* String */); + }; + TypeObject.prototype.getNumberIndexType = function () { + return this.checker.getIndexTypeOfType(this, 1 /* Number */); + }; + return TypeObject; + })(); + var SignatureObject = (function () { + function SignatureObject(checker) { + this.checker = checker; + } + SignatureObject.prototype.getDeclaration = function () { + return this.declaration; + }; + SignatureObject.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + SignatureObject.prototype.getParameters = function () { + return this.parameters; + }; + SignatureObject.prototype.getReturnType = function () { + return this.checker.getReturnTypeOfSignature(this); + }; + return SignatureObject; + })(); + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(ts.EmitOutputResult || (ts.EmitOutputResult = {})); + var EmitOutputResult = ts.EmitOutputResult; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(ts.OutputFileType || (ts.OutputFileType = {})); + var OutputFileType = ts.OutputFileType; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["Start"] = 0] = "Start"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + })(ts.EndOfLineState || (ts.EndOfLineState = {})); + var EndOfLineState = ts.EndOfLineState; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + })(ts.TokenClass || (ts.TokenClass = {})); + var TokenClass = ts.TokenClass; + var ScriptElementKind = (function () { + function ScriptElementKind() { + } + ScriptElementKind.unknown = ""; + ScriptElementKind.keyword = "keyword"; + ScriptElementKind.scriptElement = "script"; + ScriptElementKind.moduleElement = "module"; + ScriptElementKind.classElement = "class"; + ScriptElementKind.interfaceElement = "interface"; + ScriptElementKind.enumElement = "enum"; + ScriptElementKind.variableElement = "var"; + ScriptElementKind.localVariableElement = "local var"; + ScriptElementKind.functionElement = "function"; + ScriptElementKind.localFunctionElement = "local function"; + ScriptElementKind.memberFunctionElement = "method"; + ScriptElementKind.memberGetAccessorElement = "getter"; + ScriptElementKind.memberSetAccessorElement = "setter"; + ScriptElementKind.memberVariableElement = "property"; + ScriptElementKind.constructorImplementationElement = "constructor"; + ScriptElementKind.callSignatureElement = "call"; + ScriptElementKind.indexSignatureElement = "index"; + ScriptElementKind.constructSignatureElement = "construct"; + ScriptElementKind.parameterElement = "parameter"; + ScriptElementKind.typeParameterElement = "type parameter"; + ScriptElementKind.primitiveType = "primitive type"; + return ScriptElementKind; + })(); + ts.ScriptElementKind = ScriptElementKind; + var ScriptElementKindModifier = (function () { + function ScriptElementKindModifier() { + } + ScriptElementKindModifier.none = ""; + ScriptElementKindModifier.publicMemberModifier = "public"; + ScriptElementKindModifier.privateMemberModifier = "private"; + ScriptElementKindModifier.exportedModifier = "export"; + ScriptElementKindModifier.ambientModifier = "declare"; + ScriptElementKindModifier.staticModifier = "static"; + return ScriptElementKindModifier; + })(); + ts.ScriptElementKindModifier = ScriptElementKindModifier; + var MatchKind = (function () { + function MatchKind() { + } + MatchKind.none = null; + MatchKind.exact = "exact"; + MatchKind.subString = "substring"; + MatchKind.prefix = "prefix"; + return MatchKind; + })(); + ts.MatchKind = MatchKind; + var DocumentObject = (function () { + function DocumentObject(compilationSettings, filename, referencedFiles, scriptSnapshot, byteOrderMark, version, _isOpen, syntaxTree, soruceFile) { + this.compilationSettings = compilationSettings; + this.filename = filename; + this.referencedFiles = referencedFiles; + this.scriptSnapshot = scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this._isOpen = _isOpen; + this.syntaxTree = syntaxTree; + this.soruceFile = soruceFile; + this.bloomFilter = null; + } + DocumentObject.prototype.getFilename = function () { + return this.filename; + }; + DocumentObject.prototype.getVersion = function () { + return this.version; + }; + DocumentObject.prototype.isOpen = function () { + return this._isOpen; + }; + DocumentObject.prototype.getByteOrderMark = function () { + return this.byteOrderMark; + }; + DocumentObject.prototype.isDeclareFile = function () { + return TypeScript.isDTSFile(this.filename); + }; + DocumentObject.prototype.getSourceUnit = function () { + return this.getSyntaxTree().sourceUnit(); + }; + DocumentObject.prototype.getLineMap = function () { + return this.getSyntaxTree().lineMap(); + }; + DocumentObject.prototype.getSyntaxTree = function () { + if (!this.syntaxTree) { + var start = new Date().getTime(); + this.syntaxTree = TypeScript.Parser.parse(this.filename, TypeScript.SimpleText.fromScriptSnapshot(this.scriptSnapshot), this.compilationSettings.target, this.isDeclareFile()); + var time = new Date().getTime() - start; + } + return this.syntaxTree; + }; + DocumentObject.prototype.getSourceFile = function () { + if (!this.soruceFile) { + var start = new Date().getTime(); + this.soruceFile = ts.createSourceFile(this.filename, this.scriptSnapshot.getText(0, this.scriptSnapshot.getLength()), this.compilationSettings.target); + var time = new Date().getTime() - start; + } + return this.soruceFile; + }; + DocumentObject.prototype.getBloomFilter = function () { + if (!this.bloomFilter) { + var identifiers = TypeScript.createIntrinsicsObject(); + var pre = function (cur) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { + if (cur.kind() === 11 /* IdentifierName */) { + var nodeText = TypeScript.tokenValueText(cur); + identifiers[nodeText] = true; + } + } + }; + TypeScript.getAstWalkerFactory().simpleWalk(this.getSourceUnit(), pre, null, identifiers); + var identifierCount = 0; + for (var name in identifiers) { + if (identifiers[name]) { + identifierCount++; + } + } + this.bloomFilter = new TypeScript.BloomFilter(identifierCount); + this.bloomFilter.addKeys(identifiers); + } + return this.bloomFilter; + }; + DocumentObject.prototype.emitToOwnOutputFile = function () { + return !this.compilationSettings.out || this.getSyntaxTree().isExternalModule(); + }; + DocumentObject.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { + var oldSyntaxTree = this.syntaxTree; + if (textChangeRange !== null && ts.Debug.shouldAssert(1 /* Normal */)) { + var oldText = this.scriptSnapshot; + var newText = scriptSnapshot; + TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); + if (ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); + var newTextPrefix = newText.getText(0, textChangeRange.span().start()); + TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); + var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); + TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null || DocumentObject.incrementalParse === null ? TypeScript.Parser.parse(this.filename, text, this.compilationSettings.target, TypeScript.isDTSFile(this.filename)) : DocumentObject.incrementalParse(oldSyntaxTree, textChangeRange, text); + return new DocumentObject(this.compilationSettings, this.filename, this.referencedFiles, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree, null); + }; + DocumentObject.incrementalParse = TypeScript.IncrementalParser.parse; + return DocumentObject; + })(); + function createDocument(compilationSettings, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + return new DocumentObject(compilationSettings, fileName, referencedFiles, scriptSnapshot, byteOrderMark, version, isOpen, null, null); + } + ts.createDocument = createDocument; + function getDefaultCompilerOptions() { + return { + target: 1 /* ES5 */, + module: 0 /* None */ + }; + } + ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) + return false; + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) + return false; + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; + var OperationCanceledException = (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + })(); + ts.OperationCanceledException = OperationCanceledException; + var CancellationTokenObject = (function () { + function CancellationTokenObject(cancellationToken) { + this.cancellationToken = cancellationToken; + } + CancellationTokenObject.prototype.isCancellationRequested = function () { + return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + }; + CancellationTokenObject.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new OperationCanceledException(); + } + }; + CancellationTokenObject.None = new CancellationTokenObject(null); + return CancellationTokenObject; + })(); + var HostCache = (function () { + function HostCache(host) { + this.host = host; + this.filenameToEntry = {}; + var filenames = host.getScriptFileNames(); + for (var i = 0, n = filenames.length; i < n; i++) { + var filename = filenames[i]; + this.filenameToEntry[TypeScript.switchToForwardSlashes(filename)] = { + filename: filename, + version: host.getScriptVersion(filename), + isOpen: host.getScriptIsOpen(filename), + byteOrderMark: host.getScriptByteOrderMark(filename) + }; + } + this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); + } + HostCache.prototype.compilationSettings = function () { + return this._compilationSettings; + }; + HostCache.prototype.getEntry = function (filename) { + filename = TypeScript.switchToForwardSlashes(filename); + return ts.lookUp(this.filenameToEntry, filename); + }; + HostCache.prototype.contains = function (filename) { + return !!this.getEntry(filename); + }; + HostCache.prototype.getHostfilename = function (filename) { + var hostCacheEntry = this.getEntry(filename); + if (hostCacheEntry) { + return hostCacheEntry.filename; + } + return filename; + }; + HostCache.prototype.getFilenames = function () { + var _this = this; + var fileNames = []; + ts.forEachKey(this.filenameToEntry, function (key) { + if (ts.hasProperty(_this.filenameToEntry, key)) + fileNames.push(key); + }); + return fileNames; + }; + HostCache.prototype.getVersion = function (filename) { + return this.getEntry(filename).version; + }; + HostCache.prototype.isOpen = function (filename) { + return this.getEntry(filename).isOpen; + }; + HostCache.prototype.getByteOrderMark = function (filename) { + return this.getEntry(filename).byteOrderMark; + }; + HostCache.prototype.getScriptSnapshot = function (filename) { + var file = this.getEntry(filename); + if (!file.sourceText) { + file.sourceText = this.host.getScriptSnapshot(file.filename); + } + return file.sourceText; + }; + HostCache.prototype.getScriptTextChangeRangeSinceVersion = function (filename, lastKnownVersion) { + var currentVersion = this.getVersion(filename); + if (lastKnownVersion === currentVersion) { + return TypeScript.TextChangeRange.unchanged; + } + var scriptSnapshot = this.getScriptSnapshot(filename); + return scriptSnapshot.getTextChangeRangeSinceVersion(lastKnownVersion); + }; + return HostCache; + })(); + var SyntaxTreeCache = (function () { + function SyntaxTreeCache(host) { + this.host = host; + this.currentfilename = ""; + this.currentFileVersion = -1; + this.currentFileSyntaxTree = null; + this.currentFileScriptSnapshot = null; + this.hostCache = new HostCache(host); + } + SyntaxTreeCache.prototype.getCurrentFileSyntaxTree = function (filename) { + this.hostCache = new HostCache(this.host); + var version = this.hostCache.getVersion(filename); + var syntaxTree = null; + if (this.currentFileSyntaxTree === null || this.currentfilename !== filename) { + var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); + syntaxTree = this.createSyntaxTree(filename, scriptSnapshot); + } + else if (this.currentFileVersion !== version) { + var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); + syntaxTree = this.updateSyntaxTree(filename, scriptSnapshot, this.currentFileSyntaxTree, this.currentFileVersion); + } + if (syntaxTree !== null) { + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentFileVersion = version; + this.currentfilename = filename; + this.currentFileSyntaxTree = syntaxTree; + } + return this.currentFileSyntaxTree; + }; + SyntaxTreeCache.prototype.getCurrentScriptSnapshot = function (filename) { + this.getCurrentFileSyntaxTree(filename); + return this.currentFileScriptSnapshot; + }; + SyntaxTreeCache.prototype.createSyntaxTree = function (filename, scriptSnapshot) { + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + var syntaxTree = TypeScript.Parser.parse(filename, text, getDefaultCompilerOptions().target, TypeScript.isDTSFile(filename)); + return syntaxTree; + }; + SyntaxTreeCache.prototype.updateSyntaxTree = function (filename, scriptSnapshot, previousSyntaxTree, previousFileVersion) { + var editRange = this.hostCache.getScriptTextChangeRangeSinceVersion(filename, previousFileVersion); + if (editRange === null) { + return this.createSyntaxTree(filename, scriptSnapshot); + } + var nextSyntaxTree = TypeScript.IncrementalParser.parse(previousSyntaxTree, editRange, TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot)); + this.ensureInvariants(filename, editRange, nextSyntaxTree, this.currentFileScriptSnapshot, scriptSnapshot); + return nextSyntaxTree; + }; + SyntaxTreeCache.prototype.ensureInvariants = function (filename, editRange, incrementalTree, oldScriptSnapshot, newScriptSnapshot) { + var expectedNewLength = oldScriptSnapshot.getLength() - editRange.span().length() + editRange.newLength(); + var actualNewLength = newScriptSnapshot.getLength(); + function provideMoreDebugInfo() { + var debugInformation = ["expected length:", expectedNewLength, "and actual length:", actualNewLength, "are not equal\r\n"]; + var oldSpan = editRange.span(); + function prettyPrintString(s) { + return '"' + s.replace(/\r/g, '\\r').replace(/\n/g, '\\n') + '"'; + } + debugInformation.push('Edit range (old text) (start: ' + oldSpan.start() + ', end: ' + oldSpan.end() + ') \r\n'); + debugInformation.push('Old text edit range contents: ' + prettyPrintString(oldScriptSnapshot.getText(oldSpan.start(), oldSpan.end()))); + var newSpan = editRange.newSpan(); + debugInformation.push('Edit range (new text) (start: ' + newSpan.start() + ', end: ' + newSpan.end() + ') \r\n'); + debugInformation.push('New text edit range contents: ' + prettyPrintString(newScriptSnapshot.getText(newSpan.start(), newSpan.end()))); + return debugInformation.join(' '); + } + ts.Debug.assert(expectedNewLength === actualNewLength, "Expected length is different from actual!", provideMoreDebugInfo); + if (ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldPrefixText = oldScriptSnapshot.getText(0, editRange.span().start()); + var newPrefixText = newScriptSnapshot.getText(0, editRange.span().start()); + ts.Debug.assert(oldPrefixText === newPrefixText, 'Expected equal prefix texts!'); + var oldSuffixText = oldScriptSnapshot.getText(editRange.span().end(), oldScriptSnapshot.getLength()); + var newSuffixText = newScriptSnapshot.getText(editRange.newSpan().end(), newScriptSnapshot.getLength()); + ts.Debug.assert(oldSuffixText === newSuffixText, 'Expected equal suffix texts!'); + var incrementalTreeText = TypeScript.fullText(incrementalTree.sourceUnit()); + var actualSnapshotText = newScriptSnapshot.getText(0, newScriptSnapshot.getLength()); + ts.Debug.assert(incrementalTreeText === actualSnapshotText, 'Expected full texts to be equal'); + } + }; + return SyntaxTreeCache; + })(); + function createDocumentRegistry() { + var buckets = {}; + function getKeyFromCompilationSettings(settings) { + return "_" + ts.ScriptTarget[settings.target]; + } + function getBucketForCompilationSettings(settings, createIfMissing) { + var key = getKeyFromCompilationSettings(settings); + var bucket = ts.lookUp(buckets, key); + if (!bucket && createIfMissing) { + buckets[key] = bucket = {}; + } + return bucket; + } + function reportStats() { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var entries = ts.lookUp(buckets, name); + var documents = []; + for (var i in entries) { + var entry = entries[i]; + documents.push({ + name: i, + refCount: entry.refCount, + references: entry.owners.slice(0) + }); + } + documents.sort(function (x, y) { return y.refCount - x.refCount; }); + return { bucket: name, documents: documents }; + }); + return JSON.stringify(bucketInfoArray, null, 2); + } + function acquireDocument(filename, compilationSettings, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (referencedFiles === void 0) { referencedFiles = []; } + var bucket = getBucketForCompilationSettings(compilationSettings, true); + var entry = ts.lookUp(bucket, filename); + if (!entry) { + var document = createDocument(compilationSettings, filename, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + bucket[filename] = entry = { + document: document, + refCount: 0, + owners: [] + }; + } + entry.refCount++; + return entry.document; + } + function updateDocument(document, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange) { + var bucket = getBucketForCompilationSettings(compilationSettings, false); + ts.Debug.assert(bucket); + var entry = ts.lookUp(bucket, filename); + ts.Debug.assert(entry); + if (entry.document.isOpen() === isOpen && entry.document.getVersion() === version) { + return entry.document; + } + entry.document = entry.document.update(scriptSnapshot, version, isOpen, textChangeRange); + return entry.document; + } + function releaseDocument(filename, compilationSettings) { + var bucket = getBucketForCompilationSettings(compilationSettings, false); + ts.Debug.assert(bucket); + var entry = ts.lookUp(bucket, filename); + entry.refCount--; + ts.Debug.assert(entry.refCount >= 0); + if (entry.refCount === 0) { + delete bucket[filename]; + } + } + return { + acquireDocument: acquireDocument, + updateDocument: updateDocument, + releaseDocument: releaseDocument, + reportStats: reportStats + }; + } + ts.createDocumentRegistry = createDocumentRegistry; + var keywordCompletions = []; + for (var i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) { + keywordCompletions.push({ + name: ts.tokenToString(i), + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none + }); + } + function createLanguageService(host, documentRegistry) { + var syntaxTreeCache = new SyntaxTreeCache(host); + var formattingRulesProvider; + var hostCache; + var program; + var typeChecker; + var useCaseSensitivefilenames = false; + var documentsByName = {}; + var documentRegistry = documentRegistry; + var cancellationToken = new CancellationTokenObject(host.getCancellationToken()); + var activeCompletionSession; + if (!TypeScript.LocalizedDiagnosticMessages) { + TypeScript.LocalizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); + } + function getDocument(filename) { + return ts.lookUp(documentsByName, filename); + } + function createCompilerHost() { + return { + getSourceFile: function (filename, languageVersion) { + var document = getDocument(filename); + ts.Debug.assert(!!document, "document can not be undefined"); + return document.getSourceFile(); + }, + getCancellationToken: function () { return cancellationToken; }, + getCanonicalFileName: function (filename) { return useCaseSensitivefilenames ? filename : filename.toLowerCase(); }, + useCaseSensitiveFileNames: function () { return useCaseSensitivefilenames; }, + getNewLine: function () { return "\r\n"; }, + getDefaultLibFilename: function () { + throw Error("TOD:: getDefaultLibfilename"); + }, + writeFile: function (filename, data) { + throw Error("TODO: write file"); + }, + getCurrentDirectory: function () { + throw Error("TODO: getCurrentDirectory"); + } + }; + } + function synchronizeHostData() { + hostCache = new HostCache(host); + var compilationSettings = hostCache.compilationSettings(); + var oldProgram = program; + if (oldProgram) { + var oldSettings = program.getCompilerOptions(); + var settingsChangeAffectsSyntax = oldSettings.target !== compilationSettings.target || oldSettings.module !== compilationSettings.module; + var changesInCompilationSettingsAffectSyntax = oldSettings && compilationSettings && !compareDataObjects(oldSettings, compilationSettings) && settingsChangeAffectsSyntax; + var oldSourceFiles = program.getSourceFiles(); + for (var i = 0, n = oldSourceFiles.length; i < n; i++) { + cancellationToken.throwIfCancellationRequested(); + var filename = oldSourceFiles[i].filename; + if (!hostCache.contains(filename) || changesInCompilationSettingsAffectSyntax) { + documentRegistry.releaseDocument(filename, oldSettings); + delete documentsByName[filename]; + } + } + } + var hostfilenames = hostCache.getFilenames(); + for (var i = 0, n = hostfilenames.length; i < n; i++) { + var filename = hostfilenames[i]; + var version = hostCache.getVersion(filename); + var isOpen = hostCache.isOpen(filename); + var scriptSnapshot = hostCache.getScriptSnapshot(filename); + var document = getDocument(filename); + if (document) { + if (document.getVersion() === version && document.isOpen() === isOpen) { + continue; + } + var textChangeRange = null; + if (document.isOpen && isOpen) { + textChangeRange = hostCache.getScriptTextChangeRangeSinceVersion(filename, document.getVersion()); + } + document = documentRegistry.updateDocument(document, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange); + } + else { + document = documentRegistry.acquireDocument(filename, compilationSettings, scriptSnapshot, hostCache.getByteOrderMark(filename), version, isOpen, []); + } + documentsByName[filename] = document; + } + program = ts.createProgram(hostfilenames, compilationSettings, createCompilerHost()); + typeChecker = program.getTypeChecker(); + } + function dispose() { + if (program) { + ts.forEach(program.getSourceFiles(), function (f) { + documentRegistry.releaseDocument(f.filename, program.getCompilerOptions()); + }); + } + } + function getSyntacticDiagnostics(filename) { + synchronizeHostData(); + return program.getDiagnostics(program.getSourceFile(filename)); + } + function getSemanticDiagnostics(filename) { + synchronizeHostData(); + return typeChecker.getDiagnostics(program.getSourceFile(filename)); + } + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return program.getGlobalDiagnostics(); + } + function getValidCompletionEntryDisplayName(displayName, target) { + if (displayName && displayName.length > 0) { + var firstChar = displayName.charCodeAt(0); + if (firstChar === 39 /* singleQuote */ || firstChar === 34 /* doubleQuote */) { + displayName = TypeScript.stripStartAndEndQuotes(displayName); + } + if (TypeScript.Scanner.isValidIdentifier(TypeScript.SimpleText.fromString(displayName), target)) { + return displayName; + } + } + return undefined; + } + function createCompletionEntry(symbol) { + var displayName = getValidCompletionEntryDisplayName(symbol.getName(), program.getCompilerOptions().target); + if (!displayName) { + return undefined; + } + var declarations = symbol.getDeclarations(); + var firstDeclaration = [0]; + return { + name: displayName, + kind: getSymbolKind(symbol), + kindModifiers: declarations ? getNodeModifiers(declarations[0]) : ScriptElementKindModifier.none + }; + } + function getCompletionsAtPosition(filename, position, isMemberCompletion) { + function getCompletionEntriesFromSymbols(symbols, session) { + ts.forEach(symbols, function (symbol) { + var entry = createCompletionEntry(symbol); + if (entry) { + session.entries.push(entry); + session.symbols[entry.name] = symbol; + } + }); + } + function isCompletionListBlocker(sourceUnit, position) { + if (position < 0 || position > TypeScript.fullWidth(sourceUnit)) { + return true; + } + return TypeScript.Syntax.isEntirelyInsideComment(sourceUnit, position) || TypeScript.Syntax.isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) || isIdentifierDefinitionLocation(sourceUnit, position) || isRightOfIllegalDot(sourceUnit, position); + } + function getContainingObjectLiteralApplicableForCompletion(sourceUnit, position) { + var previousToken = getNonIdentifierCompleteTokenOnLeft(sourceUnit, position); + if (previousToken) { + var parent = previousToken.parent; + switch (previousToken.kind()) { + case 70 /* OpenBraceToken */: + case 79 /* CommaToken */: + if (parent && parent.kind() === 2 /* SeparatedList */) { + parent = parent.parent; + } + if (parent && parent.kind() === 215 /* ObjectLiteralExpression */) { + return parent; + } + break; + } + } + return undefined; + } + function isIdentifierDefinitionLocation(sourceUnit, position) { + var positionedToken = getNonIdentifierCompleteTokenOnLeft(sourceUnit, position); + if (positionedToken) { + var containingNodeKind = TypeScript.Syntax.containingNode(positionedToken) && TypeScript.Syntax.containingNode(positionedToken).kind(); + switch (positionedToken.kind()) { + case 79 /* CommaToken */: + return containingNodeKind === 227 /* ParameterList */ || containingNodeKind === 224 /* VariableDeclaration */ || containingNodeKind === 132 /* EnumDeclaration */; + case 72 /* OpenParenToken */: + return containingNodeKind === 227 /* ParameterList */ || containingNodeKind === 236 /* CatchClause */; + case 70 /* OpenBraceToken */: + return containingNodeKind === 132 /* EnumDeclaration */; + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 77 /* DotDotDotToken */: + return containingNodeKind === 242 /* Parameter */; + case 44 /* ClassKeyword */: + case 65 /* ModuleKeyword */: + case 46 /* EnumKeyword */: + case 52 /* InterfaceKeyword */: + case 27 /* FunctionKeyword */: + case 40 /* VarKeyword */: + case 64 /* GetKeyword */: + case 68 /* SetKeyword */: + return true; + } + switch (positionedToken.text()) { + case "class": + case "interface": + case "enum": + case "module": + return true; + } + } + return false; + } + function getNonIdentifierCompleteTokenOnLeft(sourceUnit, position) { + var positionedToken = TypeScript.Syntax.findCompleteTokenOnLeft(sourceUnit, position, true); + if (positionedToken && position === TypeScript.end(positionedToken) && positionedToken.kind() == 10 /* EndOfFileToken */) { + positionedToken = TypeScript.previousToken(positionedToken, true); + } + if (positionedToken && position === TypeScript.end(positionedToken) && positionedToken.kind() === 11 /* IdentifierName */) { + positionedToken = TypeScript.previousToken(positionedToken, true); + } + return positionedToken; + } + function isRightOfIllegalDot(sourceUnit, position) { + var positionedToken = getNonIdentifierCompleteTokenOnLeft(sourceUnit, position); + if (positionedToken) { + switch (positionedToken.kind()) { + case 76 /* DotToken */: + var leftOfDotPositionedToken = TypeScript.previousToken(positionedToken, true); + return leftOfDotPositionedToken && leftOfDotPositionedToken.kind() === 13 /* NumericLiteral */; + case 13 /* NumericLiteral */: + var text = positionedToken.text(); + return text.charAt(text.length - 1) === "."; + } + } + return false; + } + synchronizeHostData(); + filename = TypeScript.switchToForwardSlashes(filename); + var document = getDocument(filename); + var sourceUnit = document.getSourceUnit(); + if (isCompletionListBlocker(document.getSyntaxTree().sourceUnit(), position)) { + host.log("Returning an empty list because completion was blocked."); + return null; + } + var node = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position, true, true); + if (node && node.kind() === 11 /* IdentifierName */ && TypeScript.start(node) === TypeScript.end(node)) { + node = node.parent; + } + var isRightOfDot = false; + if (node && node.kind() === 212 /* MemberAccessExpression */ && TypeScript.end(node.expression) < position) { + isRightOfDot = true; + node = node.expression; + } + else if (node && node.kind() === 121 /* QualifiedName */ && TypeScript.end(node.left) < position) { + isRightOfDot = true; + node = node.left; + } + else if (node && node.parent && node.kind() === 11 /* IdentifierName */ && node.parent.kind() === 212 /* MemberAccessExpression */ && node.parent.name === node) { + isRightOfDot = true; + node = node.parent.expression; + } + else if (node && node.parent && node.kind() === 11 /* IdentifierName */ && node.parent.kind() === 121 /* QualifiedName */ && node.parent.right === node) { + isRightOfDot = true; + node = node.parent.left; + } + var mappedNode = getNodeAtPosition(document.getSourceFile(), TypeScript.end(node) - 1); + ts.Debug.assert(mappedNode, "Could not map a Fidelity node to an AST node"); + activeCompletionSession = { + filename: filename, + position: position, + entries: [], + symbols: {}, + location: mappedNode, + typeChecker: typeChecker + }; + if (isRightOfDot) { + var type = typeChecker.getTypeOfExpression(mappedNode); + if (!type) { + return undefined; + } + var symbols = type.getApparentProperties(); + isMemberCompletion = true; + getCompletionEntriesFromSymbols(symbols, activeCompletionSession); + } + else { + var containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(document.getSyntaxTree().sourceUnit(), position); + if (containingObjectLiteral) { + var searchPosition = Math.min(position, TypeScript.end(containingObjectLiteral)); + var path = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, searchPosition); + while (node && node.kind() !== 215 /* ObjectLiteralExpression */) { + node = node.parent; + } + if (!node || node.kind() !== 215 /* ObjectLiteralExpression */) { + return null; + } + isMemberCompletion = true; + } + else { + isMemberCompletion = false; + var symbolMeanings = ts.SymbolFlags.Type | ts.SymbolFlags.Value | ts.SymbolFlags.Namespace; + var symbols = typeChecker.getSymbolsInScope(mappedNode, symbolMeanings); + getCompletionEntriesFromSymbols(symbols, activeCompletionSession); + } + } + if (!isMemberCompletion) { + Array.prototype.push.apply(activeCompletionSession.entries, keywordCompletions); + } + return { + isMemberCompletion: isMemberCompletion, + entries: activeCompletionSession.entries + }; + } + function getCompletionEntryDetails(filename, position, entryName) { + filename = TypeScript.switchToForwardSlashes(filename); + var session = activeCompletionSession; + if (!session || session.filename !== filename || session.position !== position) { + return undefined; + } + var symbol = ts.lookUp(activeCompletionSession.symbols, entryName); + if (symbol) { + var type = session.typeChecker.getTypeOfSymbol(symbol); + ts.Debug.assert(type, "Could not find type for symbol"); + var completionEntry = createCompletionEntry(symbol); + return { + name: entryName, + kind: completionEntry.kind, + kindModifiers: completionEntry.kindModifiers, + type: session.typeChecker.typeToString(type, session.location), + fullSymbolName: typeChecker.symbolToString(symbol, session.location), + docComment: "" + }; + } + else { + return { + name: entryName, + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none, + type: undefined, + fullSymbolName: entryName, + docComment: undefined + }; + } + } + function getNodeAtPosition(sourceFile, position) { + var current = sourceFile; + outer: while (true) { + for (var i = 0, n = current.getChildCount(); i < n; i++) { + var child = current.getChildAt(i); + if (child.getStart() <= position && position < child.getEnd()) { + current = child; + continue outer; + } + if (child.end > position) + break; + } + return current; + } + } + function getEnclosingDeclaration(node) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 116 /* Method */: + case 167 /* FunctionDeclaration */: + case 136 /* FunctionExpression */: + case 118 /* GetAccessor */: + case 119 /* SetAccessor */: + case 169 /* ClassDeclaration */: + case 170 /* InterfaceDeclaration */: + case 171 /* EnumDeclaration */: + case 172 /* ModuleDeclaration */: + return node; + } + } + } + function getSymbolKind(symbol) { + var flags = symbol.getFlags(); + if (flags & ts.SymbolFlags.Module) + return ScriptElementKind.moduleElement; + if (flags & 16 /* Class */) + return ScriptElementKind.classElement; + if (flags & 32 /* Interface */) + return ScriptElementKind.interfaceElement; + if (flags & 64 /* Enum */) + return ScriptElementKind.enumElement; + if (flags & 1 /* Variable */) + return ScriptElementKind.variableElement; + if (flags & 8 /* Function */) + return ScriptElementKind.functionElement; + if (flags & 8192 /* GetAccessor */) + return ScriptElementKind.memberGetAccessorElement; + if (flags & 16384 /* SetAccessor */) + return ScriptElementKind.memberSetAccessorElement; + if (flags & 2048 /* Method */) + return ScriptElementKind.memberFunctionElement; + if (flags & 2 /* Property */) + return ScriptElementKind.memberVariableElement; + if (flags & 131072 /* IndexSignature */) + return ScriptElementKind.indexSignatureElement; + if (flags & 65536 /* ConstructSignature */) + return ScriptElementKind.constructSignatureElement; + if (flags & 32768 /* CallSignature */) + return ScriptElementKind.callSignatureElement; + if (flags & 4096 /* Constructor */) + return ScriptElementKind.constructorImplementationElement; + if (flags & 262144 /* TypeParameter */) + return ScriptElementKind.typeParameterElement; + if (flags & 4 /* EnumMember */) + return ScriptElementKind.variableElement; + return ScriptElementKind.unknown; + } + function getTypeKind(type) { + var flags = type.getFlags(); + if (flags & 128 /* Enum */) + return ScriptElementKind.enumElement; + if (flags & 1024 /* Class */) + return ScriptElementKind.classElement; + if (flags & 2048 /* Interface */) + return ScriptElementKind.interfaceElement; + if (flags & 512 /* TypeParameter */) + return ScriptElementKind.typeParameterElement; + if (flags & ts.TypeFlags.Intrinsic) + return ScriptElementKind.primitiveType; + if (flags & 256 /* StringLiteral */) + return ScriptElementKind.primitiveType; + return ScriptElementKind.unknown; + } + function getNodeModifiers(node) { + var flags = node.flags; + var result = []; + if (flags & 32 /* Private */) + result.push(ScriptElementKindModifier.privateMemberModifier); + if (flags & 16 /* Public */) + result.push(ScriptElementKindModifier.publicMemberModifier); + if (flags & 64 /* Static */) + result.push(ScriptElementKindModifier.staticModifier); + if (flags & 1 /* Export */) + result.push(ScriptElementKindModifier.exportedModifier); + if (ts.isInAmbientContext(node)) + result.push(ScriptElementKindModifier.ambientModifier); + return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none; + } + function getTypeAtPosition(filename, position) { + synchronizeHostData(); + filename = TypeScript.switchToForwardSlashes(filename); + var document = getDocument(filename); + var node = getNodeAtPosition(document.getSourceFile(), position); + if (!node) + return undefined; + switch (node.kind) { + case 55 /* Identifier */: + if (node.parent.kind === 132 /* CallExpression */ || node.parent.kind === 133 /* NewExpression */) { + } + var symbol = typeChecker.getSymbolOfIdentifier(node); + ts.Debug.assert(symbol, "getTypeAtPosition: Could not find symbol for node"); + var type = typeChecker.getTypeOfSymbol(symbol); + return { + memberName: new TypeScript.MemberNameString(typeChecker.typeToString(type)), + docComment: "", + fullSymbolName: typeChecker.symbolToString(symbol, getEnclosingDeclaration(node)), + kind: getSymbolKind(symbol), + minChar: node.pos, + limChar: node.end + }; + case 83 /* ThisKeyword */: + case 112 /* QualifiedName */: + case 81 /* SuperKeyword */: + case 3 /* StringLiteral */: + var type = typeChecker.getTypeOfExpression(node); + ts.Debug.assert(type, "getTypeAtPosition: Could not find type for node"); + return { + memberName: new TypeScript.MemberNameString(""), + docComment: "", + fullSymbolName: typeChecker.typeToString(type, getEnclosingDeclaration(node)), + kind: getTypeKind(type), + minChar: node.pos, + limChar: node.end + }; + break; + } + } + function getSyntaxTree(filename) { + filename = TypeScript.switchToForwardSlashes(filename); + return syntaxTreeCache.getCurrentFileSyntaxTree(filename); + } + function getNameOrDottedNameSpan(filename, startPos, endPos) { + function getTypeInfoEligiblePath(filename, position, isConstructorValidPosition) { + var sourceUnit = syntaxTreeCache.getCurrentFileSyntaxTree(filename).sourceUnit(); + var ast = TypeScript.ASTHelpers.getAstAtPosition(sourceUnit, position, false, true); + if (ast === null) { + return null; + } + if (ast.kind() === 227 /* ParameterList */ && ast.parent.kind() === 142 /* CallSignature */ && ast.parent.parent.kind() === 137 /* ConstructorDeclaration */) { + ast = ast.parent.parent; + } + switch (ast.kind()) { + default: + return null; + case 137 /* ConstructorDeclaration */: + var constructorAST = ast; + if (!isConstructorValidPosition || !(position >= TypeScript.start(constructorAST) && position <= TypeScript.start(constructorAST) + "constructor".length)) { + return null; + } + else { + return ast; + } + case 129 /* FunctionDeclaration */: + return null; + case 212 /* MemberAccessExpression */: + case 121 /* QualifiedName */: + case 50 /* SuperKeyword */: + case 14 /* StringLiteral */: + case 35 /* ThisKeyword */: + case 11 /* IdentifierName */: + return ast; + } + } + filename = TypeScript.switchToForwardSlashes(filename); + var node = getTypeInfoEligiblePath(filename, startPos, false); + if (!node) + return null; + while (node) { + if (TypeScript.ASTHelpers.isNameOfMemberAccessExpression(node) || TypeScript.ASTHelpers.isRightSideOfQualifiedName(node)) { + node = node.parent; + } + else { + break; + } + } + return { + minChar: TypeScript.start(node), + limChar: TypeScript.end(node) + }; + } + function getBreakpointStatementAtPosition(filename, position) { + filename = TypeScript.switchToForwardSlashes(filename); + var syntaxtree = getSyntaxTree(filename); + return TypeScript.Services.Breakpoints.getBreakpointLocation(syntaxtree, position); + } + function getScriptLexicalStructure(filename) { + filename = TypeScript.switchToForwardSlashes(filename); + var syntaxTree = getSyntaxTree(filename); + var items = []; + TypeScript.Services.GetScriptLexicalStructureWalker.getListsOfAllScriptLexicalStructure(items, filename, syntaxTree.sourceUnit()); + return items; + } + function getOutliningRegions(filename) { + filename = TypeScript.switchToForwardSlashes(filename); + var syntaxTree = getSyntaxTree(filename); + return TypeScript.Services.OutliningElementsCollector.collectElements(syntaxTree.sourceUnit()); + } + function getBraceMatchingAtPosition(filename, position) { + filename = TypeScript.switchToForwardSlashes(filename); + var syntaxTree = getSyntaxTree(filename); + return TypeScript.Services.BraceMatcher.getMatchSpans(syntaxTree, position); + } + function getIndentationAtPosition(filename, position, editorOptions) { + filename = TypeScript.switchToForwardSlashes(filename); + var syntaxTree = getSyntaxTree(filename); + var scriptSnapshot = syntaxTreeCache.getCurrentScriptSnapshot(filename); + var scriptText = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + var textSnapshot = new TypeScript.Services.Formatting.TextSnapshot(scriptText); + var options = new TypeScript.FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter); + return TypeScript.Services.Formatting.SingleTokenIndenter.getIndentationAmount(position, syntaxTree.sourceUnit(), textSnapshot, options); + } + function getFormattingManager(filename, options) { + if (formattingRulesProvider == null) { + formattingRulesProvider = new TypeScript.Services.Formatting.RulesProvider(host); + } + formattingRulesProvider.ensureUpToDate(options); + var syntaxTree = getSyntaxTree(filename); + var scriptSnapshot = syntaxTreeCache.getCurrentScriptSnapshot(filename); + var scriptText = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + var textSnapshot = new TypeScript.Services.Formatting.TextSnapshot(scriptText); + var manager = new TypeScript.Services.Formatting.FormattingManager(syntaxTree, textSnapshot, formattingRulesProvider, options); + return manager; + } + function getFormattingEditsForRange(filename, minChar, limChar, options) { + filename = TypeScript.switchToForwardSlashes(filename); + var manager = getFormattingManager(filename, options); + return manager.formatSelection(minChar, limChar); + } + function getFormattingEditsForDocument(filename, minChar, limChar, options) { + filename = TypeScript.switchToForwardSlashes(filename); + var manager = getFormattingManager(filename, options); + return manager.formatDocument(minChar, limChar); + } + function getFormattingEditsOnPaste(filename, minChar, limChar, options) { + filename = TypeScript.switchToForwardSlashes(filename); + var manager = getFormattingManager(filename, options); + return manager.formatOnPaste(minChar, limChar); + } + function getFormattingEditsAfterKeystroke(filename, position, key, options) { + filename = TypeScript.switchToForwardSlashes(filename); + var manager = getFormattingManager(filename, options); + if (key === "}") + return manager.formatOnClosingCurlyBrace(position); + else if (key === ";") + return manager.formatOnSemicolon(position); + else if (key === "\n") + return manager.formatOnEnter(position); + else + return []; + } + return { + dispose: dispose, + refresh: function () { + }, + cleanupSemanticCache: function () { + }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getCompletionsAtPosition: getCompletionsAtPosition, + getCompletionEntryDetails: getCompletionEntryDetails, + getTypeAtPosition: getTypeAtPosition, + getSignatureAtPosition: function (filename, position) { return undefined; }, + getDefinitionAtPosition: function (filename, position) { return []; }, + getReferencesAtPosition: function (filename, position) { return []; }, + getOccurrencesAtPosition: function (filename, position) { return []; }, + getImplementorsAtPosition: function (filename, position) { return []; }, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: function (searchValue) { return []; }, + getScriptLexicalStructure: getScriptLexicalStructure, + getOutliningRegions: getOutliningRegions, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsOnPaste: getFormattingEditsOnPaste, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getEmitOutput: function (filename) { return undefined; } + }; + } + ts.createLanguageService = createLanguageService; + function createClassifier(host) { + var scanner; + var lastDiagnosticKey = null; + var noRegexTable; + var reportDiagnostic = function (position, fullWidth, key, args) { + lastDiagnosticKey = key; + }; + if (!noRegexTable) { + noRegexTable = []; + noRegexTable[11 /* IdentifierName */] = true; + noRegexTable[14 /* StringLiteral */] = true; + noRegexTable[13 /* NumericLiteral */] = true; + noRegexTable[12 /* RegularExpressionLiteral */] = true; + noRegexTable[35 /* ThisKeyword */] = true; + noRegexTable[93 /* PlusPlusToken */] = true; + noRegexTable[94 /* MinusMinusToken */] = true; + noRegexTable[73 /* CloseParenToken */] = true; + noRegexTable[75 /* CloseBracketToken */] = true; + noRegexTable[71 /* CloseBraceToken */] = true; + noRegexTable[37 /* TrueKeyword */] = true; + noRegexTable[24 /* FalseKeyword */] = true; + } + function getClassificationsForLine(text, lexState) { + var offset = 0; + if (lexState !== 0 /* Start */) { + if (lexState === 3 /* InDoubleQuoteStringLiteral */) { + text = '"\\\n' + text; + } + else if (lexState === 2 /* InSingleQuoteStringLiteral */) { + text = "'\\\n" + text; + } + else if (lexState === 1 /* InMultiLineCommentTrivia */) { + text = "/*\n" + text; + } + offset = 3; + } + var result = { + finalLexState: 0 /* Start */, + entries: [] + }; + var simpleText = TypeScript.SimpleText.fromString(text); + scanner = TypeScript.Scanner.createScanner(1 /* ES5 */, simpleText, reportDiagnostic); + var lastTokenKind = 0 /* None */; + var token = null; + do { + lastDiagnosticKey = null; + token = scanner.scan(!noRegexTable[lastTokenKind]); + lastTokenKind = token.kind(); + processToken(text, simpleText, offset, token, result); + } while (token.kind() !== 10 /* EndOfFileToken */); + lastDiagnosticKey = null; + return result; + } + function processToken(text, simpleText, offset, token, result) { + processTriviaList(text, offset, token.leadingTrivia(simpleText), result); + addResult(text, offset, result, TypeScript.width(token), token.kind()); + processTriviaList(text, offset, token.trailingTrivia(simpleText), result); + if (TypeScript.fullEnd(token) >= text.length) { + if (lastDiagnosticKey === TypeScript.DiagnosticCode.AsteriskSlash_expected) { + result.finalLexState = 1 /* InMultiLineCommentTrivia */; + return; + } + if (token.kind() === 14 /* StringLiteral */) { + var tokenText = token.text(); + if (tokenText.length > 0 && tokenText.charCodeAt(tokenText.length - 1) === 92 /* backslash */) { + var quoteChar = tokenText.charCodeAt(0); + result.finalLexState = quoteChar === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; + return; + } + } + } + } + function processTriviaList(text, offset, triviaList, result) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + addResult(text, offset, result, trivia.fullWidth(), trivia.kind()); + } + } + function addResult(text, offset, result, length, kind) { + if (length > 0) { + if (result.entries.length === 0) { + length -= offset; + } + result.entries.push({ length: length, classification: classFromKind(kind) }); + } + } + function classFromKind(kind) { + if (TypeScript.SyntaxFacts.isAnyKeyword(kind)) { + return 1 /* Keyword */; + } + else if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(kind) || TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(kind)) { + return 2 /* Operator */; + } + else if (TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return 0 /* Punctuation */; + } + switch (kind) { + case 4 /* WhitespaceTrivia */: + return 4 /* Whitespace */; + case 6 /* MultiLineCommentTrivia */: + case 7 /* SingleLineCommentTrivia */: + return 3 /* Comment */; + case 13 /* NumericLiteral */: + return 6 /* NumberLiteral */; + case 14 /* StringLiteral */: + return 7 /* StringLiteral */; + case 12 /* RegularExpressionLiteral */: + return 8 /* RegExpLiteral */; + case 11 /* IdentifierName */: + default: + return 5 /* Identifier */; + } + } + return { + getClassificationsForLine: getClassificationsForLine + }; + } + ts.createClassifier = createClassifier; + function initializeServices() { + ts.objectAllocator = { + getNodeConstructor: function (kind) { + function Node() { + } + var proto = new NodeObject(); + proto.kind = kind; + proto.pos = 0; + proto.end = 0; + proto.flags = 0; + proto.parent = undefined; + Node.prototype = proto; + return Node; + }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; } + }; + } + initializeServices(); +})(ts || (ts = {})); +var TypeScript; +(function (TypeScript) { + function isNoDefaultLibMatch(comment) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + return isNoDefaultLibRegex.exec(comment); + } + TypeScript.tripleSlashReferenceRegExp = /^(\/\/\/\s*/; + function getFileReferenceFromReferencePath(fileName, text, position, comment, diagnostics) { + var lineMap = text.lineMap(); + var simpleReferenceRegEx = /^\/\/\/\s*= 7 && fullReference[6] === "true"; + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } + } + } + return null; + } + var reportDiagnostic = function () { + }; + function processImports(text, scanner, token, importedFiles) { + var lineChar = { line: -1, character: -1 }; + var lineMap = text.lineMap(); + var start = new Date().getTime(); + while (token.kind() !== 10 /* EndOfFileToken */) { + if (token.kind() === 49 /* ImportKeyword */) { + var importToken = token; + token = scanner.scan(false); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(false); + if (token.kind() === 107 /* EqualsToken */) { + token = scanner.scan(false); + if (token.kind() === 65 /* ModuleKeyword */ || token.kind() === 66 /* RequireKeyword */) { + token = scanner.scan(false); + if (token.kind() === 72 /* OpenParenToken */) { + token = scanner.scan(false); + lineMap.fillLineAndCharacterFromPosition(TypeScript.start(importToken, text), lineChar); + if (token.kind() === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: TypeScript.start(token, text), + length: TypeScript.width(token), + path: TypeScript.stripStartAndEndQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + token = scanner.scan(false); + } + var totalTime = new Date().getTime() - start; + } + function processTripleSlashDirectives(fileName, text, firstToken) { + var leadingTrivia = firstToken.leadingTrivia(text); + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + var diagnostics = []; + var referencedFiles = []; + var lineMap = text.lineMap(); + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(fileName, text, position, triviaText, diagnostics); + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + referencedFiles.push(referencedCode); + } + var isNoDefaultLib = isNoDefaultLibMatch(triviaText); + if (isNoDefaultLib) { + noDefaultLib = isNoDefaultLib[3] === "true"; + } + } + position += trivia.fullWidth(); + } + return { noDefaultLib: noDefaultLib, diagnostics: diagnostics, referencedFiles: referencedFiles }; + } + function preProcessFile(fileName, sourceText, readImportFiles) { + if (readImportFiles === void 0) { readImportFiles = true; } + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = TypeScript.Scanner.createScanner(1 /* ES5 */, text, reportDiagnostic); + var firstToken = scanner.scan(false); + var importedFiles = []; + if (readImportFiles) { + processImports(text, scanner, firstToken, importedFiles); + } + var properties = processTripleSlashDirectives(fileName, text, firstToken); + return { referencedFiles: properties.referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib, diagnostics: properties.diagnostics }; + } + TypeScript.preProcessFile = preProcessFile; + function getReferencedFiles(fileName, sourceText) { + return preProcessFile(fileName, sourceText, false).referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; +})(TypeScript || (TypeScript = {})); +var debugObjectHost = this; +var ts; +(function (ts) { + var LanguageVersion; + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(LanguageVersion || (LanguageVersion = {})); + var ModuleGenTarget; + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Unspecified"] = 0] = "Unspecified"; + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 1] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 2] = "Asynchronous"; + })(ModuleGenTarget || (ModuleGenTarget = {})); + function languageVersionToScriptTarget(languageVersion) { + if (typeof languageVersion === "undefined") + return undefined; + switch (languageVersion) { + case 0 /* EcmaScript3 */: + return 0 /* ES3 */; + case 1 /* EcmaScript5 */: + return 1 /* ES5 */; + default: + throw Error("unsuported LanguageVersion value: " + languageVersion); + } + } + function moduleGenTargetToModuleKind(moduleGenTarget) { + if (typeof moduleGenTarget === "undefined") + return undefined; + switch (moduleGenTarget) { + case 2 /* Asynchronous */: + return 2 /* AMD */; + case 1 /* Synchronous */: + return 1 /* CommonJS */; + case 0 /* Unspecified */: + return 0 /* None */; + default: + throw Error("unsuported ModuleGenTarget value: " + moduleGenTarget); + } + } + function scriptTargetTolanguageVersion(scriptTarget) { + if (typeof scriptTarget === "undefined") + return undefined; + switch (scriptTarget) { + case 0 /* ES3 */: + return 0 /* EcmaScript3 */; + case 1 /* ES5 */: + return 1 /* EcmaScript5 */; + default: + throw Error("unsuported ScriptTarget value: " + scriptTarget); + } + } + function moduleKindToModuleGenTarget(moduleKind) { + if (typeof moduleKind === "undefined") + return undefined; + switch (moduleKind) { + case 2 /* AMD */: + return 2 /* Asynchronous */; + case 1 /* CommonJS */: + return 1 /* Synchronous */; + case 0 /* None */: + return 0 /* Unspecified */; + default: + throw Error("unsuported ModuleKind value: " + moduleKind); + } + } + function compilationSettingsToCompilerOptions(settings) { + var options = {}; + options.removeComments = settings.removeComments; + options.noResolve = settings.noResolve; + options.noImplicitAny = settings.noImplicitAny; + options.noLib = settings.noLib; + options.target = languageVersionToScriptTarget(settings.codeGenTarget); + options.module = moduleGenTargetToModuleKind(settings.moduleGenTarget); + options.out = settings.outFileOption; + options.outDir = settings.outDirOption; + options.sourceMap = settings.mapSourceFiles; + options.mapRoot = settings.mapRoot; + options.sourceRoot = settings.sourceRoot; + options.declaration = settings.generateDeclarationFiles; + options.codepage = settings.codepage; + return options; + } + function compilerOptionsToCompilationSettings(options) { + var settings = {}; + settings.removeComments = options.removeComments; + settings.noResolve = options.noResolve; + settings.noImplicitAny = options.noImplicitAny; + settings.noLib = options.noLib; + settings.codeGenTarget = scriptTargetTolanguageVersion(options.target); + settings.moduleGenTarget = moduleKindToModuleGenTarget(options.module); + settings.outFileOption = options.out; + settings.outDirOption = options.outDir; + settings.mapSourceFiles = options.sourceMap; + settings.mapRoot = options.mapRoot; + settings.sourceRoot = options.sourceRoot; + settings.generateDeclarationFiles = options.declaration; + settings.codepage = options.codepage; + return settings; + } + function logInternalError(logger, err) { + logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + } + var ScriptSnapshotShimAdapter = (function () { + function ScriptSnapshotShimAdapter(scriptSnapshotShim) { + this.scriptSnapshotShim = scriptSnapshotShim; + this.lineStartPositions = null; + } + ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { + return this.scriptSnapshotShim.getText(start, end); + }; + ScriptSnapshotShimAdapter.prototype.getLength = function () { + return this.scriptSnapshotShim.getLength(); + }; + ScriptSnapshotShimAdapter.prototype.getLineStartPositions = function () { + if (this.lineStartPositions == null) { + this.lineStartPositions = JSON.parse(this.scriptSnapshotShim.getLineStartPositions()); + } + return this.lineStartPositions; + }; + ScriptSnapshotShimAdapter.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + var encoded = this.scriptSnapshotShim.getTextChangeRangeSinceVersion(scriptVersion); + if (encoded == null) { + return null; + } + var decoded = JSON.parse(encoded); + return new TypeScript.TextChangeRange(new TypeScript.TextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + }; + return ScriptSnapshotShimAdapter; + })(); + var LanguageServiceShimHostAdapter = (function () { + function LanguageServiceShimHostAdapter(shimHost) { + this.shimHost = shimHost; + } + LanguageServiceShimHostAdapter.prototype.information = function () { + return this.shimHost.information(); + }; + LanguageServiceShimHostAdapter.prototype.debug = function () { + return this.shimHost.debug(); + }; + LanguageServiceShimHostAdapter.prototype.warning = function () { + return this.shimHost.warning(); + }; + LanguageServiceShimHostAdapter.prototype.error = function () { + return this.shimHost.error(); + }; + LanguageServiceShimHostAdapter.prototype.fatal = function () { + return this.shimHost.fatal(); + }; + LanguageServiceShimHostAdapter.prototype.log = function (s) { + this.shimHost.log(s); + }; + LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { + var settingsJson = this.shimHost.getCompilationSettings(); + if (settingsJson == null || settingsJson == "") { + throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + return null; + } + var options = compilationSettingsToCompilerOptions(JSON.parse(settingsJson)); + options.noResolve = true; + return options; + }; + LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { + var encoded = this.shimHost.getScriptFileNames(); + return JSON.parse(encoded); + }; + LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { + return new ScriptSnapshotShimAdapter(this.shimHost.getScriptSnapshot(fileName)); + }; + LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { + return this.shimHost.getScriptVersion(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getScriptIsOpen = function (fileName) { + return this.shimHost.getScriptIsOpen(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getScriptByteOrderMark = function (fileName) { + return this.shimHost.getScriptByteOrderMark(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () { + var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") { + return null; + } + try { + return JSON.parse(diagnosticMessagesJson); + } + catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + }; + LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () { + return this.shimHost.getCancellationToken(); + }; + return LanguageServiceShimHostAdapter; + })(); + function simpleForwardCall(logger, actionDescription, action) { + logger.log(actionDescription); + var start = Date.now(); + var result = action(); + var end = Date.now(); + logger.log(actionDescription + " completed in " + (end - start) + " msec"); + if (typeof (result) === "string") { + var str = result; + if (str.length > 128) { + str = str.substring(0, 128) + "..."; + } + logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + } + return result; + } + function forwardJSONCall(logger, actionDescription, action) { + try { + var result = simpleForwardCall(logger, actionDescription, action); + return JSON.stringify({ result: result }); + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + return JSON.stringify({ canceled: true }); + } + logInternalError(logger, err); + err.description = actionDescription; + return JSON.stringify({ error: err }); + } + } + var ShimBase = (function () { + function ShimBase(factory) { + this.factory = factory; + factory.registerShim(this); + } + ShimBase.prototype.dispose = function (dummy) { + this.factory.unregisterShim(this); + }; + return ShimBase; + })(); + var LanguageServiceShimObject = (function (_super) { + __extends(LanguageServiceShimObject, _super); + function LanguageServiceShimObject(factory, host, languageService) { + _super.call(this, factory); + this.host = host; + this.languageService = languageService; + this.logger = this.host; + } + LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action); + }; + LanguageServiceShimObject.prototype.dispose = function (dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + _super.prototype.dispose.call(this, dummy); + }; + LanguageServiceShimObject.prototype.refresh = function (throwOnError) { + var _this = this; + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { + _this.languageService.refresh(); + return null; + }); + }; + LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { + var _this = this; + this.forwardJSONCall("cleanupSemanticCache()", function () { + _this.languageService.cleanupSemanticCache(); + return null; + }); + }; + LanguageServiceShimObject.realizeDiagnostic = function (diagnostic) { + return { + message: diagnostic.messageText, + start: diagnostic.start, + length: diagnostic.length, + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase() + }; + }; + LanguageServiceShimObject.prototype.realizeDiagnosticWithFileName = function (diagnostic) { + return { + fileName: diagnostic.file.filename, + message: diagnostic.messageText, + start: diagnostic.start, + length: diagnostic.length, + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase() + }; + }; + LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSyntacticDiagnostics(\"" + fileName + "\")", function () { + var errors = _this.languageService.getSyntacticDiagnostics(fileName); + return errors.map(LanguageServiceShimObject.realizeDiagnostic); + }); + }; + LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSemanticDiagnostics(\"" + fileName + "\")", function () { + var errors = _this.languageService.getSemanticDiagnostics(fileName); + return errors.map(LanguageServiceShimObject.realizeDiagnostic); + }); + }; + LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { + var _this = this; + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { + var errors = _this.languageService.getCompilerOptionsDiagnostics(); + return errors.map(function (d) { return _this.realizeDiagnosticWithFileName(d); }); + }); + }; + LanguageServiceShimObject.prototype.getTypeAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeAtPosition(\"" + fileName + "\", " + position + ")", function () { + var typeInfo = _this.languageService.getTypeAtPosition(fileName, position); + return typeInfo; + }); + }; + LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { + var _this = this; + return this.forwardJSONCall("getNameOrDottedNameSpan(\"" + fileName + "\", " + startPos + ", " + endPos + ")", function () { + var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); + return spanInfo; + }); + }; + LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBreakpointStatementAtPosition(\"" + fileName + "\", " + position + ")", function () { + var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); + return spanInfo; + }); + }; + LanguageServiceShimObject.prototype.getSignatureAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getSignatureAtPosition(\"" + fileName + "\", " + position + ")", function () { + var signatureInfo = _this.languageService.getSignatureAtPosition(fileName, position); + return signatureInfo; + }); + }; + LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAtPosition(\"" + fileName + "\", " + position + ")", function () { + return _this.languageService.getDefinitionAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBraceMatchingAtPosition(\"" + fileName + "\", " + position + ")", function () { + var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); + return textRanges; + }); + }; + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options) { + var _this = this; + return this.forwardJSONCall("getIndentationAtPosition(\"" + fileName + "\", " + position + ")", function () { + var localOptions = JSON.parse(options); + var columnOffset = _this.languageService.getIndentationAtPosition(fileName, position, localOptions); + return { value: columnOffset }; + }); + }; + LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getReferencesAtPosition(\"" + fileName + "\", " + position + ")", function () { + return _this.languageService.getReferencesAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getOccurrencesAtPosition(\"" + fileName + "\", " + position + ")", function () { + return _this.languageService.getOccurrencesAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getImplementorsAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getImplementorsAtPosition(\"" + fileName + "\", " + position + ")", function () { + return _this.languageService.getImplementorsAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, isMemberCompletion) { + var _this = this; + return this.forwardJSONCall("getCompletionsAtPosition(\"" + fileName + "\", " + position + ", " + isMemberCompletion + ")", function () { + var completion = _this.languageService.getCompletionsAtPosition(fileName, position, isMemberCompletion); + return completion; + }); + }; + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + var _this = this; + return this.forwardJSONCall("getCompletionEntryDetails(\"" + fileName + "\", " + position + ", " + entryName + ")", function () { + var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); + return details; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, minChar, limChar, options) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForRange(\"" + fileName + "\", " + minChar + ", " + limChar + ")", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsForRange(fileName, minChar, limChar, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, minChar, limChar, options) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForDocument(\"" + fileName + "\", " + minChar + ", " + limChar + ")", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsForDocument(fileName, minChar, limChar, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsOnPaste = function (fileName, minChar, limChar, options) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsOnPaste(\"" + fileName + "\", " + minChar + ", " + limChar + ")", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsOnPaste(fileName, minChar, limChar, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsAfterKeystroke(\"" + fileName + "\", " + position + ", \"" + key + "\")", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue) { + var _this = this; + return this.forwardJSONCall("getNavigateToItems(\"" + searchValue + "\")", function () { + var items = _this.languageService.getNavigateToItems(searchValue); + var result = _this._navigateToItemsToString(items); + return result; + }); + }; + LanguageServiceShimObject.prototype.getScriptLexicalStructure = function (fileName) { + var _this = this; + return this.forwardJSONCall("getScriptLexicalStructure(\"" + fileName + "\")", function () { + var items = _this.languageService.getScriptLexicalStructure(fileName); + var result = _this._navigateToItemsToString(items); + return result; + }); + }; + LanguageServiceShimObject.prototype.getOutliningRegions = function (fileName) { + var _this = this; + return this.forwardJSONCall("getOutliningRegions(\"" + fileName + "\")", function () { + var items = _this.languageService.getOutliningRegions(fileName); + return items; + }); + }; + LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { + var _this = this; + return this.forwardJSONCall("getEmitOutput(\"" + fileName + "\")", function () { + var output = _this.languageService.getEmitOutput(fileName); + return output; + }); + }; + LanguageServiceShimObject.prototype._navigateToItemsToString = function (items) { + var result = []; + for (var i = 0; i < items.length; i++) { + var item = items[i]; + result.push({ + name: item.name, + kind: item.kind, + kindModifiers: item.kindModifiers, + containerName: item.containerName, + containerKind: item.containerKind, + matchKind: item.matchKind, + fileName: item.fileName, + minChar: item.minChar, + limChar: item.limChar, + additionalSpans: item.additionalSpans ? item.additionalSpans.map(function (i) { + return { start: i.minChar, end: i.limChar }; + }) : undefined + }); + } + return result; + }; + return LanguageServiceShimObject; + })(ShimBase); + var ClassifierShimObject = (function (_super) { + __extends(ClassifierShimObject, _super); + function ClassifierShimObject(factory, host) { + _super.call(this, factory); + this.host = host; + this.classifier = ts.createClassifier(this.host); + } + ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState) { + var classification = this.classifier.getClassificationsForLine(text, lexState); + var items = classification.entries; + var result = ""; + for (var i = 0; i < items.length; i++) { + result += items[i].length + "\n"; + result += items[i].classification + "\n"; + } + result += classification.finalLexState; + return result; + }; + return ClassifierShimObject; + })(ShimBase); + var CoreServicesShimObject = (function (_super) { + __extends(CoreServicesShimObject, _super); + function CoreServicesShimObject(factory, host) { + _super.call(this, factory); + this.host = host; + } + CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.host, actionDescription, action); + }; + CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceText) { + return this.forwardJSONCall("getPreProcessedFileInfo(\"" + fileName + "\")", function () { + var result = TypeScript.preProcessFile(fileName, sourceText); + return result; + }); + }; + CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { + return compilerOptionsToCompilationSettings(ts.getDefaultCompilerOptions()); + }); + }; + return CoreServicesShimObject; + })(ShimBase); + var TypeScriptServicesFactory = (function () { + function TypeScriptServicesFactory() { + this._shims = []; + this.documentRegistry = ts.createDocumentRegistry(); + } + TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { + try { + var hostAdapter = new LanguageServiceShimHostAdapter(host); + var pullLanguageService = ts.createLanguageService(hostAdapter, this.documentRegistry); + return new LanguageServiceShimObject(this, host, pullLanguageService); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createClassifierShim = function (host) { + try { + return new ClassifierShimObject(this, host); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) { + try { + return new CoreServicesShimObject(this, host); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.close = function () { + this._shims = []; + this.documentRegistry = ts.createDocumentRegistry(); + }; + TypeScriptServicesFactory.prototype.registerShim = function (shim) { + this._shims.push(shim); + }; + TypeScriptServicesFactory.prototype.unregisterShim = function (shim) { + for (var i = 0, n = this._shims.length; i < n; i++) { + if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + } + throw TypeScript.Errors.invalidOperation(); + }; + return TypeScriptServicesFactory; + })(); + ts.TypeScriptServicesFactory = TypeScriptServicesFactory; +})(ts || (ts = {})); +var TypeScript; +(function (TypeScript) { + (function (Services) { + Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; + })(TypeScript.Services || (TypeScript.Services = {})); + var Services = TypeScript.Services; +})(TypeScript || (TypeScript = {})); From 30509f1ecc8d44d10a4645fb94d7b58f6466fac9 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 1 Aug 2014 18:54:26 -0700 Subject: [PATCH 21/29] Changed messages, got rid of 'oldProgram'. --- .../diagnosticInformationMap.generated.ts | 4 ++-- src/compiler/diagnosticMessages.json | 4 ++-- src/compiler/sys.ts | 2 +- src/compiler/tc.ts | 15 +++++++++------ 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index a3b85cfb013..c1319edd442 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -217,8 +217,8 @@ module ts { Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: DiagnosticCategory.Error, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: DiagnosticCategory.Error, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, Version_0: { code: 6029, category: DiagnosticCategory.Message, key: "Version {0}" }, - File_Changed_Compiling: { code: 6032, category: DiagnosticCategory.Message, key: "File Changed. Compiling." }, - Compile_complete_Listening_for_changed_files: { code: 6042, category: DiagnosticCategory.Message, key: "Compile complete. Listening for changed files." }, + File_change_detected_Compiling: { code: 6032, category: DiagnosticCategory.Message, key: "File change detected. Compiling..." }, + Compilation_complete_Watching_for_file_changes: { code: 6042, category: DiagnosticCategory.Message, key: "Compilation complete. Watching for file changes." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 9ace46f4202..fac4ba6732f 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -862,11 +862,11 @@ "category": "Message", "code": 6029 }, - "File Changed. Compiling.": { + "File change detected. Compiling...": { "category": "Message", "code": 6032 }, - "Compile complete. Listening for changed files.": { + "Compilation complete. Watching for file changes.": { "category": "Message", "code": 6042 }, diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 03d517476cd..564f22b9f08 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -199,7 +199,7 @@ var sys: System = (function () { close() { _fs.unwatchFile(fileName, fileChanged); } }; - function fileChanged(curr:any, prev:any) { + function fileChanged(curr: any, prev: any) { if (+curr.mtime <= +prev.mtime) { return; } diff --git a/src/compiler/tc.ts b/src/compiler/tc.ts index fc508ed459c..0cfa89a01c9 100644 --- a/src/compiler/tc.ts +++ b/src/compiler/tc.ts @@ -231,7 +231,7 @@ module ts { // Compile the program the first time and watch all given/referenced files. var program = compile(commandLine, compilerHost).program; - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compile_complete_Listening_for_changed_files)); + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes)); addWatchers(program); return; @@ -272,11 +272,14 @@ module ts { } function recompile(changedFiles: Map) { - var oldProgram = program; - reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_Changed_Compiling)); + reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Compiling)); // Remove all the watchers, since we may not be watching every file // specified since the last recompilation cycle. - removeWatchers(oldProgram); + removeWatchers(program); + + // Release the old program. + var getUnmodifiedSourceFile = program.getSourceFile; + program = undefined; // We create a new compiler host for this compilation cycle. // This new host is effectively the same except that 'getSourceFile' @@ -285,7 +288,7 @@ module ts { var newCompilerHost = clone(compilerHost); newCompilerHost.getSourceFile = (fileName, languageVersion, onError) => { if (!hasProperty(changedFiles, fileName)) { - var sourceFile = oldProgram.getSourceFile(fileName); + var sourceFile = getUnmodifiedSourceFile(fileName); if (sourceFile) { return sourceFile; } @@ -295,7 +298,7 @@ module ts { }; program = compile(commandLine, newCompilerHost).program; - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compile_complete_Listening_for_changed_files)); + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes)); addWatchers(program); } } From 5a8eff848bf2819726f11c78fb53891075ff1a13 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Sat, 2 Aug 2014 12:03:25 -0700 Subject: [PATCH 22/29] Minor edits, no longer release 'program' Edited comments, no longer releasing 'program' as it is potentially confusing and doesn't buy us a heck of a lot anyway. --- src/compiler/tc.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/compiler/tc.ts b/src/compiler/tc.ts index 0cfa89a01c9..e347269fb30 100644 --- a/src/compiler/tc.ts +++ b/src/compiler/tc.ts @@ -273,13 +273,12 @@ module ts { function recompile(changedFiles: Map) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Compiling)); - // Remove all the watchers, since we may not be watching every file - // specified since the last recompilation cycle. + // Remove all the watchers, as we may not be watching every file + // specified since the last compilation cycle. removeWatchers(program); - // Release the old program. + // Gets us syntactically correct files from the last compilation. var getUnmodifiedSourceFile = program.getSourceFile; - program = undefined; // We create a new compiler host for this compilation cycle. // This new host is effectively the same except that 'getSourceFile' From 116401b2c859c1248ea2afe8c1a0cf361bf8ca19 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 3 Aug 2014 15:53:06 -0700 Subject: [PATCH 23/29] Addressing CR feedback. checkImplicitAny now returns void. --- src/compiler/checker.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 99b4d776b43..36ab4a7b142 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1108,27 +1108,28 @@ module ts { if (declaration.initializer) { var unwidenedType = checkAndMarkExpression(declaration.initializer); var type = getWidenedType(unwidenedType); - return type !== unwidenedType ? checkImplicitAny(type) : type; + if (type !== unwidenedType) { + checkImplicitAny(type); + } + return type; } - // Rest parameter defaults to type any[] - if (declaration.flags & NodeFlags.Rest) { - return checkImplicitAny(createArrayType(anyType)); - } - // Other parameters default to type any - return checkImplicitAny(anyType); + // Rest parameters default to type any[], other parameters default to type any + var type = declaration.flags & NodeFlags.Rest ? createArrayType(anyType) : anyType; + checkImplicitAny(type); + return type; - function checkImplicitAny(type: Type): Type { + function checkImplicitAny(type: Type) { if (!program.getCompilerOptions().noImplicitAny) { - return type; + return; } // We need to have ended up with 'any', 'any[]', 'any[][]', etc. if (getInnermostTypeOfNestedArrayTypes(type) !== anyType) { - return type; + return; } // Ignore privates within ambient contexts; they exist purely for documentative purposes to avoid name clashing. // (e.g. privates within .d.ts files do not expose type information) if (isPrivateWithinAmbient(declaration) || (declaration.kind === SyntaxKind.Parameter && isPrivateWithinAmbient(declaration.parent))) { - return type; + return; } switch (declaration.kind) { case SyntaxKind.Property: @@ -1143,7 +1144,6 @@ module ts { var diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } error(declaration, diagnostic, identifierToString(declaration.name), typeToString(type)); - return type; } } From 1e586134f71604aa367752e319820df2ab4fd576 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 4 Aug 2014 11:18:00 -0700 Subject: [PATCH 24/29] Removing trailing comma that breaks cscript.exe. --- src/compiler/commandLineParser.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 7a3e27b8a02..00aa5efcee4 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -34,7 +34,7 @@ module ts { { name: "sourceRoot", type: "string" }, { name: "target", type: { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5 }, error: Diagnostics.Argument_for_target_option_must_be_es3_or_es5 }, { name: "version", type: "boolean" }, - { name: "watch", type: "boolean" }, + { name: "watch", type: "boolean" } ]; // Map command line switches to compiler options' property descriptors. Keys must be lower case spellings of command line switches. From 2b26e3797642c396a1e70c787dd3ffe2b0e2cc06 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 4 Aug 2014 11:40:56 -0700 Subject: [PATCH 25/29] Addressing CR feedback. --- src/compiler/checker.ts | 2 +- src/compiler/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 36ab4a7b142..e9370005df7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3416,7 +3416,7 @@ module ts { } // Return contextual type of parameter or undefined if no contextual type is available - function getContextuallyTypedParameterType(parameter: VariableDeclaration): Type { + function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type { var func = parameter.parent; if (func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction) { if (isContextSensitiveExpression(func)) { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 78f462230f3..359896c9e4b 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -320,7 +320,7 @@ module ts { } export interface Expression extends Node { - contextualType?: Type; + contextualType?: Type; // Used to temporarily assign a contextual type during overload resolution } export interface UnaryExpression extends Expression { From 6b2a970ff32a109e855bf9f5ad2208515106c85e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 4 Aug 2014 11:58:32 -0700 Subject: [PATCH 26/29] Fix duplicate getTypeOfExpression function. --- src/compiler/checker.ts | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8f76127af76..731f5abf9e0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3437,11 +3437,6 @@ module ts { return unknownType; } - function getTypeOfExpression(node: Expression): Type { - // TODO: Optimize by caching type in NodeLinks? - return checkExpression(node); - } - // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type { var func = parameter.parent; @@ -3502,13 +3497,13 @@ module ts { var operator = binaryExpression.operator; if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); + return checkExpression(binaryExpression.left); } } else if (operator === SyntaxKind.BarBarToken) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); + type = checkExpression(binaryExpression.left); } return type; } From aa75de9c70ec2f316eb81336841f790322b9f4aa Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 4 Aug 2014 11:45:35 -0700 Subject: [PATCH 27/29] Consolidate Document and SoruceFile --- src/compiler/parser.ts | 6 +- src/compiler/tc.ts | 2 +- src/compiler/types.ts | 4 + src/harness/fourslash.ts | 6 +- src/harness/harness.ts | 4 +- src/harness/harnessLanguageService.ts | 9 +- src/harness/projectsRunner.ts | 4 +- src/harness/rwcRunner.ts | 2 +- src/services/services.ts | 329 ++++++++++++-------------- 9 files changed, 168 insertions(+), 198 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 6902ebc4835..4bd1a826567 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -417,7 +417,7 @@ module ts { nodeIsNestedInLabel(label: Identifier, requireIterationStatement: boolean, stopAtFunctionBoundary: boolean): ControlBlockContext; } - export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget): SourceFile { + export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, byteOrderMark: ByteOrderMark, version: number = 0, isOpen: boolean = false): SourceFile { var file: SourceFile; var scanner: Scanner; var token: SyntaxKind; @@ -3523,6 +3523,10 @@ module ts { file.externalModuleIndicator = getExternalModuleIndicator(); file.nodeCount = nodeCount; file.identifierCount = identifierCount; + file.version = version; + file.byteOrderMark = byteOrderMark; + file.isOpen = isOpen; + file.languageVersion = languageVersion; return file; } diff --git a/src/compiler/tc.ts b/src/compiler/tc.ts index e564002d03f..cbe9bcee6df 100644 --- a/src/compiler/tc.ts +++ b/src/compiler/tc.ts @@ -135,7 +135,7 @@ module ts { } text = ""; } - return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; + return text !== undefined ? createSourceFile(filename, text, languageVersion, ByteOrderMark.None) : undefined; } function writeFile(fileName: string, data: string, onError?: (message: string) => void) { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 10a358f379d..3411b3d2104 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -525,6 +525,10 @@ module ts { nodeCount: number; identifierCount: number; symbolCount: number; + byteOrderMark: ByteOrderMark; + isOpen: boolean; + version: number; + languageVersion: ScriptTarget; } export interface Program { diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 30b70f1631e..25cc615c8e0 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1895,12 +1895,12 @@ module FourSlash { var result = ''; var fourslashFilename = 'fourslash.ts'; var tsFn = 'tests/cases/fourslash/' + fourslashFilename; - fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), ts.ScriptTarget.ES5); - libdtsSourceFile = libdtsSourceFile || ts.createSourceFile('lib.d.ts', Harness.Compiler.libTextMinimal, ts.ScriptTarget.ES3); + fourslashSourceFile = fourslashSourceFile || ts.createSourceFile(tsFn, Harness.IO.readFile(tsFn), ts.ScriptTarget.ES5, ts.ByteOrderMark.None, /*version*/ 0, /*isOpen*/ false); + libdtsSourceFile = libdtsSourceFile || ts.createSourceFile('lib.d.ts', Harness.Compiler.libTextMinimal, ts.ScriptTarget.ES3, ts.ByteOrderMark.None, /*version*/ 0, /*isOpen*/ false); var files: { [filename: string]: ts.SourceFile; } = {}; files[fourslashFilename] = fourslashSourceFile; - files[fileName] = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5); + files[fileName] = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5, ts.ByteOrderMark.None, /*version*/ 0, /*isOpen*/ false); files['lib.d.ts'] = libdtsSourceFile; var host = Harness.Compiler.createCompilerHost(files, (fn, contents) => result = contents); diff --git a/src/harness/harness.ts b/src/harness/harness.ts index f90d096f536..b77514611d5 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -544,7 +544,7 @@ module Harness { } else { var lib = 'lib.d.ts'; if (fn.substr(fn.length - lib.length) === lib) { - return filemap[fn] = ts.createSourceFile('lib.d.ts', libTextMinimal, languageVersion); + return filemap[fn] = ts.createSourceFile('lib.d.ts', libTextMinimal, languageVersion, ts.ByteOrderMark.None); } // Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC return null; @@ -720,7 +720,7 @@ module Harness { var filemap: { [name: string]: ts.SourceFile; } = {}; var register = (file: { unitName: string; content: string; }) => { var filename = Path.switchToForwardSlashes(file.unitName); - filemap[filename] = ts.createSourceFile(filename, file.content, options.target); + filemap[filename] = ts.createSourceFile(filename, file.content, options.target, ts.ByteOrderMark.None); }; inputFiles.forEach(register); otherFiles.forEach(register); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index e3646b98e03..400cae2abe1 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -147,20 +147,19 @@ module Harness.LanguageService { scriptSnapshot: TypeScript.IScriptSnapshot, byteOrderMark: ts.ByteOrderMark, version: number, - isOpen: boolean, - referencedFiles: string[]= []): ts.Document { - return ts.createDocument(compilationSettings, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + isOpen: boolean): ts.SourceFile { + return ts.createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), compilationSettings.target, byteOrderMark, version, isOpen); } public updateDocument( - document: ts.Document, + document: ts.SourceFile, fileName: string, compilationSettings: ts.CompilerOptions, scriptSnapshot: TypeScript.IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange - ): ts.Document { + ): ts.SourceFile { return document.update(scriptSnapshot, version, isOpen, textChangeRange); } diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index f3fc650e55c..e6ec6d6f9de 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -139,7 +139,7 @@ class ProjectRunner extends RunnerBase { function getSourceFile(filename: string, languageVersion: ts.ScriptTarget): ts.SourceFile { var sourceFile: ts.SourceFile = undefined; if (filename === 'lib.d.ts') { - sourceFile = ts.createSourceFile('lib.d.ts', Harness.Compiler.libTextMinimal, languageVersion); + sourceFile = ts.createSourceFile('lib.d.ts', Harness.Compiler.libTextMinimal, languageVersion, ts.ByteOrderMark.None); } else { assert.isTrue(!ts.filter(readInputFiles, sourceFile => sourceFile.filename == filename).length, "Compiler trying to read same file again: " + filename); @@ -154,7 +154,7 @@ class ProjectRunner extends RunnerBase { } if (text !== undefined) { - sourceFile = ts.createSourceFile(filename, text, languageVersion) + sourceFile = ts.createSourceFile(filename, text, languageVersion, ts.ByteOrderMark.None); } } diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts index 576b06e3435..98006cd6bce 100644 --- a/src/harness/rwcRunner.ts +++ b/src/harness/rwcRunner.ts @@ -107,7 +107,7 @@ module RWC { catch (e) { // Leave fileContents undefined; } - return ts.createSourceFile(fileName, fileContents, languageVersion); + return ts.createSourceFile(fileName, fileContents, languageVersion, ts.ByteOrderMark.None); }, getDefaultLibFilename: () => libPath, writeFile: (fn, contents) => emitterIOHost.writeFile(fn, contents, false), diff --git a/src/services/services.ts b/src/services/services.ts index 1c60f2c6ba0..ef0526442e9 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -67,6 +67,13 @@ module ts { getReturnType(): Type; } + export interface SourceFile { + getSourceUnit(): TypeScript.SourceUnitSyntax; + getSyntaxTree(): TypeScript.SyntaxTree; + getBloomFilter(): TypeScript.BloomFilter; + update(scriptSnapshot: TypeScript.IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange): SourceFile; + } + var scanner: Scanner = createScanner(ScriptTarget.ES5); var emptyArray: any [] = []; @@ -81,7 +88,6 @@ module ts { } class NodeObject implements Node { - public kind: SyntaxKind; public pos: number; public end: number; @@ -294,6 +300,130 @@ module ts { } } + var incrementalParse: IncrementalParse = TypeScript.IncrementalParser.parse; + + class SourceFileObject extends NodeObject implements SourceFile { + public filename: string; + public text: string; + public getLineAndCharacterFromPosition(position: number): { line: number; character: number } { return null; } + public amdDependencies: string[]; + public referencedFiles: FileReference[]; + public syntacticErrors: Diagnostic[]; + public semanticErrors: Diagnostic[]; + public hasNoDefaultLib: boolean; + public externalModuleIndicator: Node; // The first node that causes this file to be an external module + public nodeCount: number; + public identifierCount: number; + public symbolCount: number; + public statements: NodeArray; + public byteOrderMark: ByteOrderMark; + public version: number; + public isOpen: boolean; + public languageVersion: ScriptTarget; + + private bloomFilter: TypeScript.BloomFilter; + private syntaxTree: TypeScript.SyntaxTree; + private scriptSnapshot: TypeScript.IScriptSnapshot; + + public getSourceUnit(): TypeScript.SourceUnitSyntax { + // If we don't have a script, create one from our parse tree. + return this.getSyntaxTree().sourceUnit(); + } + + public getLineMap(): TypeScript.LineMap { + return this.getSyntaxTree().lineMap(); + } + + 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 getBloomFilter(): TypeScript.BloomFilter { + if (!this.bloomFilter) { + var identifiers = TypeScript.createIntrinsicsObject(); + var pre = function (cur: TypeScript.ISyntaxElement) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { + if (cur.kind() === TypeScript.SyntaxKind.IdentifierName) { + var nodeText = TypeScript.tokenValueText((cur)); + + identifiers[nodeText] = true; + } + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(this.getSourceUnit(), pre, null, identifiers); + + var identifierCount = 0; + for (var name in identifiers) { + if (identifiers[name]) { + identifierCount++; + } + } + + this.bloomFilter = new TypeScript.BloomFilter(identifierCount); + this.bloomFilter.addKeys(identifiers); + } + return this.bloomFilter; + } + + public update(scriptSnapshot: TypeScript.IScriptSnapshot, version: number, 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 accidently realize + // the old syntax tree. + var oldSyntaxTree = this.syntaxTree; + + if (textChangeRange !== null && Debug.shouldAssert(AssertionLevel.Normal)) { + var oldText = this.scriptSnapshot; + var newText = scriptSnapshot; + + TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); + + if (Debug.shouldAssert(AssertionLevel.VeryAggressive)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); + var newTextPrefix = newText.getText(0, textChangeRange.span().start()); + TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); + + var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); + var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); + TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + + 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 === null || oldSyntaxTree === null + ? TypeScript.Parser.parse(this.filename, text, this.languageVersion, TypeScript.isDTSFile(this.filename)) + : TypeScript.IncrementalParser.parse(oldSyntaxTree, textChangeRange, text); + + return SourceFileObject.createSourceFileObject(this.languageVersion, this.filename, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree); + } + + public static createSourceFileObject(languageVersion: ScriptTarget, filename: string, scriptSnapshot: TypeScript.IScriptSnapshot, byteOrderMark: ByteOrderMark, version: number, isOpen: boolean, syntaxTree: TypeScript.SyntaxTree) { + var newSoruceFile = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), languageVersion, byteOrderMark, version, isOpen); + newSoruceFile.scriptSnapshot = scriptSnapshot; + newSoruceFile.syntaxTree = syntaxTree; + return newSoruceFile; + } + } + export interface Logger { information(): boolean; debug(): boolean; @@ -563,17 +693,17 @@ module ts { byteOrderMark: ByteOrderMark, version: number, isOpen: boolean, - referencedFiles: string[]): Document; + referencedFiles: string[]): SourceFile; updateDocument( - document: Document, + document: SourceFile, filename: string, compilationSettings: CompilerOptions, scriptSnapshot: TypeScript.IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange - ): Document; + ): SourceFile; releaseDocument(filename: string, compilationSettings: CompilerOptions): void } @@ -665,172 +795,6 @@ module ts { (oldSyntaxTree: TypeScript.SyntaxTree, textChangeRange: TypeScript.TextChangeRange, newText: TypeScript.ISimpleText): TypeScript.SyntaxTree } - export interface Document { - getFilename(): string; - getByteOrderMark(): ByteOrderMark; - getVersion(): number; - isOpen(): boolean; - getSourceUnit(): TypeScript.SourceUnitSyntax; - getSyntaxTree(): TypeScript.SyntaxTree; - getSourceFile(): SourceFile; - getBloomFilter(): TypeScript.BloomFilter; - update(scriptSnapshot: TypeScript.IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange): Document; - } - - class DocumentObject implements Document { - private bloomFilter: TypeScript.BloomFilter = null; - - // By default, our Document class doesn't support incremental update of its conten - // However, we enable other layers (like teh services layer) to inject the capability - // into us by setting this function. - public static incrementalParse: IncrementalParse = TypeScript.IncrementalParser.parse; - - constructor(private compilationSettings: CompilerOptions, - public filename: string, - public referencedFiles: string[], - private scriptSnapshot: TypeScript.IScriptSnapshot, - public byteOrderMark: ByteOrderMark, - public version: number, - public _isOpen: boolean, - private syntaxTree: TypeScript.SyntaxTree, - private soruceFile: SourceFile) { - } - - public getFilename(): string { - return this.filename; - } - - public getVersion(): number { - return this.version; - } - - public isOpen(): boolean { - return this._isOpen; - } - - public getByteOrderMark(): ByteOrderMark { - return this.byteOrderMark; - } - public isDeclareFile(): boolean { - return TypeScript.isDTSFile(this.filename); - } - - public getSourceUnit(): TypeScript.SourceUnitSyntax { - // If we don't have a script, create one from our parse tree. - return this.getSyntaxTree().sourceUnit(); - } - - public getLineMap(): TypeScript.LineMap { - return this.getSyntaxTree().lineMap(); - } - - 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.compilationSettings.target, this.isDeclareFile()); - - var time = new Date().getTime() - start; - - //TypeScript.syntaxTreeParseTime += time; - } - - return this.syntaxTree; - } - - public getSourceFile(): SourceFile { - if (!this.soruceFile) { - var start = new Date().getTime(); - - this.soruceFile = createSourceFile(this.filename, this.scriptSnapshot.getText(0, this.scriptSnapshot.getLength()), this.compilationSettings.target); - - var time = new Date().getTime() - start; - - //TypeScript.astParseTime += time; - } - - return this.soruceFile; - } - - public getBloomFilter(): TypeScript.BloomFilter { - if (!this.bloomFilter) { - var identifiers = TypeScript.createIntrinsicsObject(); - var pre = function (cur: TypeScript.ISyntaxElement) { - if (TypeScript.ASTHelpers.isValidAstNode(cur)) { - if (cur.kind() === TypeScript.SyntaxKind.IdentifierName) { - var nodeText = TypeScript.tokenValueText((cur)); - - identifiers[nodeText] = true; - } - } - }; - - TypeScript.getAstWalkerFactory().simpleWalk(this.getSourceUnit(), pre, null, identifiers); - - var identifierCount = 0; - for (var name in identifiers) { - if (identifiers[name]) { - identifierCount++; - } - } - - this.bloomFilter = new TypeScript.BloomFilter(identifierCount); - this.bloomFilter.addKeys(identifiers); - } - return this.bloomFilter; - } - - // Returns true if this file should get emitted into its own unique output file. - // Otherwise, it should be written into a single output file along with the rest of hte - // documents in the compilation. - public emitToOwnOutputFile(): boolean { - // If we haven't specified an output file in our settings, then we're definitely - // emitting to our own file. Also, if we're an external module, then we're - // definitely emitting to our own file. - return !this.compilationSettings.out || this.getSyntaxTree().isExternalModule(); - } - - public update(scriptSnapshot: TypeScript.IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange): Document { - // 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 accidently realize - // the old syntax tree. - var oldSyntaxTree = this.syntaxTree; - - if (textChangeRange !== null && Debug.shouldAssert(AssertionLevel.Normal)) { - var oldText = this.scriptSnapshot; - var newText = scriptSnapshot; - - TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); - - if (Debug.shouldAssert(AssertionLevel.VeryAggressive)) { - var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); - var newTextPrefix = newText.getText(0, textChangeRange.span().start()); - TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); - - var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); - var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); - TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - - 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 === null || oldSyntaxTree === null || DocumentObject.incrementalParse === null - ? TypeScript.Parser.parse(this.filename, text, this.compilationSettings.target, TypeScript.isDTSFile(this.filename)) - : DocumentObject.incrementalParse(oldSyntaxTree, textChangeRange, text); - - return new DocumentObject(this.compilationSettings, this.filename, this.referencedFiles, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree, /*soruceFile*/ null); - } - } - - export function createDocument(compilationSettings: CompilerOptions, fileName: string, scriptSnapshot: TypeScript.IScriptSnapshot, byteOrderMark: ByteOrderMark, version: number, isOpen: boolean, referencedFiles: string[]): Document { - return new DocumentObject(compilationSettings, fileName, referencedFiles, scriptSnapshot, byteOrderMark, version, isOpen, /*syntaxTree:*/ null, /*soruceFile*/ null); - } - /// Language Service interface CompletionSession { @@ -859,7 +823,7 @@ module ts { } interface DocumentRegistryEntry { - document: Document; + document: SourceFile; refCount: number; owners: string[]; } @@ -1172,13 +1136,12 @@ module ts { scriptSnapshot: TypeScript.IScriptSnapshot, byteOrderMark: ByteOrderMark, version: number, - isOpen: boolean, - referencedFiles: string[]= []): Document { + isOpen: boolean): SourceFile { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); var entry = lookUp(bucket, filename); if (!entry) { - var document = createDocument(compilationSettings, filename, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + var document = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), compilationSettings.target, byteOrderMark, version, isOpen); bucket[filename] = entry = { document: document, @@ -1192,21 +1155,21 @@ module ts { } function updateDocument( - document: Document, + document: SourceFile, filename: string, compilationSettings: CompilerOptions, scriptSnapshot: TypeScript.IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TypeScript.TextChangeRange - ): Document { + ): SourceFile { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false); Debug.assert(bucket); var entry = lookUp(bucket, filename); Debug.assert(entry); - if (entry.document.isOpen() === isOpen && entry.document.getVersion() === version) { + if (entry.document.isOpen === isOpen && entry.document.version === version) { return entry.document; } @@ -1252,7 +1215,7 @@ module ts { var program: Program; var typeChecker: TypeChecker; var useCaseSensitivefilenames = false; - var documentsByName: Map = {}; + var documentsByName: Map = {}; var documentRegistry = documentRegistry; var cancellationToken = new CancellationTokenObject(host.getCancellationToken()); var activeCompletionSession: CompletionSession; // The current active completion session, used to get the completion entry details @@ -1262,7 +1225,7 @@ module ts { TypeScript.LocalizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } - function getDocument(filename: string): Document { + function getDocument(filename: string): SourceFile { return lookUp(documentsByName, filename); } @@ -1339,12 +1302,12 @@ module ts { var isOpen = hostCache.isOpen(filename); var scriptSnapshot = hostCache.getScriptSnapshot(filename); - var document: Document = getDocument(filename); + var document: SourceFile = getDocument(filename); if (document) { // // If the document is the same, assume no update // - if (document.getVersion() === version && document.isOpen() === isOpen) { + if (document.version === version && document.isOpen === isOpen) { continue; } @@ -1356,7 +1319,7 @@ module ts { // new text buffer). var textChangeRange: TypeScript.TextChangeRange = null; if (document.isOpen && isOpen) { - textChangeRange = hostCache.getScriptTextChangeRangeSinceVersion(filename, document.getVersion()); + textChangeRange = hostCache.getScriptTextChangeRangeSinceVersion(filename, document.version); } document = documentRegistry.updateDocument(document, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange); @@ -2217,7 +2180,7 @@ module ts { getNodeConstructor: kind => { function Node() { } - var proto = new NodeObject(); + var proto = kind === SyntaxKind.SourceFile ? new SourceFileObject() : new NodeObject(); proto.kind = kind; proto.pos = 0; proto.end = 0; From 4da02cbc06ec5755cdd05075d4a5400d48f61f23 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 4 Aug 2014 11:54:46 -0700 Subject: [PATCH 28/29] rename values named document to sourceFile --- src/services/services.ts | 70 ++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index ef0526442e9..aae0ae8cfc0 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -696,7 +696,7 @@ module ts { referencedFiles: string[]): SourceFile; updateDocument( - document: SourceFile, + soruceFile: SourceFile, filename: string, compilationSettings: CompilerOptions, scriptSnapshot: TypeScript.IScriptSnapshot, @@ -823,7 +823,7 @@ module ts { } interface DocumentRegistryEntry { - document: SourceFile; + sourceFile: SourceFile; refCount: number; owners: string[]; } @@ -1115,17 +1115,17 @@ module ts { function reportStats() { var bucketInfoArray = Object.keys(buckets).filter(name => name && name.charAt(0) === '_').map(name => { var entries = lookUp(buckets, name); - var documents: { name: string; refCount: number; references: string[]; }[] = []; + var soruceFiles: { name: string; refCount: number; references: string[]; }[] = []; for (var i in entries) { var entry = entries[i]; - documents.push({ + soruceFiles.push({ name: i, refCount: entry.refCount, references: entry.owners.slice(0) }); } - documents.sort((x, y) => y.refCount - x.refCount); - return { bucket: name, documents: documents } + soruceFiles.sort((x, y) => y.refCount - x.refCount); + return { bucket: name, sourceFiles: soruceFiles } }); return JSON.stringify(bucketInfoArray, null, 2); } @@ -1141,21 +1141,21 @@ module ts { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); var entry = lookUp(bucket, filename); if (!entry) { - var document = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), compilationSettings.target, byteOrderMark, version, isOpen); + var sourceFile = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), compilationSettings.target, byteOrderMark, version, isOpen); bucket[filename] = entry = { - document: document, + sourceFile: sourceFile, refCount: 0, owners: [] }; } entry.refCount++; - return entry.document; + return entry.sourceFile; } function updateDocument( - document: SourceFile, + sourceFile: SourceFile, filename: string, compilationSettings: CompilerOptions, scriptSnapshot: TypeScript.IScriptSnapshot, @@ -1169,12 +1169,12 @@ module ts { var entry = lookUp(bucket, filename); Debug.assert(entry); - if (entry.document.isOpen === isOpen && entry.document.version === version) { - return entry.document; + if (entry.sourceFile.isOpen === isOpen && entry.sourceFile.version === version) { + return entry.sourceFile; } - entry.document = entry.document.update(scriptSnapshot, version, isOpen, textChangeRange); - return entry.document; + entry.sourceFile = entry.sourceFile.update(scriptSnapshot, version, isOpen, textChangeRange); + return entry.sourceFile; } function releaseDocument(filename: string, compilationSettings: CompilerOptions): void { @@ -1225,18 +1225,18 @@ module ts { TypeScript.LocalizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } - function getDocument(filename: string): SourceFile { + function getSourceFile(filename: string): SourceFile { return lookUp(documentsByName, filename); } function createCompilerHost(): CompilerHost { return { getSourceFile: (filename, languageVersion) => { - var document = getDocument(filename); + var sourceFile = getSourceFile(filename); - Debug.assert(!!document, "document can not be undefined"); + Debug.assert(!!sourceFile, "sourceFile can not be undefined"); - return document.getSourceFile(); + return sourceFile.getSourceFile(); }, getCancellationToken: () => cancellationToken, getCanonicalFileName: (filename) => useCaseSensitivefilenames ? filename : filename.toLowerCase(), @@ -1302,12 +1302,12 @@ module ts { var isOpen = hostCache.isOpen(filename); var scriptSnapshot = hostCache.getScriptSnapshot(filename); - var document: SourceFile = getDocument(filename); - if (document) { + var sourceFile: SourceFile = getSourceFile(filename); + if (sourceFile) { // - // If the document is the same, assume no update + // If the sourceFile is the same, assume no update // - if (document.version === version && document.isOpen === isOpen) { + if (sourceFile.version === version && sourceFile.isOpen === isOpen) { continue; } @@ -1318,18 +1318,18 @@ module ts { // the old buffer alive that represented the file on disk (as the host has moved to a // new text buffer). var textChangeRange: TypeScript.TextChangeRange = null; - if (document.isOpen && isOpen) { - textChangeRange = hostCache.getScriptTextChangeRangeSinceVersion(filename, document.version); + if (sourceFile.isOpen && isOpen) { + textChangeRange = hostCache.getScriptTextChangeRangeSinceVersion(filename, sourceFile.version); } - document = documentRegistry.updateDocument(document, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange); + sourceFile = documentRegistry.updateDocument(sourceFile, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange); } else { - document = documentRegistry.acquireDocument(filename, compilationSettings, scriptSnapshot, hostCache.getByteOrderMark(filename), version, isOpen, []); + sourceFile = documentRegistry.acquireDocument(filename, compilationSettings, scriptSnapshot, hostCache.getByteOrderMark(filename), version, isOpen, []); } - // Remeber the new document - documentsByName[filename] = document; + // Remeber the new sourceFile + documentsByName[filename] = sourceFile; } // Now create a new compiler @@ -1534,10 +1534,10 @@ module ts { filename = TypeScript.switchToForwardSlashes(filename); - var document = getDocument(filename); - var sourceUnit = document.getSourceUnit(); + var sourceFile = getSourceFile(filename); + var sourceUnit = sourceFile.getSourceUnit(); - if (isCompletionListBlocker(document.getSyntaxTree().sourceUnit(), position)) { + if (isCompletionListBlocker(sourceFile.getSyntaxTree().sourceUnit(), position)) { host.log("Returning an empty list because completion was blocked."); return null; } @@ -1583,7 +1583,7 @@ module ts { } // TODO: this is a hack for now, we need a proper walking mechanism to verify that we have the correct node - var mappedNode = getNodeAtPosition(document.getSourceFile(), TypeScript.end(node) - 1); + var mappedNode = getNodeAtPosition(sourceFile.getSourceFile(), TypeScript.end(node) - 1); Debug.assert(mappedNode, "Could not map a Fidelity node to an AST node"); @@ -1609,7 +1609,7 @@ module ts { getCompletionEntriesFromSymbols(symbols, activeCompletionSession); } else { - var containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(document.getSyntaxTree().sourceUnit(), position); + var containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(sourceFile.getSyntaxTree().sourceUnit(), position); // Object literal expression, look up possible property names from contextual type if (containingObjectLiteral) { @@ -1794,8 +1794,8 @@ module ts { synchronizeHostData(); filename = TypeScript.switchToForwardSlashes(filename); - var document = getDocument(filename); - var node = getNodeAtPosition(document.getSourceFile(), position); + var sourceFile = getSourceFile(filename); + var node = getNodeAtPosition(sourceFile.getSourceFile(), position); if (!node) return undefined; switch (node.kind) { From 5d26599811f9c8432b3c782f90f264d9255cf49d Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 4 Aug 2014 12:26:44 -0700 Subject: [PATCH 29/29] remove documentsByName --- src/services/services.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index aae0ae8cfc0..c9c5c9d34fa 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1215,7 +1215,6 @@ module ts { var program: Program; var typeChecker: TypeChecker; var useCaseSensitivefilenames = false; - var documentsByName: Map = {}; var documentRegistry = documentRegistry; var cancellationToken = new CancellationTokenObject(host.getCancellationToken()); var activeCompletionSession: CompletionSession; // The current active completion session, used to get the completion entry details @@ -1226,7 +1225,8 @@ module ts { } function getSourceFile(filename: string): SourceFile { - return lookUp(documentsByName, filename); + Debug.assert(!!program, "'getSoruceFile(filename)' is called before 'program' is initialized, consider calling 'synchronizeHostData()' first"); + return program.getSourceFile(filename); } function createCompilerHost(): CompilerHost { @@ -1285,7 +1285,6 @@ module ts { var filename = oldSourceFiles[i].filename; if (!hostCache.contains(filename) || changesInCompilationSettingsAffectSyntax) { documentRegistry.releaseDocument(filename, oldSettings); - delete documentsByName[filename]; } } } @@ -1327,9 +1326,6 @@ module ts { else { sourceFile = documentRegistry.acquireDocument(filename, compilationSettings, scriptSnapshot, hostCache.getByteOrderMark(filename), version, isOpen, []); } - - // Remeber the new sourceFile - documentsByName[filename] = sourceFile; } // Now create a new compiler