From b85d56b8570ce6bdb4ec0ee4dd5e8694dc0cabb9 Mon Sep 17 00:00:00 2001 From: SaschaNaz Date: Fri, 15 May 2015 21:00:32 +0900 Subject: [PATCH 01/79] block form indentation --- src/services/formatting/smartIndenter.ts | 28 ++++++++++++++++++- .../fourslash/formattingOnChainedCallbacks.ts | 2 ++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 9cd28a40a54..35bc015d66b 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -26,7 +26,7 @@ module ts.formatting { precedingToken.kind === SyntaxKind.TemplateHead || precedingToken.kind === SyntaxKind.TemplateMiddle || precedingToken.kind === SyntaxKind.TemplateTail; - if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { return 0; } @@ -110,6 +110,12 @@ module ts.formatting { if (actualIndentation !== Value.Unknown) { return actualIndentation + indentationDelta; } + + // check if current node is a block-form item - if yes, take indentation from it + actualIndentation = getActualIndentationForBlockFormItem(current, sourceFile, options); + if (actualIndentation !== Value.Unknown) { + return actualIndentation + indentationDelta; + } } parentStart = getParentStart(parent, current, sourceFile); let parentAndChildShareLine = @@ -277,6 +283,15 @@ module ts.formatting { return undefined; } + function getActualIndentationForBlockFormItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number { + if (isPassableBlockForm(node.kind)) { + let firstChild = node.getChildAt(0); + let lineAndCharacter = getStartLineAndCharacterForNode(firstChild, sourceFile); + return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); + } + return Value.Unknown; + } + function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number { let containingList = getContainingList(node, sourceFile); return containingList ? getActualIndentationFromList(containingList) : Value.Unknown; @@ -400,5 +415,16 @@ module ts.formatting { return false; } } + + export function isPassableBlockForm(kind: SyntaxKind): boolean { + switch (kind) { + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.ObjectLiteralExpression: + return true; + } + return false; + } } } \ No newline at end of file diff --git a/tests/cases/fourslash/formattingOnChainedCallbacks.ts b/tests/cases/fourslash/formattingOnChainedCallbacks.ts index 37fa6ff03f1..98f91de56fb 100644 --- a/tests/cases/fourslash/formattingOnChainedCallbacks.ts +++ b/tests/cases/fourslash/formattingOnChainedCallbacks.ts @@ -17,6 +17,8 @@ goTo.marker('1'); edit.insertLine(''); goTo.marker('2'); verify.currentLineContentIs(' ""'); +edit.insertLine(''); +verify.indentationIs(8); goTo.marker('4'); edit.insertLine(''); goTo.marker('3'); From a9eba62b68611bfb4aa75446ad6b147086dbe541 Mon Sep 17 00:00:00 2001 From: SaschaNaz Date: Sat, 16 May 2015 16:24:50 +0900 Subject: [PATCH 02/79] getLineIndentation --- src/services/formatting/smartIndenter.ts | 62 +++++++++++++----------- 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 35bc015d66b..77e70a1ceaf 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -110,12 +110,6 @@ module ts.formatting { if (actualIndentation !== Value.Unknown) { return actualIndentation + indentationDelta; } - - // check if current node is a block-form item - if yes, take indentation from it - actualIndentation = getActualIndentationForBlockFormItem(current, sourceFile, options); - if (actualIndentation !== Value.Unknown) { - return actualIndentation + indentationDelta; - } } parentStart = getParentStart(parent, current, sourceFile); let parentAndChildShareLine = @@ -283,23 +277,48 @@ module ts.formatting { return undefined; } - function getActualIndentationForBlockFormItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number { - if (isPassableBlockForm(node.kind)) { - let firstChild = node.getChildAt(0); - let lineAndCharacter = getStartLineAndCharacterForNode(firstChild, sourceFile); - return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); - } - return Value.Unknown; - } - function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number { let containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : Value.Unknown; + + if (containingList) { + let lineIndentation = getLineIndentationWhenExpressionIsInMultiLine(); + if (lineIndentation !== Value.Unknown) + return lineIndentation; + return getActualIndentationFromList(containingList); + } + return Value.Unknown; function getActualIndentationFromList(list: Node[]): number { let index = indexOf(list, node); return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : Value.Unknown; } + + function getLineIndentationWhenExpressionIsInMultiLine() { + if (node.parent.kind === SyntaxKind.CallExpression) { + let parentExpression = (node.parent).expression; + let startingExpression = getStartingExpression(parentExpression); + + if (parentExpression === startingExpression) { + return Value.Unknown; + } + + let parentExpressionEnd = sourceFile.getLineAndCharacterOfPosition(parentExpression.end); + let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + + if (parentExpressionEnd.line === startingExpressionEnd.line) { + return Value.Unknown; + } + + return findColumnForFirstNonWhitespaceCharacterInLine(parentExpressionEnd, sourceFile, options); + } + return Value.Unknown; + } + + function getStartingExpression(expression: CallExpression) { + while (expression.expression) + expression = expression.expression; + return expression; + } } function deriveActualIndentationFromList(list: Node[], index: number, sourceFile: SourceFile, options: EditorOptions): number { @@ -415,16 +434,5 @@ module ts.formatting { return false; } } - - export function isPassableBlockForm(kind: SyntaxKind): boolean { - switch (kind) { - case SyntaxKind.ArrowFunction: - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrayLiteralExpression: - case SyntaxKind.ObjectLiteralExpression: - return true; - } - return false; - } } } \ No newline at end of file From 4b4fc0147e6480033ccfb50cc2a8a8168c1fde76 Mon Sep 17 00:00:00 2001 From: SaschaNaz Date: Sat, 16 May 2015 17:08:09 +0900 Subject: [PATCH 03/79] take the function out --- src/services/formatting/smartIndenter.ts | 38 ++++++++++++------------ 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 77e70a1ceaf..a02dc4454fa 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -281,7 +281,7 @@ module ts.formatting { let containingList = getContainingList(node, sourceFile); if (containingList) { - let lineIndentation = getLineIndentationWhenExpressionIsInMultiLine(); + let lineIndentation = getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options); if (lineIndentation !== Value.Unknown) return lineIndentation; return getActualIndentationFromList(containingList); @@ -292,28 +292,28 @@ module ts.formatting { let index = indexOf(list, node); return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : Value.Unknown; } + } - function getLineIndentationWhenExpressionIsInMultiLine() { - if (node.parent.kind === SyntaxKind.CallExpression) { - let parentExpression = (node.parent).expression; - let startingExpression = getStartingExpression(parentExpression); + function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorOptions): number { + if (node.parent.kind === SyntaxKind.CallExpression) { + let parentExpression = (node.parent).expression; + let startingExpression = getStartingExpression(parentExpression); - if (parentExpression === startingExpression) { - return Value.Unknown; - } - - let parentExpressionEnd = sourceFile.getLineAndCharacterOfPosition(parentExpression.end); - let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - - if (parentExpressionEnd.line === startingExpressionEnd.line) { - return Value.Unknown; - } - - return findColumnForFirstNonWhitespaceCharacterInLine(parentExpressionEnd, sourceFile, options); + if (parentExpression === startingExpression) { + return Value.Unknown; } - return Value.Unknown; - } + let parentExpressionEnd = sourceFile.getLineAndCharacterOfPosition(parentExpression.end); + let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + + if (parentExpressionEnd.line === startingExpressionEnd.line) { + return Value.Unknown; + } + + return findColumnForFirstNonWhitespaceCharacterInLine(parentExpressionEnd, sourceFile, options); + } + return Value.Unknown; + function getStartingExpression(expression: CallExpression) { while (expression.expression) expression = expression.expression; From ac447f1f513fbbe3eb16eb7f0dcaf795ef080792 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 21 May 2015 16:45:23 -0700 Subject: [PATCH 04/79] Migrated decorator checks to call resolution --- src/compiler/checker.ts | 368 +++++++++++++++--- .../diagnosticInformationMap.generated.ts | 2 + src/compiler/diagnosticMessages.json | 8 + src/compiler/types.ts | 2 +- src/compiler/utilities.ts | 3 + .../decoratedClassFromExternalModule.js | 4 +- .../decoratedClassFromExternalModule.symbols | 5 +- .../decoratedClassFromExternalModule.types | 7 +- .../decoratorChecksFunctionBodies.errors.txt | 2 +- .../decoratorChecksFunctionBodies.js | 4 +- ...ratorInstantiateModulesInFunctionBodies.js | 4 +- ...InstantiateModulesInFunctionBodies.symbols | 3 +- ...orInstantiateModulesInFunctionBodies.types | 11 +- .../reference/decoratorOnClass8.errors.txt | 6 +- .../decoratorOnClassMethod10.errors.txt | 16 +- .../reference/decoratorOnClassMethod13.js | 2 +- .../decoratorOnClassMethod13.symbols | 16 +- .../reference/decoratorOnClassMethod13.types | 8 +- .../decoratorOnClassMethod6.errors.txt | 13 + .../reference/decoratorOnClassMethod6.symbols | 18 - .../reference/decoratorOnClassMethod6.types | 19 - .../decoratorOnClassMethod8.errors.txt | 13 + .../reference/decoratorOnClassMethod8.symbols | 15 - .../reference/decoratorOnClassMethod8.types | 15 - .../decoratorOnClassMethodParameter1.js | 2 +- .../decoratorOnClassMethodParameter1.symbols | 10 +- .../decoratorOnClassMethodParameter1.types | 10 +- .../decoratorOnClassProperty11.errors.txt | 13 + .../decoratorOnClassProperty11.symbols | 14 - .../decoratorOnClassProperty11.types | 14 - .../decoratorOnClassProperty6.errors.txt | 13 + .../decoratorOnClassProperty6.symbols | 13 - .../reference/decoratorOnClassProperty6.types | 13 - .../decoratorOnClassProperty7.errors.txt | 6 +- .../reference/missingDecoratorType.errors.txt | 22 +- .../reference/missingDecoratorType.js | 15 +- tests/baselines/reference/noEmitHelpers2.js | 3 +- .../reference/noEmitHelpers2.symbols | 10 +- .../baselines/reference/noEmitHelpers2.types | 8 +- .../sourceMapValidationDecorators.js | 4 +- ...ourceMapValidationDecorators.sourcemap.txt | 4 +- .../sourceMapValidationDecorators.symbols | 36 +- .../sourceMapValidationDecorators.types | 40 +- tests/cases/compiler/noEmitHelpers2.ts | 2 +- .../compiler/sourceMapValidationDecorators.ts | 4 +- .../class/decoratedClassFromExternalModule.ts | 2 +- .../class/decoratorChecksFunctionBodies.ts | 2 +- ...ratorInstantiateModulesInFunctionBodies.ts | 2 +- .../class/method/decoratorOnClassMethod13.ts | 2 +- .../decoratorOnClassMethodParameter1.ts | 2 +- .../decorators/missingDecoratorType.ts | 9 +- 51 files changed, 533 insertions(+), 306 deletions(-) create mode 100644 tests/baselines/reference/decoratorOnClassMethod6.errors.txt delete mode 100644 tests/baselines/reference/decoratorOnClassMethod6.symbols delete mode 100644 tests/baselines/reference/decoratorOnClassMethod6.types create mode 100644 tests/baselines/reference/decoratorOnClassMethod8.errors.txt delete mode 100644 tests/baselines/reference/decoratorOnClassMethod8.symbols delete mode 100644 tests/baselines/reference/decoratorOnClassMethod8.types create mode 100644 tests/baselines/reference/decoratorOnClassProperty11.errors.txt delete mode 100644 tests/baselines/reference/decoratorOnClassProperty11.symbols delete mode 100644 tests/baselines/reference/decoratorOnClassProperty11.types create mode 100644 tests/baselines/reference/decoratorOnClassProperty6.errors.txt delete mode 100644 tests/baselines/reference/decoratorOnClassProperty6.symbols delete mode 100644 tests/baselines/reference/decoratorOnClassProperty6.types diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9bd0d6475fe..e99dd7eeb4e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -114,10 +114,7 @@ module ts { let globalIterableType: ObjectType; let anyArrayType: Type; - let getGlobalClassDecoratorType: () => ObjectType; - let getGlobalParameterDecoratorType: () => ObjectType; - let getGlobalPropertyDecoratorType: () => ObjectType; - let getGlobalMethodDecoratorType: () => ObjectType; + let getGlobalTypedPropertyDescriptorType: () => ObjectType; let tupleTypes: Map = {}; let unionTypes: Map = {}; @@ -3975,8 +3972,8 @@ module ts { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } - function checkTypeAssignableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage): boolean { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); + function checkTypeAssignableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: DiagnosticMessageChain): boolean { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source: Signature, target: Signature): boolean { @@ -6539,7 +6536,7 @@ module ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { checkExpression((node).template); } - else { + else if (node.kind !== SyntaxKind.Decorator) { forEach((node).arguments, argument => { checkExpression(argument); }); @@ -6645,6 +6642,41 @@ module ts { callIsIncomplete = !!templateLiteral.isUnterminated; } } + else if (node.kind === SyntaxKind.Decorator) { + let decorator = node; + switch (decorator.parent.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + adjustedArgCount = 1; + typeArguments = undefined; + break; + + case SyntaxKind.PropertyDeclaration: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + adjustedArgCount = 2; + typeArguments = undefined; + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // A method or accessor declaration decorator will have two or three arguments (see + // `MethodDecorator` in core.d.ts) + adjustedArgCount = signature.parameters.length >= 3 ? 3 : 2; + typeArguments = undefined; + break; + + case SyntaxKind.Parameter: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + + adjustedArgCount = 3; + typeArguments = undefined; + break; + } + } else { let callExpression = node; if (!callExpression.arguments) { @@ -6742,11 +6774,8 @@ module ts { let arg = args[i]; if (arg.kind !== SyntaxKind.OmittedExpression) { let paramType = getTypeAtPosition(signature, i); - let argType: Type; - if (i === 0 && args[i].parent.kind === SyntaxKind.TaggedTemplateExpression) { - argType = globalTemplateStringsArrayType; - } - else { + let argType = getSyntheticArgumentType(i, arg); + if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; @@ -6773,7 +6802,7 @@ module ts { getInferredTypes(context); } - function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean): boolean { + function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean, containingMessageChain?: DiagnosticMessageChain): boolean { let typeParameters = signature.typeParameters; let typeArgumentsAreAssignable = true; for (let i = 0; i < typeParameters.length; i++) { @@ -6785,14 +6814,147 @@ module ts { let constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + Diagnostics.Type_0_does_not_satisfy_the_constraint_1, containingMessageChain); } } } return typeArgumentsAreAssignable; } + + function getTypeOfParentOfClassElement(node: ClassElement) { + let classSymbol = getSymbolOfNode(node.parent); + if (node.flags & NodeFlags.Static) { + return getTypeOfSymbol(classSymbol); + } + else { + return getDeclaredTypeOfSymbol(classSymbol); + } + } + + function createTypedPropertyDescriptorType(propertyType: Type): Type { + let globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyObjectType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } + + /** + * Gets the type for a synthetic argument when resolving the first argument for a TaggedTemplateExpression + * or any arguments to a Decorator. + */ + function getSyntheticArgumentType(argumentIndex: number, arg: Expression): Type { + if (arg.parent.kind === SyntaxKind.Decorator) { + let decorator = arg.parent; + let parent = decorator.parent; + if (argumentIndex === 0) { + // The first argument to a decorator is its `target`. + switch (parent.kind) { + case SyntaxKind.ClassDeclaration: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + let classSymbol = getSymbolOfNode(parent); + return getTypeOfSymbol(classSymbol); + + case SyntaxKind.Parameter: + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + parent = parent.parent; + if (parent.kind === SyntaxKind.Constructor) { + let classSymbol = getSymbolOfNode(parent); + return getTypeOfSymbol(classSymbol); + } + + // fall-through + + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getTypeOfParentOfClassElement(parent); + } + } + else if (argumentIndex === 1) { + // The second argument to a decorator is its `propertyKey` + switch (parent.kind) { + case SyntaxKind.ClassDeclaration: + Debug.fail("Class decorators should not have a second synthetic argument."); + + case SyntaxKind.Parameter: + parent = parent.parent; + if (parent.kind === SyntaxKind.Constructor) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + + // fall-through + + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + let element = decorator.parent; + switch (element.name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.NumericLiteral: + case SyntaxKind.StringLiteral: + return getStringLiteralType(element.name); + + case SyntaxKind.ComputedPropertyName: + let nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { + return nameType; + } + else { + return stringType; + } + } + } + } + else if (argumentIndex === 2) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a paramter decorator + switch (parent.kind) { + case SyntaxKind.ClassDeclaration: + Debug.fail("Class decorators should not have a third synthetic argument."); + break; - function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { + case SyntaxKind.Parameter: + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + + case SyntaxKind.PropertyDeclaration: + Debug.fail("Property decorators should not have a third synthetic argument."); + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + let propertyType: Type = getTypeOfNode(parent); + return createTypedPropertyDescriptorType(propertyType); + } + } + } + else if (argumentIndex === 0 && arg.parent.kind === SyntaxKind.TaggedTemplateExpression) { + return globalTemplateStringsArrayType; + } + + return undefined; + } + + function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean, containingMessageChain?: DiagnosticMessageChain) { for (let i = 0; i < args.length; i++) { let arg = args[i]; if (arg.kind !== SyntaxKind.OmittedExpression) { @@ -6800,15 +6962,16 @@ module ts { let paramType = getTypeAtPosition(signature, i); // A tagged template expression provides a special first argument, and string literals get string literal types // unless we're reporting errors - let argType = i === 0 && node.kind === SyntaxKind.TaggedTemplateExpression - ? globalTemplateStringsArrayType - : arg.kind === SyntaxKind.StringLiteral && !reportErrors + let argType = getSyntheticArgumentType(i, arg); + if (argType === undefined) { + argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + } // Use argument expression as error location when reporting errors if (!checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1)) { + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, containingMessageChain)) { return false; } } @@ -6822,6 +6985,8 @@ module ts { * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution * expressions, where the first element of the list is the template for error reporting purposes. + * If 'node' is a Decorator, a new argument list is constructed with the decorator + * expression as a placeholder. */ function getEffectiveCallArguments(node: CallLikeExpression): Expression[] { let args: Expression[]; @@ -6835,6 +7000,23 @@ module ts { }); } } + else if (node.kind === SyntaxKind.Decorator) { + let decorator = node; + switch (decorator.parent.kind) { + case SyntaxKind.ClassDeclaration: + args = [decorator.expression]; + break; + case SyntaxKind.PropertyDeclaration: + args = [decorator.expression, decorator.expression]; + break; + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.Parameter: + args = [decorator.expression, decorator.expression, decorator.expression]; + break; + } + } else { args = (node).arguments || emptyArray; } @@ -6863,13 +7045,14 @@ module ts { return callExpression.typeArguments; } } - - function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[]): Signature { + + function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], containingMessageChain?: DiagnosticMessageChain): Signature { let isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; + let isDecorator = node.kind === SyntaxKind.Decorator; let typeArguments: TypeNode[]; - if (!isTaggedTemplate) { + if (!isTaggedTemplate && !isDecorator) { typeArguments = getEffectiveTypeArguments(node); // We already perform checking on the type arguments on the class declaration itself. @@ -6882,7 +7065,7 @@ module ts { // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - error(node, Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); return resolveErrorCall(node); } @@ -6900,12 +7083,14 @@ module ts { // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. let excludeArgument: boolean[]; - for (let i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); + if (!isDecorator) { + for (let i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; } - excludeArgument[i] = true; } } @@ -6969,11 +7154,11 @@ module ts { // in arguments too early. If possible, we'd like to only type them once we know the correct // overload. However, this matters for the case where the call is correct. When the call is // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true, containingMessageChain); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && (node).typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true) + if (!isTaggedTemplate && !isDecorator && (node).typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, containingMessageChain) } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -6983,12 +7168,16 @@ module ts { let diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + + if (containingMessageChain) { + diagnosticChainHead = concatenateDiagnosticMessageChains(containingMessageChain, diagnosticChainHead); + } reportNoCommonSupertypeError(inferenceCandidates, (node).expression || (node).tag, diagnosticChainHead); } } else { - error(node, Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } // No signature was applicable. We have already reported the errors for the invalid signature. @@ -7005,6 +7194,15 @@ module ts { } return resolveErrorCall(node); + + function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { + let errorInfo = chainDiagnosticMessages(/*details*/ undefined, message, arg0, arg1, arg2); + if (containingMessageChain) { + errorInfo = concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + + diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); + } function chooseOverload(candidates: Signature[], relation: Map) { for (let originalCandidate of candidates) { @@ -7205,6 +7403,55 @@ module ts { return resolveCall(node, callSignatures, candidatesOutArray); } + function resolveDecorator(node: Decorator, candidatesOutArray: Signature[]): Signature { + let funcType = checkExpression(node.expression); + let apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + + let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & TypeFlags.Union) && isTypeAssignableTo(funcType, globalFunctionType))) { + return resolveUntypedCall(node); + } + + let decoratorKind: string; + switch (node.parent.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + decoratorKind = "class"; + break; + + case SyntaxKind.Parameter: + decoratorKind = "parameter"; + break; + + case SyntaxKind.PropertyDeclaration: + decoratorKind = "property"; + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + decoratorKind = "method"; + break; + + default: + Debug.fail("Invalid decorator target."); + break; + } + + let diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Invalid_expression_for_0_decorator, decoratorKind); + if (!callSignatures.length) { + let errorInfo = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = concatenateDiagnosticMessageChains(diagnosticChainHead, errorInfo); + diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + + return resolveCall(node, callSignatures, candidatesOutArray, diagnosticChainHead); + } + // candidatesOutArray is passed by signature help in the language service, and collectCandidates // must fill it up with the appropriate candidate signatures function getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature { @@ -7225,6 +7472,9 @@ module ts { else if (node.kind === SyntaxKind.TaggedTemplateExpression) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } + else if (node.kind === SyntaxKind.Decorator) { + links.resolvedSignature = resolveDecorator(node, candidatesOutArray); + } else { Debug.fail("Branch in 'getResolvedSignature' should be unreachable."); } @@ -8844,35 +9094,58 @@ module ts { /** Check a decorator */ function checkDecorator(node: Decorator): void { - let expression: Expression = node.expression; - let exprType = checkExpression(expression); - + let signature = getResolvedSignature(node); + let returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & TypeFlags.Any) { + return; + } + + let expectedReturnType: Type; + let diagnosticChainHead: DiagnosticMessageChain; + let decoratorKind: string; switch (node.parent.kind) { case SyntaxKind.ClassDeclaration: let classSymbol = getSymbolOfNode(node.parent); let classConstructorType = getTypeOfSymbol(classSymbol); - let classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); - checkTypeAssignableTo(exprType, classDecoratorType, node); + expectedReturnType = getUnionType([classConstructorType, voidType]); + decoratorKind = "class"; + break; + + case SyntaxKind.Parameter: + expectedReturnType = voidType; + decoratorKind = "parameter"; break; case SyntaxKind.PropertyDeclaration: - checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); + expectedReturnType = voidType; + decoratorKind = "property"; break; case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: let methodType = getTypeOfNode(node.parent); - let methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); - checkTypeAssignableTo(exprType, methodDecoratorType, node); - break; - - case SyntaxKind.Parameter: - checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); + let descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + decoratorKind = "method"; break; } + + if (expectedReturnType === voidType) { + diagnosticChainHead = chainDiagnosticMessages( + diagnosticChainHead, + Diagnostics.The_return_type_of_a_0_decorator_function_must_be_either_void_or_any, + decoratorKind); + } + + diagnosticChainHead = chainDiagnosticMessages( + diagnosticChainHead, + Diagnostics.Invalid_expression_for_0_decorator, + decoratorKind); + + checkTypeAssignableTo(returnType, expectedReturnType, node, /*headMessage*/ undefined, diagnosticChainHead); } - + /** Checks a type reference node as an expression. */ function checkTypeNodeAsExpression(node: TypeNode) { // When we are emitting type metadata for decorators, we need to try to check the type @@ -12043,10 +12316,7 @@ module ts { globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - getGlobalClassDecoratorType = memoize(() => getGlobalType("ClassDecorator")); - getGlobalPropertyDecoratorType = memoize(() => getGlobalType("PropertyDecorator")); - getGlobalMethodDecoratorType = memoize(() => getGlobalType("MethodDecorator")); - getGlobalParameterDecoratorType = memoize(() => getGlobalType("ParameterDecorator")); + getGlobalTypedPropertyDescriptorType = memoize(() => getGlobalType("TypedPropertyDescriptor", /*arity*/ 1)); // If we're in ES6 mode, load the TemplateStringsArray. // Otherwise, default to 'unknown' for the purposes of type checking in LS scenarios. diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 2a852716846..1eaf69d8886 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -174,6 +174,8 @@ module ts { Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: DiagnosticCategory.Error, key: "Export assignment is not supported when '--module' flag is 'system'." }, + The_return_type_of_a_0_decorator_function_must_be_either_void_or_any: { code: 1219, category: DiagnosticCategory.Error, key: "The return type of a {0} decorator function must be either 'void' or 'any'." }, + Invalid_expression_for_0_decorator: { code: 1220, category: DiagnosticCategory.Error, key: "Invalid expression for {0} decorator." }, Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index cf1645b1407..36f7505fc65 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -683,6 +683,14 @@ "category": "Error", "code": 1218 }, + "The return type of a {0} decorator function must be either 'void' or 'any'.": { + "category": "Error", + "code": 1219 + }, + "Invalid expression for {0} decorator.": { + "category": "Error", + "code": 1220 + }, "Duplicate identifier '{0}'.": { "category": "Error", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 86e680ca8b0..2c63241fdf2 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -753,7 +753,7 @@ module ts { template: LiteralExpression | TemplateExpression; } - export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression; + export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; export interface TypeAssertion extends UnaryExpression { type: TypeNode; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 356337e1315..e720c7a112e 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -620,6 +620,9 @@ module ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { return (node).tag; } + else if (node.kind === SyntaxKind.Decorator) { + return (node).expression; + } // Will either be a CallExpression or NewExpression. return (node).expression; diff --git a/tests/baselines/reference/decoratedClassFromExternalModule.js b/tests/baselines/reference/decoratedClassFromExternalModule.js index 163a4a094b4..aca1d28b952 100644 --- a/tests/baselines/reference/decoratedClassFromExternalModule.js +++ b/tests/baselines/reference/decoratedClassFromExternalModule.js @@ -1,7 +1,7 @@ //// [tests/cases/conformance/decorators/class/decoratedClassFromExternalModule.ts] //// //// [decorated.ts] -function decorate() { } +function decorate(target: any) { } @decorate export default class Decorated { } @@ -18,7 +18,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; -function decorate() { } +function decorate(target) { } let Decorated = class { }; Decorated = __decorate([ diff --git a/tests/baselines/reference/decoratedClassFromExternalModule.symbols b/tests/baselines/reference/decoratedClassFromExternalModule.symbols index aa17dde616a..60e4a892ec0 100644 --- a/tests/baselines/reference/decoratedClassFromExternalModule.symbols +++ b/tests/baselines/reference/decoratedClassFromExternalModule.symbols @@ -1,12 +1,13 @@ === tests/cases/conformance/decorators/class/decorated.ts === -function decorate() { } +function decorate(target: any) { } >decorate : Symbol(decorate, Decl(decorated.ts, 0, 0)) +>target : Symbol(target, Decl(decorated.ts, 0, 18)) @decorate >decorate : Symbol(decorate, Decl(decorated.ts, 0, 0)) export default class Decorated { } ->Decorated : Symbol(Decorated, Decl(decorated.ts, 0, 23)) +>Decorated : Symbol(Decorated, Decl(decorated.ts, 0, 34)) === tests/cases/conformance/decorators/class/undecorated.ts === import Decorated from 'decorated'; diff --git a/tests/baselines/reference/decoratedClassFromExternalModule.types b/tests/baselines/reference/decoratedClassFromExternalModule.types index 4234b6a4b15..d4bc3239e46 100644 --- a/tests/baselines/reference/decoratedClassFromExternalModule.types +++ b/tests/baselines/reference/decoratedClassFromExternalModule.types @@ -1,9 +1,10 @@ === tests/cases/conformance/decorators/class/decorated.ts === -function decorate() { } ->decorate : () => void +function decorate(target: any) { } +>decorate : (target: any) => void +>target : any @decorate ->decorate : () => void +>decorate : (target: any) => void export default class Decorated { } >Decorated : Decorated diff --git a/tests/baselines/reference/decoratorChecksFunctionBodies.errors.txt b/tests/baselines/reference/decoratorChecksFunctionBodies.errors.txt index c8166b538fd..cef2f90f704 100644 --- a/tests/baselines/reference/decoratorChecksFunctionBodies.errors.txt +++ b/tests/baselines/reference/decoratorChecksFunctionBodies.errors.txt @@ -8,7 +8,7 @@ tests/cases/conformance/decorators/class/decoratorChecksFunctionBodies.ts(9,14): } class A { - @(x => { + @((x, p) => { var a = 3; func(a); ~ diff --git a/tests/baselines/reference/decoratorChecksFunctionBodies.js b/tests/baselines/reference/decoratorChecksFunctionBodies.js index 020bc775aea..adb710efccc 100644 --- a/tests/baselines/reference/decoratorChecksFunctionBodies.js +++ b/tests/baselines/reference/decoratorChecksFunctionBodies.js @@ -5,7 +5,7 @@ function func(s: string): void { } class A { - @(x => { + @((x, p) => { var a = 3; func(a); return x; @@ -34,7 +34,7 @@ var A = (function () { }; Object.defineProperty(A.prototype, "m", __decorate([ - (function (x) { + (function (x, p) { var a = 3; func(a); return x; diff --git a/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.js b/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.js index 313d77fa5ce..08ba6e9ea7e 100644 --- a/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.js +++ b/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.js @@ -9,7 +9,7 @@ export var test = 'abc'; import { test } from './a'; function filter(handler: any) { - return function (target: any) { + return function (target: any, propertyKey: string) { // ... }; } @@ -35,7 +35,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, }; var a_1 = require('./a'); function filter(handler) { - return function (target) { + return function (target, propertyKey) { // ... }; } diff --git a/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.symbols b/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.symbols index 5088e740a57..f7c96097caf 100644 --- a/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.symbols +++ b/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.symbols @@ -12,8 +12,9 @@ function filter(handler: any) { >filter : Symbol(filter, Decl(b.ts, 0, 27)) >handler : Symbol(handler, Decl(b.ts, 2, 16)) - return function (target: any) { + return function (target: any, propertyKey: string) { >target : Symbol(target, Decl(b.ts, 3, 21)) +>propertyKey : Symbol(propertyKey, Decl(b.ts, 3, 33)) // ... }; diff --git a/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.types b/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.types index 18d993af9bb..d0f930b7ad4 100644 --- a/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.types +++ b/tests/baselines/reference/decoratorInstantiateModulesInFunctionBodies.types @@ -10,12 +10,13 @@ import { test } from './a'; >test : string function filter(handler: any) { ->filter : (handler: any) => (target: any) => void +>filter : (handler: any) => (target: any, propertyKey: string) => void >handler : any - return function (target: any) { ->function (target: any) { // ... } : (target: any) => void + return function (target: any, propertyKey: string) { +>function (target: any, propertyKey: string) { // ... } : (target: any, propertyKey: string) => void >target : any +>propertyKey : string // ... }; @@ -25,8 +26,8 @@ class Wat { >Wat : Wat @filter(() => test == 'abc') ->filter(() => test == 'abc') : (target: any) => void ->filter : (handler: any) => (target: any) => void +>filter(() => test == 'abc') : (target: any, propertyKey: string) => void +>filter : (handler: any) => (target: any, propertyKey: string) => void >() => test == 'abc' : () => boolean >test == 'abc' : boolean >test : string diff --git a/tests/baselines/reference/decoratorOnClass8.errors.txt b/tests/baselines/reference/decoratorOnClass8.errors.txt index 0a9fbf2956c..31abd9e2300 100644 --- a/tests/baselines/reference/decoratorOnClass8.errors.txt +++ b/tests/baselines/reference/decoratorOnClass8.errors.txt @@ -1,4 +1,5 @@ -tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS2322: Type '(target: Function, paramIndex: number) => void' is not assignable to type '(target: typeof C) => void | typeof C'. +tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1220: Invalid expression for class decorator. + Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/decoratorOnClass8.ts (1 errors) ==== @@ -6,6 +7,7 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS2322 @dec() ~~~~~~ -!!! error TS2322: Type '(target: Function, paramIndex: number) => void' is not assignable to type '(target: typeof C) => void | typeof C'. +!!! error TS1220: Invalid expression for class decorator. +!!! error TS1220: Supplied parameters do not match any signature of call target. class C { } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod10.errors.txt b/tests/baselines/reference/decoratorOnClassMethod10.errors.txt index cd331473b7c..bfc56717e6c 100644 --- a/tests/baselines/reference/decoratorOnClassMethod10.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod10.errors.txt @@ -1,7 +1,6 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,5): error TS2322: Type '(target: Function, paramIndex: number) => void' is not assignable to type '(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<() => void>) => void | TypedPropertyDescriptor<() => void>'. - Types of parameters 'paramIndex' and 'propertyKey' are incompatible. - Type 'number' is not assignable to type 'string | symbol'. - Type 'number' is not assignable to type 'symbol'. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6): error TS1220: Invalid expression for method decorator. + Argument of type 'C' is not assignable to parameter of type 'Function'. + Property 'apply' is missing in type 'C'. ==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts (1 errors) ==== @@ -9,9 +8,8 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,5) class C { @dec method() {} - ~~~~ -!!! error TS2322: Type '(target: Function, paramIndex: number) => void' is not assignable to type '(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<() => void>) => void | TypedPropertyDescriptor<() => void>'. -!!! error TS2322: Types of parameters 'paramIndex' and 'propertyKey' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string | symbol'. -!!! error TS2322: Type 'number' is not assignable to type 'symbol'. + ~~~ +!!! error TS1220: Invalid expression for method decorator. +!!! error TS1220: Argument of type 'C' is not assignable to parameter of type 'Function'. +!!! error TS1220: Property 'apply' is missing in type 'C'. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod13.js b/tests/baselines/reference/decoratorOnClassMethod13.js index 967cc05ba4d..b39fa63686a 100644 --- a/tests/baselines/reference/decoratorOnClassMethod13.js +++ b/tests/baselines/reference/decoratorOnClassMethod13.js @@ -1,5 +1,5 @@ //// [decoratorOnClassMethod13.ts] -declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; class C { @dec ["1"]() { } diff --git a/tests/baselines/reference/decoratorOnClassMethod13.symbols b/tests/baselines/reference/decoratorOnClassMethod13.symbols index af3819924f4..42f44d885ee 100644 --- a/tests/baselines/reference/decoratorOnClassMethod13.symbols +++ b/tests/baselines/reference/decoratorOnClassMethod13.symbols @@ -1,17 +1,17 @@ === tests/cases/conformance/decorators/class/method/decoratorOnClassMethod13.ts === -declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; >dec : Symbol(dec, Decl(decoratorOnClassMethod13.ts, 0, 0)) ->T : Symbol(T, Decl(decoratorOnClassMethod13.ts, 0, 25)) ->target : Symbol(target, Decl(decoratorOnClassMethod13.ts, 0, 28)) ->propertyKey : Symbol(propertyKey, Decl(decoratorOnClassMethod13.ts, 0, 40)) ->descriptor : Symbol(descriptor, Decl(decoratorOnClassMethod13.ts, 0, 61)) +>T : Symbol(T, Decl(decoratorOnClassMethod13.ts, 0, 21)) +>target : Symbol(target, Decl(decoratorOnClassMethod13.ts, 0, 24)) +>propertyKey : Symbol(propertyKey, Decl(decoratorOnClassMethod13.ts, 0, 36)) +>descriptor : Symbol(descriptor, Decl(decoratorOnClassMethod13.ts, 0, 57)) >TypedPropertyDescriptor : Symbol(TypedPropertyDescriptor, Decl(lib.d.ts, 1171, 36)) ->T : Symbol(T, Decl(decoratorOnClassMethod13.ts, 0, 25)) +>T : Symbol(T, Decl(decoratorOnClassMethod13.ts, 0, 21)) >TypedPropertyDescriptor : Symbol(TypedPropertyDescriptor, Decl(lib.d.ts, 1171, 36)) ->T : Symbol(T, Decl(decoratorOnClassMethod13.ts, 0, 25)) +>T : Symbol(T, Decl(decoratorOnClassMethod13.ts, 0, 21)) class C { ->C : Symbol(C, Decl(decoratorOnClassMethod13.ts, 0, 132)) +>C : Symbol(C, Decl(decoratorOnClassMethod13.ts, 0, 126)) @dec ["1"]() { } >dec : Symbol(dec, Decl(decoratorOnClassMethod13.ts, 0, 0)) diff --git a/tests/baselines/reference/decoratorOnClassMethod13.types b/tests/baselines/reference/decoratorOnClassMethod13.types index 2858f8877bd..5fdbe071828 100644 --- a/tests/baselines/reference/decoratorOnClassMethod13.types +++ b/tests/baselines/reference/decoratorOnClassMethod13.types @@ -1,6 +1,6 @@ === tests/cases/conformance/decorators/class/method/decoratorOnClassMethod13.ts === -declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; ->dec : () => (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor >T : T >target : any >propertyKey : string @@ -14,10 +14,10 @@ class C { >C : C @dec ["1"]() { } ->dec : () => (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor >"1" : string @dec ["b"]() { } ->dec : () => (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor +>dec : (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor >"b" : string } diff --git a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt new file mode 100644 index 00000000000..ade416aefbc --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1220: Invalid expression for method decorator. + Supplied parameters do not match any signature of call target. + + +==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts (1 errors) ==== + declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; + + class C { + @dec ["method"]() {} + ~~~~ +!!! error TS1220: Invalid expression for method decorator. +!!! error TS1220: Supplied parameters do not match any signature of call target. + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod6.symbols b/tests/baselines/reference/decoratorOnClassMethod6.symbols deleted file mode 100644 index 8dcdd99a8e9..00000000000 --- a/tests/baselines/reference/decoratorOnClassMethod6.symbols +++ /dev/null @@ -1,18 +0,0 @@ -=== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts === -declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; ->dec : Symbol(dec, Decl(decoratorOnClassMethod6.ts, 0, 0)) ->T : Symbol(T, Decl(decoratorOnClassMethod6.ts, 0, 25)) ->target : Symbol(target, Decl(decoratorOnClassMethod6.ts, 0, 28)) ->propertyKey : Symbol(propertyKey, Decl(decoratorOnClassMethod6.ts, 0, 40)) ->descriptor : Symbol(descriptor, Decl(decoratorOnClassMethod6.ts, 0, 61)) ->TypedPropertyDescriptor : Symbol(TypedPropertyDescriptor, Decl(lib.d.ts, 1171, 36)) ->T : Symbol(T, Decl(decoratorOnClassMethod6.ts, 0, 25)) ->TypedPropertyDescriptor : Symbol(TypedPropertyDescriptor, Decl(lib.d.ts, 1171, 36)) ->T : Symbol(T, Decl(decoratorOnClassMethod6.ts, 0, 25)) - -class C { ->C : Symbol(C, Decl(decoratorOnClassMethod6.ts, 0, 132)) - - @dec ["method"]() {} ->dec : Symbol(dec, Decl(decoratorOnClassMethod6.ts, 0, 0)) -} diff --git a/tests/baselines/reference/decoratorOnClassMethod6.types b/tests/baselines/reference/decoratorOnClassMethod6.types deleted file mode 100644 index 9da71791763..00000000000 --- a/tests/baselines/reference/decoratorOnClassMethod6.types +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts === -declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; ->dec : () => (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor ->T : T ->target : any ->propertyKey : string ->descriptor : TypedPropertyDescriptor ->TypedPropertyDescriptor : TypedPropertyDescriptor ->T : T ->TypedPropertyDescriptor : TypedPropertyDescriptor ->T : T - -class C { ->C : C - - @dec ["method"]() {} ->dec : () => (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor ->"method" : string -} diff --git a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt new file mode 100644 index 00000000000..d0635b4f5f3 --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1220: Invalid expression for method decorator. + Supplied parameters do not match any signature of call target. + + +==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts (1 errors) ==== + declare function dec(target: T): T; + + class C { + @dec method() {} + ~~~~ +!!! error TS1220: Invalid expression for method decorator. +!!! error TS1220: Supplied parameters do not match any signature of call target. + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod8.symbols b/tests/baselines/reference/decoratorOnClassMethod8.symbols deleted file mode 100644 index 84b68b81421..00000000000 --- a/tests/baselines/reference/decoratorOnClassMethod8.symbols +++ /dev/null @@ -1,15 +0,0 @@ -=== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts === -declare function dec(target: T): T; ->dec : Symbol(dec, Decl(decoratorOnClassMethod8.ts, 0, 0)) ->T : Symbol(T, Decl(decoratorOnClassMethod8.ts, 0, 21)) ->target : Symbol(target, Decl(decoratorOnClassMethod8.ts, 0, 24)) ->T : Symbol(T, Decl(decoratorOnClassMethod8.ts, 0, 21)) ->T : Symbol(T, Decl(decoratorOnClassMethod8.ts, 0, 21)) - -class C { ->C : Symbol(C, Decl(decoratorOnClassMethod8.ts, 0, 38)) - - @dec method() {} ->dec : Symbol(dec, Decl(decoratorOnClassMethod8.ts, 0, 0)) ->method : Symbol(method, Decl(decoratorOnClassMethod8.ts, 2, 9)) -} diff --git a/tests/baselines/reference/decoratorOnClassMethod8.types b/tests/baselines/reference/decoratorOnClassMethod8.types deleted file mode 100644 index 20890b09846..00000000000 --- a/tests/baselines/reference/decoratorOnClassMethod8.types +++ /dev/null @@ -1,15 +0,0 @@ -=== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts === -declare function dec(target: T): T; ->dec : (target: T) => T ->T : T ->target : T ->T : T ->T : T - -class C { ->C : C - - @dec method() {} ->dec : (target: T) => T ->method : () => void -} diff --git a/tests/baselines/reference/decoratorOnClassMethodParameter1.js b/tests/baselines/reference/decoratorOnClassMethodParameter1.js index 4a3ed36eec5..a6ab1704acc 100644 --- a/tests/baselines/reference/decoratorOnClassMethodParameter1.js +++ b/tests/baselines/reference/decoratorOnClassMethodParameter1.js @@ -1,5 +1,5 @@ //// [decoratorOnClassMethodParameter1.ts] -declare function dec(target: Function, propertyKey: string | symbol, parameterIndex: number): void; +declare function dec(target: Object, propertyKey: string | symbol, parameterIndex: number): void; class C { method(@dec p: number) {} diff --git a/tests/baselines/reference/decoratorOnClassMethodParameter1.symbols b/tests/baselines/reference/decoratorOnClassMethodParameter1.symbols index 0ced8829766..47c5999ff47 100644 --- a/tests/baselines/reference/decoratorOnClassMethodParameter1.symbols +++ b/tests/baselines/reference/decoratorOnClassMethodParameter1.symbols @@ -1,13 +1,13 @@ === tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodParameter1.ts === -declare function dec(target: Function, propertyKey: string | symbol, parameterIndex: number): void; +declare function dec(target: Object, propertyKey: string | symbol, parameterIndex: number): void; >dec : Symbol(dec, Decl(decoratorOnClassMethodParameter1.ts, 0, 0)) >target : Symbol(target, Decl(decoratorOnClassMethodParameter1.ts, 0, 21)) ->Function : Symbol(Function, Decl(lib.d.ts, 223, 38), Decl(lib.d.ts, 269, 11)) ->propertyKey : Symbol(propertyKey, Decl(decoratorOnClassMethodParameter1.ts, 0, 38)) ->parameterIndex : Symbol(parameterIndex, Decl(decoratorOnClassMethodParameter1.ts, 0, 68)) +>Object : Symbol(Object, Decl(lib.d.ts, 92, 1), Decl(lib.d.ts, 223, 11)) +>propertyKey : Symbol(propertyKey, Decl(decoratorOnClassMethodParameter1.ts, 0, 36)) +>parameterIndex : Symbol(parameterIndex, Decl(decoratorOnClassMethodParameter1.ts, 0, 66)) class C { ->C : Symbol(C, Decl(decoratorOnClassMethodParameter1.ts, 0, 99)) +>C : Symbol(C, Decl(decoratorOnClassMethodParameter1.ts, 0, 97)) method(@dec p: number) {} >method : Symbol(method, Decl(decoratorOnClassMethodParameter1.ts, 2, 9)) diff --git a/tests/baselines/reference/decoratorOnClassMethodParameter1.types b/tests/baselines/reference/decoratorOnClassMethodParameter1.types index 0b75471471f..74aa04a8985 100644 --- a/tests/baselines/reference/decoratorOnClassMethodParameter1.types +++ b/tests/baselines/reference/decoratorOnClassMethodParameter1.types @@ -1,8 +1,8 @@ === tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodParameter1.ts === -declare function dec(target: Function, propertyKey: string | symbol, parameterIndex: number): void; ->dec : (target: Function, propertyKey: string | symbol, parameterIndex: number) => void ->target : Function ->Function : Function +declare function dec(target: Object, propertyKey: string | symbol, parameterIndex: number): void; +>dec : (target: Object, propertyKey: string | symbol, parameterIndex: number) => void +>target : Object +>Object : Object >propertyKey : string | symbol >parameterIndex : number @@ -11,6 +11,6 @@ class C { method(@dec p: number) {} >method : (p: number) => void ->dec : (target: Function, propertyKey: string | symbol, parameterIndex: number) => void +>dec : (target: Object, propertyKey: string | symbol, parameterIndex: number) => void >p : number } diff --git a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt new file mode 100644 index 00000000000..92b89b0b430 --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1220: Invalid expression for property decorator. + Supplied parameters do not match any signature of call target. + + +==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts (1 errors) ==== + declare function dec(): (target: any, propertyKey: string) => void; + + class C { + @dec prop; + ~~~~ +!!! error TS1220: Invalid expression for property decorator. +!!! error TS1220: Supplied parameters do not match any signature of call target. + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty11.symbols b/tests/baselines/reference/decoratorOnClassProperty11.symbols deleted file mode 100644 index c7d6e39c713..00000000000 --- a/tests/baselines/reference/decoratorOnClassProperty11.symbols +++ /dev/null @@ -1,14 +0,0 @@ -=== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts === -declare function dec(): (target: any, propertyKey: string) => void; ->dec : Symbol(dec, Decl(decoratorOnClassProperty11.ts, 0, 0)) ->T : Symbol(T, Decl(decoratorOnClassProperty11.ts, 0, 25)) ->target : Symbol(target, Decl(decoratorOnClassProperty11.ts, 0, 28)) ->propertyKey : Symbol(propertyKey, Decl(decoratorOnClassProperty11.ts, 0, 40)) - -class C { ->C : Symbol(C, Decl(decoratorOnClassProperty11.ts, 0, 70)) - - @dec prop; ->dec : Symbol(dec, Decl(decoratorOnClassProperty11.ts, 0, 0)) ->prop : Symbol(prop, Decl(decoratorOnClassProperty11.ts, 2, 9)) -} diff --git a/tests/baselines/reference/decoratorOnClassProperty11.types b/tests/baselines/reference/decoratorOnClassProperty11.types deleted file mode 100644 index 5caa467d3ba..00000000000 --- a/tests/baselines/reference/decoratorOnClassProperty11.types +++ /dev/null @@ -1,14 +0,0 @@ -=== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts === -declare function dec(): (target: any, propertyKey: string) => void; ->dec : () => (target: any, propertyKey: string) => void ->T : T ->target : any ->propertyKey : string - -class C { ->C : C - - @dec prop; ->dec : () => (target: any, propertyKey: string) => void ->prop : any -} diff --git a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt new file mode 100644 index 00000000000..441ff38a421 --- /dev/null +++ b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1220: Invalid expression for property decorator. + Supplied parameters do not match any signature of call target. + + +==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts (1 errors) ==== + declare function dec(target: Function): void; + + class C { + @dec prop; + ~~~~ +!!! error TS1220: Invalid expression for property decorator. +!!! error TS1220: Supplied parameters do not match any signature of call target. + } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty6.symbols b/tests/baselines/reference/decoratorOnClassProperty6.symbols deleted file mode 100644 index 7b9857e0a19..00000000000 --- a/tests/baselines/reference/decoratorOnClassProperty6.symbols +++ /dev/null @@ -1,13 +0,0 @@ -=== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts === -declare function dec(target: Function): void; ->dec : Symbol(dec, Decl(decoratorOnClassProperty6.ts, 0, 0)) ->target : Symbol(target, Decl(decoratorOnClassProperty6.ts, 0, 21)) ->Function : Symbol(Function, Decl(lib.d.ts, 223, 38), Decl(lib.d.ts, 269, 11)) - -class C { ->C : Symbol(C, Decl(decoratorOnClassProperty6.ts, 0, 45)) - - @dec prop; ->dec : Symbol(dec, Decl(decoratorOnClassProperty6.ts, 0, 0)) ->prop : Symbol(prop, Decl(decoratorOnClassProperty6.ts, 2, 9)) -} diff --git a/tests/baselines/reference/decoratorOnClassProperty6.types b/tests/baselines/reference/decoratorOnClassProperty6.types deleted file mode 100644 index 59d03678330..00000000000 --- a/tests/baselines/reference/decoratorOnClassProperty6.types +++ /dev/null @@ -1,13 +0,0 @@ -=== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts === -declare function dec(target: Function): void; ->dec : (target: Function) => void ->target : Function ->Function : Function - -class C { ->C : C - - @dec prop; ->dec : (target: Function) => void ->prop : any -} diff --git a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt index 8b93d0ab38e..e061ce446ac 100644 --- a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt @@ -1,4 +1,5 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS2322: Type '(target: Function, propertyKey: string | symbol, paramIndex: number) => void' is not assignable to type '(target: Object, propertyKey: string | symbol) => void'. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1220: Invalid expression for property decorator. + Supplied parameters do not match any signature of call target. ==== tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts (1 errors) ==== @@ -7,5 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4 class C { @dec prop; ~~~~ -!!! error TS2322: Type '(target: Function, propertyKey: string | symbol, paramIndex: number) => void' is not assignable to type '(target: Object, propertyKey: string | symbol) => void'. +!!! error TS1220: Invalid expression for property decorator. +!!! error TS1220: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/missingDecoratorType.errors.txt b/tests/baselines/reference/missingDecoratorType.errors.txt index 0b159a8fcb2..91b54fde54a 100644 --- a/tests/baselines/reference/missingDecoratorType.errors.txt +++ b/tests/baselines/reference/missingDecoratorType.errors.txt @@ -1,7 +1,17 @@ -error TS2318: Cannot find global type 'ClassDecorator'. +error TS2318: Cannot find global type 'TypedPropertyDescriptor'. -!!! error TS2318: Cannot find global type 'ClassDecorator'. +!!! error TS2318: Cannot find global type 'TypedPropertyDescriptor'. +==== tests/cases/conformance/decorators/b.ts (0 errors) ==== + /// + declare function dec(t, k, d); + + class C { + @dec + method() {} + } + + ==== tests/cases/conformance/decorators/a.ts (0 errors) ==== interface Object { } @@ -12,12 +22,4 @@ error TS2318: Cannot find global type 'ClassDecorator'. interface Function { } interface RegExp { } interface IArguments { } - -==== tests/cases/conformance/decorators/b.ts (0 errors) ==== - declare var dec: any; - - @dec - class C { - } - \ No newline at end of file diff --git a/tests/baselines/reference/missingDecoratorType.js b/tests/baselines/reference/missingDecoratorType.js index 4460abdc798..e65ca7dc341 100644 --- a/tests/baselines/reference/missingDecoratorType.js +++ b/tests/baselines/reference/missingDecoratorType.js @@ -12,10 +12,12 @@ interface RegExp { } interface IArguments { } //// [b.ts] -declare var dec: any; +/// +declare function dec(t, k, d); -@dec class C { + @dec + method() {} } @@ -30,11 +32,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; +/// var C = (function () { function C() { } - C = __decorate([ - dec - ], C); + C.prototype.method = function () { }; + Object.defineProperty(C.prototype, "method", + __decorate([ + dec + ], C.prototype, "method", Object.getOwnPropertyDescriptor(C.prototype, "method"))); return C; })(); diff --git a/tests/baselines/reference/noEmitHelpers2.js b/tests/baselines/reference/noEmitHelpers2.js index 1bd42377679..66e2ff78b64 100644 --- a/tests/baselines/reference/noEmitHelpers2.js +++ b/tests/baselines/reference/noEmitHelpers2.js @@ -1,6 +1,6 @@ //// [noEmitHelpers2.ts] -function decorator() { } +declare var decorator: any; @decorator class A { @@ -9,7 +9,6 @@ class A { } //// [noEmitHelpers2.js] -function decorator() { } var A = (function () { function A(a, b) { } diff --git a/tests/baselines/reference/noEmitHelpers2.symbols b/tests/baselines/reference/noEmitHelpers2.symbols index 3a3e3ec94c7..044026a3db7 100644 --- a/tests/baselines/reference/noEmitHelpers2.symbols +++ b/tests/baselines/reference/noEmitHelpers2.symbols @@ -1,17 +1,17 @@ === tests/cases/compiler/noEmitHelpers2.ts === -function decorator() { } ->decorator : Symbol(decorator, Decl(noEmitHelpers2.ts, 0, 0)) +declare var decorator: any; +>decorator : Symbol(decorator, Decl(noEmitHelpers2.ts, 1, 11)) @decorator ->decorator : Symbol(decorator, Decl(noEmitHelpers2.ts, 0, 0)) +>decorator : Symbol(decorator, Decl(noEmitHelpers2.ts, 1, 11)) class A { ->A : Symbol(A, Decl(noEmitHelpers2.ts, 1, 24)) +>A : Symbol(A, Decl(noEmitHelpers2.ts, 1, 27)) constructor(a: number, @decorator b: string) { >a : Symbol(a, Decl(noEmitHelpers2.ts, 5, 16)) ->decorator : Symbol(decorator, Decl(noEmitHelpers2.ts, 0, 0)) +>decorator : Symbol(decorator, Decl(noEmitHelpers2.ts, 1, 11)) >b : Symbol(b, Decl(noEmitHelpers2.ts, 5, 26)) } } diff --git a/tests/baselines/reference/noEmitHelpers2.types b/tests/baselines/reference/noEmitHelpers2.types index 2a5b5413a7e..14260e4f95c 100644 --- a/tests/baselines/reference/noEmitHelpers2.types +++ b/tests/baselines/reference/noEmitHelpers2.types @@ -1,17 +1,17 @@ === tests/cases/compiler/noEmitHelpers2.ts === -function decorator() { } ->decorator : () => void +declare var decorator: any; +>decorator : any @decorator ->decorator : () => void +>decorator : any class A { >A : A constructor(a: number, @decorator b: string) { >a : number ->decorator : () => void +>decorator : any >b : string } } diff --git a/tests/baselines/reference/sourceMapValidationDecorators.js b/tests/baselines/reference/sourceMapValidationDecorators.js index f858aeff586..5196d3b0dd8 100644 --- a/tests/baselines/reference/sourceMapValidationDecorators.js +++ b/tests/baselines/reference/sourceMapValidationDecorators.js @@ -3,8 +3,8 @@ declare function ClassDecorator1(target: Function): void; declare function ClassDecorator2(x: number): (target: Function) => void; declare function PropertyDecorator1(target: Object, key: string | symbol, descriptor?: PropertyDescriptor): void; declare function PropertyDecorator2(x: number): (target: Object, key: string | symbol, descriptor?: PropertyDescriptor) => void; -declare function ParameterDecorator1(target: Function, key: string | symbol, paramIndex: number): void; -declare function ParameterDecorator2(x: number): (target: Function, key: string | symbol, paramIndex: number) => void; +declare function ParameterDecorator1(target: Object, key: string | symbol, paramIndex: number): void; +declare function ParameterDecorator2(x: number): (target: Object, key: string | symbol, paramIndex: number) => void; @ClassDecorator1 @ClassDecorator2(10) diff --git a/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt b/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt index 68ad353db9f..b7036723a85 100644 --- a/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt +++ b/tests/baselines/reference/sourceMapValidationDecorators.sourcemap.txt @@ -26,8 +26,8 @@ sourceFile:sourceMapValidationDecorators.ts >declare function ClassDecorator2(x: number): (target: Function) => void; >declare function PropertyDecorator1(target: Object, key: string | symbol, descriptor?: PropertyDescriptor): void; >declare function PropertyDecorator2(x: number): (target: Object, key: string | symbol, descriptor?: PropertyDescriptor) => void; - >declare function ParameterDecorator1(target: Function, key: string | symbol, paramIndex: number): void; - >declare function ParameterDecorator2(x: number): (target: Function, key: string | symbol, paramIndex: number) => void; + >declare function ParameterDecorator1(target: Object, key: string | symbol, paramIndex: number): void; + >declare function ParameterDecorator2(x: number): (target: Object, key: string | symbol, paramIndex: number) => void; > > 1 >Emitted(12, 1) Source(8, 1) + SourceIndex(0) diff --git a/tests/baselines/reference/sourceMapValidationDecorators.symbols b/tests/baselines/reference/sourceMapValidationDecorators.symbols index 37db95d3e05..e22afb7b7fc 100644 --- a/tests/baselines/reference/sourceMapValidationDecorators.symbols +++ b/tests/baselines/reference/sourceMapValidationDecorators.symbols @@ -27,20 +27,20 @@ declare function PropertyDecorator2(x: number): (target: Object, key: string | s >descriptor : Symbol(descriptor, Decl(sourceMapValidationDecorators.ts, 3, 86)) >PropertyDescriptor : Symbol(PropertyDescriptor, Decl(lib.d.ts, 79, 66)) -declare function ParameterDecorator1(target: Function, key: string | symbol, paramIndex: number): void; +declare function ParameterDecorator1(target: Object, key: string | symbol, paramIndex: number): void; >ParameterDecorator1 : Symbol(ParameterDecorator1, Decl(sourceMapValidationDecorators.ts, 3, 128)) >target : Symbol(target, Decl(sourceMapValidationDecorators.ts, 4, 37)) ->Function : Symbol(Function, Decl(lib.d.ts, 223, 38), Decl(lib.d.ts, 269, 11)) ->key : Symbol(key, Decl(sourceMapValidationDecorators.ts, 4, 54)) ->paramIndex : Symbol(paramIndex, Decl(sourceMapValidationDecorators.ts, 4, 76)) +>Object : Symbol(Object, Decl(lib.d.ts, 92, 1), Decl(lib.d.ts, 223, 11)) +>key : Symbol(key, Decl(sourceMapValidationDecorators.ts, 4, 52)) +>paramIndex : Symbol(paramIndex, Decl(sourceMapValidationDecorators.ts, 4, 74)) -declare function ParameterDecorator2(x: number): (target: Function, key: string | symbol, paramIndex: number) => void; ->ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 103)) +declare function ParameterDecorator2(x: number): (target: Object, key: string | symbol, paramIndex: number) => void; +>ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 101)) >x : Symbol(x, Decl(sourceMapValidationDecorators.ts, 5, 37)) >target : Symbol(target, Decl(sourceMapValidationDecorators.ts, 5, 50)) ->Function : Symbol(Function, Decl(lib.d.ts, 223, 38), Decl(lib.d.ts, 269, 11)) ->key : Symbol(key, Decl(sourceMapValidationDecorators.ts, 5, 67)) ->paramIndex : Symbol(paramIndex, Decl(sourceMapValidationDecorators.ts, 5, 89)) +>Object : Symbol(Object, Decl(lib.d.ts, 92, 1), Decl(lib.d.ts, 223, 11)) +>key : Symbol(key, Decl(sourceMapValidationDecorators.ts, 5, 65)) +>paramIndex : Symbol(paramIndex, Decl(sourceMapValidationDecorators.ts, 5, 87)) @ClassDecorator1 >ClassDecorator1 : Symbol(ClassDecorator1, Decl(sourceMapValidationDecorators.ts, 0, 0)) @@ -49,14 +49,14 @@ declare function ParameterDecorator2(x: number): (target: Function, key: string >ClassDecorator2 : Symbol(ClassDecorator2, Decl(sourceMapValidationDecorators.ts, 0, 57)) class Greeter { ->Greeter : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 118)) +>Greeter : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 116)) constructor( @ParameterDecorator1 >ParameterDecorator1 : Symbol(ParameterDecorator1, Decl(sourceMapValidationDecorators.ts, 3, 128)) @ParameterDecorator2(20) ->ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 103)) +>ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 101)) public greeting: string, >greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) @@ -65,7 +65,7 @@ class Greeter { >ParameterDecorator1 : Symbol(ParameterDecorator1, Decl(sourceMapValidationDecorators.ts, 3, 128)) @ParameterDecorator2(30) ->ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 103)) +>ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 101)) ...b: string[]) { >b : Symbol(b, Decl(sourceMapValidationDecorators.ts, 13, 30)) @@ -82,7 +82,7 @@ class Greeter { return "

" + this.greeting + "

"; >this.greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) ->this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 118)) +>this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 116)) >greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) } @@ -111,14 +111,14 @@ class Greeter { >ParameterDecorator1 : Symbol(ParameterDecorator1, Decl(sourceMapValidationDecorators.ts, 3, 128)) @ParameterDecorator2(70) ->ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 103)) +>ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 101)) x: number) { >x : Symbol(x, Decl(sourceMapValidationDecorators.ts, 34, 15)) return this.greeting; >this.greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) ->this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 118)) +>this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 116)) >greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) } @@ -133,7 +133,7 @@ class Greeter { return this.greeting; >this.greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) ->this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 118)) +>this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 116)) >greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) } @@ -144,14 +144,14 @@ class Greeter { >ParameterDecorator1 : Symbol(ParameterDecorator1, Decl(sourceMapValidationDecorators.ts, 3, 128)) @ParameterDecorator2(90) ->ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 103)) +>ParameterDecorator2 : Symbol(ParameterDecorator2, Decl(sourceMapValidationDecorators.ts, 4, 101)) greetings: string) { >greetings : Symbol(greetings, Decl(sourceMapValidationDecorators.ts, 47, 18)) this.greeting = greetings; >this.greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) ->this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 118)) +>this : Symbol(Greeter, Decl(sourceMapValidationDecorators.ts, 5, 116)) >greeting : Symbol(greeting, Decl(sourceMapValidationDecorators.ts, 10, 16)) >greetings : Symbol(greetings, Decl(sourceMapValidationDecorators.ts, 47, 18)) } diff --git a/tests/baselines/reference/sourceMapValidationDecorators.types b/tests/baselines/reference/sourceMapValidationDecorators.types index 182f68570bc..9e83bb03509 100644 --- a/tests/baselines/reference/sourceMapValidationDecorators.types +++ b/tests/baselines/reference/sourceMapValidationDecorators.types @@ -27,18 +27,18 @@ declare function PropertyDecorator2(x: number): (target: Object, key: string | s >descriptor : PropertyDescriptor >PropertyDescriptor : PropertyDescriptor -declare function ParameterDecorator1(target: Function, key: string | symbol, paramIndex: number): void; ->ParameterDecorator1 : (target: Function, key: string | symbol, paramIndex: number) => void ->target : Function ->Function : Function +declare function ParameterDecorator1(target: Object, key: string | symbol, paramIndex: number): void; +>ParameterDecorator1 : (target: Object, key: string | symbol, paramIndex: number) => void +>target : Object +>Object : Object >key : string | symbol >paramIndex : number -declare function ParameterDecorator2(x: number): (target: Function, key: string | symbol, paramIndex: number) => void; ->ParameterDecorator2 : (x: number) => (target: Function, key: string | symbol, paramIndex: number) => void +declare function ParameterDecorator2(x: number): (target: Object, key: string | symbol, paramIndex: number) => void; +>ParameterDecorator2 : (x: number) => (target: Object, key: string | symbol, paramIndex: number) => void >x : number ->target : Function ->Function : Function +>target : Object +>Object : Object >key : string | symbol >paramIndex : number @@ -55,22 +55,22 @@ class Greeter { constructor( @ParameterDecorator1 ->ParameterDecorator1 : (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator1 : (target: Object, key: string | symbol, paramIndex: number) => void @ParameterDecorator2(20) ->ParameterDecorator2(20) : (target: Function, key: string | symbol, paramIndex: number) => void ->ParameterDecorator2 : (x: number) => (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2(20) : (target: Object, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2 : (x: number) => (target: Object, key: string | symbol, paramIndex: number) => void >20 : number public greeting: string, >greeting : string @ParameterDecorator1 ->ParameterDecorator1 : (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator1 : (target: Object, key: string | symbol, paramIndex: number) => void @ParameterDecorator2(30) ->ParameterDecorator2(30) : (target: Function, key: string | symbol, paramIndex: number) => void ->ParameterDecorator2 : (x: number) => (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2(30) : (target: Object, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2 : (x: number) => (target: Object, key: string | symbol, paramIndex: number) => void >30 : number ...b: string[]) { @@ -125,11 +125,11 @@ class Greeter { >fn : (x: number) => string @ParameterDecorator1 ->ParameterDecorator1 : (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator1 : (target: Object, key: string | symbol, paramIndex: number) => void @ParameterDecorator2(70) ->ParameterDecorator2(70) : (target: Function, key: string | symbol, paramIndex: number) => void ->ParameterDecorator2 : (x: number) => (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2(70) : (target: Object, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2 : (x: number) => (target: Object, key: string | symbol, paramIndex: number) => void >70 : number x: number) { @@ -162,11 +162,11 @@ class Greeter { >greetings : string @ParameterDecorator1 ->ParameterDecorator1 : (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator1 : (target: Object, key: string | symbol, paramIndex: number) => void @ParameterDecorator2(90) ->ParameterDecorator2(90) : (target: Function, key: string | symbol, paramIndex: number) => void ->ParameterDecorator2 : (x: number) => (target: Function, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2(90) : (target: Object, key: string | symbol, paramIndex: number) => void +>ParameterDecorator2 : (x: number) => (target: Object, key: string | symbol, paramIndex: number) => void >90 : number greetings: string) { diff --git a/tests/cases/compiler/noEmitHelpers2.ts b/tests/cases/compiler/noEmitHelpers2.ts index df71f4fae82..c794261c65f 100644 --- a/tests/cases/compiler/noEmitHelpers2.ts +++ b/tests/cases/compiler/noEmitHelpers2.ts @@ -2,7 +2,7 @@ // @emitdecoratormetadata: true // @target: es5 -function decorator() { } +declare var decorator: any; @decorator class A { diff --git a/tests/cases/compiler/sourceMapValidationDecorators.ts b/tests/cases/compiler/sourceMapValidationDecorators.ts index c8bd16be80f..f755700197a 100644 --- a/tests/cases/compiler/sourceMapValidationDecorators.ts +++ b/tests/cases/compiler/sourceMapValidationDecorators.ts @@ -4,8 +4,8 @@ declare function ClassDecorator1(target: Function): void; declare function ClassDecorator2(x: number): (target: Function) => void; declare function PropertyDecorator1(target: Object, key: string | symbol, descriptor?: PropertyDescriptor): void; declare function PropertyDecorator2(x: number): (target: Object, key: string | symbol, descriptor?: PropertyDescriptor) => void; -declare function ParameterDecorator1(target: Function, key: string | symbol, paramIndex: number): void; -declare function ParameterDecorator2(x: number): (target: Function, key: string | symbol, paramIndex: number) => void; +declare function ParameterDecorator1(target: Object, key: string | symbol, paramIndex: number): void; +declare function ParameterDecorator2(x: number): (target: Object, key: string | symbol, paramIndex: number) => void; @ClassDecorator1 @ClassDecorator2(10) diff --git a/tests/cases/conformance/decorators/class/decoratedClassFromExternalModule.ts b/tests/cases/conformance/decorators/class/decoratedClassFromExternalModule.ts index cb622265b44..979bb28965a 100644 --- a/tests/cases/conformance/decorators/class/decoratedClassFromExternalModule.ts +++ b/tests/cases/conformance/decorators/class/decoratedClassFromExternalModule.ts @@ -1,6 +1,6 @@ // @target: es6 // @Filename: decorated.ts -function decorate() { } +function decorate(target: any) { } @decorate export default class Decorated { } diff --git a/tests/cases/conformance/decorators/class/decoratorChecksFunctionBodies.ts b/tests/cases/conformance/decorators/class/decoratorChecksFunctionBodies.ts index 31f5fe82551..8a9cb6a7ecf 100644 --- a/tests/cases/conformance/decorators/class/decoratorChecksFunctionBodies.ts +++ b/tests/cases/conformance/decorators/class/decoratorChecksFunctionBodies.ts @@ -5,7 +5,7 @@ function func(s: string): void { } class A { - @(x => { + @((x, p) => { var a = 3; func(a); return x; diff --git a/tests/cases/conformance/decorators/class/decoratorInstantiateModulesInFunctionBodies.ts b/tests/cases/conformance/decorators/class/decoratorInstantiateModulesInFunctionBodies.ts index 7fa7ab8dd84..ce153d2fef0 100644 --- a/tests/cases/conformance/decorators/class/decoratorInstantiateModulesInFunctionBodies.ts +++ b/tests/cases/conformance/decorators/class/decoratorInstantiateModulesInFunctionBodies.ts @@ -9,7 +9,7 @@ export var test = 'abc'; import { test } from './a'; function filter(handler: any) { - return function (target: any) { + return function (target: any, propertyKey: string) { // ... }; } diff --git a/tests/cases/conformance/decorators/class/method/decoratorOnClassMethod13.ts b/tests/cases/conformance/decorators/class/method/decoratorOnClassMethod13.ts index df0b847e99d..f506af5d841 100644 --- a/tests/cases/conformance/decorators/class/method/decoratorOnClassMethod13.ts +++ b/tests/cases/conformance/decorators/class/method/decoratorOnClassMethod13.ts @@ -1,5 +1,5 @@ // @target: ES6 -declare function dec(): (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor; +declare function dec(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor; class C { @dec ["1"]() { } diff --git a/tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodParameter1.ts b/tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodParameter1.ts index e525933fb6a..fa9c85c6f8e 100644 --- a/tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodParameter1.ts +++ b/tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodParameter1.ts @@ -1,5 +1,5 @@ // @target:es5 -declare function dec(target: Function, propertyKey: string | symbol, parameterIndex: number): void; +declare function dec(target: Object, propertyKey: string | symbol, parameterIndex: number): void; class C { method(@dec p: number) {} diff --git a/tests/cases/conformance/decorators/missingDecoratorType.ts b/tests/cases/conformance/decorators/missingDecoratorType.ts index 1407e00b7a3..286595d450e 100644 --- a/tests/cases/conformance/decorators/missingDecoratorType.ts +++ b/tests/cases/conformance/decorators/missingDecoratorType.ts @@ -1,4 +1,4 @@ -// @target: ES5 +// @target: ES5 // @noLib: true // @Filename: a.ts @@ -11,11 +11,12 @@ interface Function { } interface RegExp { } interface IArguments { } -// @Filename: b.ts +// @Filename: b.ts /// -declare var dec: any; +declare function dec(t, k, d); -@dec class C { + @dec + method() {} } From 666a0db6ae646e2f0eba192055ad6c70269dac13 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 22 May 2015 23:56:41 -0700 Subject: [PATCH 05/79] PR Feedback --- src/compiler/checker.ts | 279 ++++++++++-------- .../diagnosticInformationMap.generated.ts | 2 +- src/compiler/diagnosticMessages.json | 2 +- src/compiler/utilities.ts | 7 +- .../reference/decoratorOnClass8.errors.txt | 4 +- .../decoratorOnClassMethod10.errors.txt | 4 +- .../decoratorOnClassMethod6.errors.txt | 4 +- .../decoratorOnClassMethod8.errors.txt | 4 +- .../decoratorOnClassProperty11.errors.txt | 4 +- .../decoratorOnClassProperty6.errors.txt | 4 +- .../decoratorOnClassProperty7.errors.txt | 4 +- 11 files changed, 174 insertions(+), 144 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e99dd7eeb4e..6cd98c43529 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6774,13 +6774,29 @@ module ts { let arg = args[i]; if (arg.kind !== SyntaxKind.OmittedExpression) { let paramType = getTypeAtPosition(signature, i); - let argType = getSyntheticArgumentType(i, arg); + let argType: Type; + if (arg.parent.kind === SyntaxKind.Decorator) { + if (i === 0) { + argType = getDecoratorTargetArgumentType(arg.parent.parent); + } + else if (i === 1) { + argType = getDecoratorPropertyKeyArgumentType(arg.parent.parent); + } + else if (i === 2) { + argType = getDecoratorPropertyIndexOrDescriptorArgumentType(arg.parent.parent); + } + } + else if (i === 0 && arg.parent.kind === SyntaxKind.TaggedTemplateExpression) { + argType = globalTemplateStringsArrayType; + } + if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } + inferTypes(context, argType, paramType); } } @@ -6838,140 +6854,151 @@ module ts { : emptyObjectType; } - /** - * Gets the type for a synthetic argument when resolving the first argument for a TaggedTemplateExpression - * or any arguments to a Decorator. - */ - function getSyntheticArgumentType(argumentIndex: number, arg: Expression): Type { - if (arg.parent.kind === SyntaxKind.Decorator) { - let decorator = arg.parent; - let parent = decorator.parent; - if (argumentIndex === 0) { - // The first argument to a decorator is its `target`. - switch (parent.kind) { - case SyntaxKind.ClassDeclaration: - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - let classSymbol = getSymbolOfNode(parent); - return getTypeOfSymbol(classSymbol); - - case SyntaxKind.Parameter: - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - parent = parent.parent; - if (parent.kind === SyntaxKind.Constructor) { - let classSymbol = getSymbolOfNode(parent); - return getTypeOfSymbol(classSymbol); - } - - // fall-through - - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getTypeOfParentOfClassElement(parent); + function getDecoratorTargetArgumentType(target: Node): Type { + // The first argument to a decorator is its `target`. + switch (target.kind) { + case SyntaxKind.ClassDeclaration: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + let classSymbol = getSymbolOfNode(target); + return getTypeOfSymbol(classSymbol); + + case SyntaxKind.Parameter: + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + target = target.parent; + if (target.kind === SyntaxKind.Constructor) { + let classSymbol = getSymbolOfNode(target); + return getTypeOfSymbol(classSymbol); } - } - else if (argumentIndex === 1) { - // The second argument to a decorator is its `propertyKey` - switch (parent.kind) { - case SyntaxKind.ClassDeclaration: - Debug.fail("Class decorators should not have a second synthetic argument."); - - case SyntaxKind.Parameter: - parent = parent.parent; - if (parent.kind === SyntaxKind.Constructor) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - - // fall-through - - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - let element = decorator.parent; - switch (element.name.kind) { - case SyntaxKind.Identifier: - case SyntaxKind.NumericLiteral: - case SyntaxKind.StringLiteral: - return getStringLiteralType(element.name); - - case SyntaxKind.ComputedPropertyName: - let nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { - return nameType; - } - else { - return stringType; - } - } - } - } - else if (argumentIndex === 2) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a paramter decorator - switch (parent.kind) { - case SyntaxKind.ClassDeclaration: - Debug.fail("Class decorators should not have a third synthetic argument."); - break; - - case SyntaxKind.Parameter: - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - - case SyntaxKind.PropertyDeclaration: - Debug.fail("Property decorators should not have a third synthetic argument."); - break; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - let propertyType: Type = getTypeOfNode(parent); - return createTypedPropertyDescriptorType(propertyType); - } - } + + // fall-through + + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getTypeOfParentOfClassElement(target); + + default: + return undefined; } - else if (argumentIndex === 0 && arg.parent.kind === SyntaxKind.TaggedTemplateExpression) { - return globalTemplateStringsArrayType; - } - - return undefined; } + + function getDecoratorPropertyKeyArgumentType(target: Node) { + // The second argument to a decorator is its `propertyKey` + switch (target.kind) { + case SyntaxKind.ClassDeclaration: + Debug.fail("Class decorators should not have a second synthetic argument."); + + case SyntaxKind.Parameter: + target = target.parent; + if (target.kind === SyntaxKind.Constructor) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + + // fall-through + + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + let element = target; + switch (element.name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.NumericLiteral: + case SyntaxKind.StringLiteral: + return getStringLiteralType(element.name); + + case SyntaxKind.ComputedPropertyName: + let nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { + return nameType; + } + else { + return stringType; + } + } + } + } + + function getDecoratorPropertyIndexOrDescriptorArgumentType(parent: Node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a paramter decorator + switch (parent.kind) { + case SyntaxKind.ClassDeclaration: + Debug.fail("Class decorators should not have a third synthetic argument."); + break; + case SyntaxKind.Parameter: + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + + case SyntaxKind.PropertyDeclaration: + Debug.fail("Property decorators should not have a third synthetic argument."); + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + let propertyType: Type = getTypeOfNode(parent); + return createTypedPropertyDescriptorType(propertyType); + } + } + function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean, containingMessageChain?: DiagnosticMessageChain) { for (let i = 0; i < args.length; i++) { let arg = args[i]; if (arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) let paramType = getTypeAtPosition(signature, i); - // A tagged template expression provides a special first argument, and string literals get string literal types + + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types // unless we're reporting errors - let argType = getSyntheticArgumentType(i, arg); + let argType: Type; + if (arg.parent.kind === SyntaxKind.Decorator) { + if (i === 0) { + argType = getDecoratorTargetArgumentType(arg.parent.parent); + } + else if (i === 1) { + argType = getDecoratorPropertyKeyArgumentType(arg.parent.parent); + } + else if (i === 2) { + argType = getDecoratorPropertyIndexOrDescriptorArgumentType(arg.parent.parent); + } + } + else if (i === 0 && arg.parent.kind === SyntaxKind.TaggedTemplateExpression) { + argType = globalTemplateStringsArrayType; + } + if (argType === undefined) { - argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors - ? getStringLiteralType(arg) - : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + if (arg.kind === SyntaxKind.StringLiteral && !reportErrors) { + argType = getStringLiteralType(arg); + } + else { + argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + } } // Use argument expression as error location when reporting errors - if (!checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, containingMessageChain)) { + let errorNode = reportErrors ? arg : undefined; + let headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage, containingMessageChain)) { return false; } } @@ -6986,7 +7013,8 @@ module ts { * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution * expressions, where the first element of the list is the template for error reporting purposes. * If 'node' is a Decorator, a new argument list is constructed with the decorator - * expression as a placeholder. + * expression as a placeholder to help when choosing an applicable signature and + * for error reporting purposes. */ function getEffectiveCallArguments(node: CallLikeExpression): Expression[] { let args: Expression[]; @@ -7082,6 +7110,9 @@ module ts { // // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. let excludeArgument: boolean[]; if (!isDecorator) { for (let i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { @@ -7441,7 +7472,9 @@ module ts { break; } - let diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Invalid_expression_for_0_decorator, decoratorKind); + let diagnosticChainHead = chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.Unable_to_resolve_signature_of_0_decorator_when_called_as_an_expression, decoratorKind); if (!callSignatures.length) { let errorInfo = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); errorInfo = concatenateDiagnosticMessageChains(diagnosticChainHead, errorInfo); @@ -9140,7 +9173,7 @@ module ts { diagnosticChainHead = chainDiagnosticMessages( diagnosticChainHead, - Diagnostics.Invalid_expression_for_0_decorator, + Diagnostics.Unable_to_resolve_signature_of_0_decorator_when_called_as_an_expression, decoratorKind); checkTypeAssignableTo(returnType, expectedReturnType, node, /*headMessage*/ undefined, diagnosticChainHead); diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 1eaf69d8886..a1b776611f7 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -175,7 +175,7 @@ module ts { Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: DiagnosticCategory.Error, key: "Export assignment is not supported when '--module' flag is 'system'." }, The_return_type_of_a_0_decorator_function_must_be_either_void_or_any: { code: 1219, category: DiagnosticCategory.Error, key: "The return type of a {0} decorator function must be either 'void' or 'any'." }, - Invalid_expression_for_0_decorator: { code: 1220, category: DiagnosticCategory.Error, key: "Invalid expression for {0} decorator." }, + Unable_to_resolve_signature_of_0_decorator_when_called_as_an_expression: { code: 1220, category: DiagnosticCategory.Error, key: "Unable to resolve signature of {0} decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 36f7505fc65..27238db5d95 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -687,7 +687,7 @@ "category": "Error", "code": 1219 }, - "Invalid expression for {0} decorator.": { + "Unable to resolve signature of {0} decorator when called as an expression.": { "category": "Error", "code": 1220 }, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index e720c7a112e..f1239b87629 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -620,12 +620,9 @@ module ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { return (node).tag; } - else if (node.kind === SyntaxKind.Decorator) { - return (node).expression; - } - // Will either be a CallExpression or NewExpression. - return (node).expression; + // Will either be a CallExpression, NewExpression, or Decorator. + return (node).expression; } export function nodeCanBeDecorated(node: Node): boolean { diff --git a/tests/baselines/reference/decoratorOnClass8.errors.txt b/tests/baselines/reference/decoratorOnClass8.errors.txt index 31abd9e2300..b5e27b4b3cb 100644 --- a/tests/baselines/reference/decoratorOnClass8.errors.txt +++ b/tests/baselines/reference/decoratorOnClass8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1220: Invalid expression for class decorator. +tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1220: Unable to resolve signature of class decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -7,7 +7,7 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1220 @dec() ~~~~~~ -!!! error TS1220: Invalid expression for class decorator. +!!! error TS1220: Unable to resolve signature of class decorator when called as an expression. !!! error TS1220: Supplied parameters do not match any signature of call target. class C { } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod10.errors.txt b/tests/baselines/reference/decoratorOnClassMethod10.errors.txt index bfc56717e6c..1d94f08f2a2 100644 --- a/tests/baselines/reference/decoratorOnClassMethod10.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6): error TS1220: Invalid expression for method decorator. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6): error TS1220: Unable to resolve signature of method decorator when called as an expression. Argument of type 'C' is not assignable to parameter of type 'Function'. Property 'apply' is missing in type 'C'. @@ -9,7 +9,7 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6) class C { @dec method() {} ~~~ -!!! error TS1220: Invalid expression for method decorator. +!!! error TS1220: Unable to resolve signature of method decorator when called as an expression. !!! error TS1220: Argument of type 'C' is not assignable to parameter of type 'Function'. !!! error TS1220: Property 'apply' is missing in type 'C'. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt index ade416aefbc..2231d0da56d 100644 --- a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1220: Invalid expression for method decorator. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1220: Unable to resolve signature of method decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): class C { @dec ["method"]() {} ~~~~ -!!! error TS1220: Invalid expression for method decorator. +!!! error TS1220: Unable to resolve signature of method decorator when called as an expression. !!! error TS1220: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt index d0635b4f5f3..d80fe7e05f7 100644 --- a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1220: Invalid expression for method decorator. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1220: Unable to resolve signature of method decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): class C { @dec method() {} ~~~~ -!!! error TS1220: Invalid expression for method decorator. +!!! error TS1220: Unable to resolve signature of method decorator when called as an expression. !!! error TS1220: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt index 92b89b0b430..8dad5dc955f 100644 --- a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1220: Invalid expression for property decorator. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1220: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts( class C { @dec prop; ~~~~ -!!! error TS1220: Invalid expression for property decorator. +!!! error TS1220: Unable to resolve signature of property decorator when called as an expression. !!! error TS1220: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt index 441ff38a421..eca97e803e0 100644 --- a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1220: Invalid expression for property decorator. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1220: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4 class C { @dec prop; ~~~~ -!!! error TS1220: Invalid expression for property decorator. +!!! error TS1220: Unable to resolve signature of property decorator when called as an expression. !!! error TS1220: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt index e061ce446ac..7f2249e5934 100644 --- a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1220: Invalid expression for property decorator. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1220: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4 class C { @dec prop; ~~~~ -!!! error TS1220: Invalid expression for property decorator. +!!! error TS1220: Unable to resolve signature of property decorator when called as an expression. !!! error TS1220: Supplied parameters do not match any signature of call target. } \ No newline at end of file From e20be958122788560753e67dda48792f7bca6fc6 Mon Sep 17 00:00:00 2001 From: SaschaNaz Date: Sat, 23 May 2015 17:47:13 +0900 Subject: [PATCH 06/79] fixing some types --- src/services/formatting/smartIndenter.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index a02dc4454fa..712c8a2f93f 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -295,9 +295,11 @@ module ts.formatting { } function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorOptions): number { - if (node.parent.kind === SyntaxKind.CallExpression) { - let parentExpression = (node.parent).expression; - let startingExpression = getStartingExpression(parentExpression); + if (node.parent.kind === SyntaxKind.CallExpression || + node.parent.kind === SyntaxKind.NewExpression) { + + let parentExpression = (node.parent).expression; + let startingExpression = getStartingExpression(parentExpression); if (parentExpression === startingExpression) { return Value.Unknown; @@ -314,9 +316,9 @@ module ts.formatting { } return Value.Unknown; - function getStartingExpression(expression: CallExpression) { + function getStartingExpression(expression: PropertyAccessExpression | CallExpression | ElementAccessExpression) { while (expression.expression) - expression = expression.expression; + expression = expression.expression; return expression; } } From 50a02237d1fc2deb2001214843ab01f0b9cae61c Mon Sep 17 00:00:00 2001 From: SaschaNaz Date: Sun, 24 May 2015 14:38:17 +0900 Subject: [PATCH 07/79] getLineIndentation for others --- src/services/formatting/smartIndenter.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 712c8a2f93f..4bd7fd66411 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -66,6 +66,10 @@ module ts.formatting { if (actualIndentation !== Value.Unknown) { return actualIndentation; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== Value.Unknown) { + return actualIndentation + options.IndentSize; + } previous = current; current = current.parent; @@ -122,6 +126,10 @@ module ts.formatting { if (actualIndentation !== Value.Unknown) { return actualIndentation + indentationDelta; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== Value.Unknown) { + return actualIndentation + indentationDelta; + } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line @@ -279,14 +287,7 @@ module ts.formatting { function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number { let containingList = getContainingList(node, sourceFile); - - if (containingList) { - let lineIndentation = getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options); - if (lineIndentation !== Value.Unknown) - return lineIndentation; - return getActualIndentationFromList(containingList); - } - return Value.Unknown; + return containingList ? getActualIndentationFromList(containingList) : Value.Unknown; function getActualIndentationFromList(list: Node[]): number { let index = indexOf(list, node); @@ -295,8 +296,9 @@ module ts.formatting { } function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorOptions): number { - if (node.parent.kind === SyntaxKind.CallExpression || - node.parent.kind === SyntaxKind.NewExpression) { + if (node.parent && ( + node.parent.kind === SyntaxKind.CallExpression || + node.parent.kind === SyntaxKind.NewExpression)) { let parentExpression = (node.parent).expression; let startingExpression = getStartingExpression(parentExpression); From f559d061eceefe539c117f544dba254c7a98731e Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 27 May 2015 10:19:37 -0700 Subject: [PATCH 08/79] PR feedback and minor refactoring --- src/compiler/checker.ts | 714 ++++++++++-------- .../diagnosticInformationMap.generated.ts | 8 +- src/compiler/diagnosticMessages.json | 21 +- .../reference/decoratorOnClass8.errors.txt | 6 +- .../decoratorOnClassMethod10.errors.txt | 10 +- .../decoratorOnClassMethod6.errors.txt | 6 +- .../decoratorOnClassMethod8.errors.txt | 6 +- .../decoratorOnClassProperty11.errors.txt | 6 +- .../decoratorOnClassProperty6.errors.txt | 6 +- .../decoratorOnClassProperty7.errors.txt | 6 +- 10 files changed, 455 insertions(+), 334 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6cd98c43529..57e1f8190f0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3504,6 +3504,16 @@ module ts { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + /** + * Creates a TypeReference for a generic `TypedPropertyDescriptor`. + */ + function createTypedPropertyDescriptorType(propertyType: Type): Type { + let globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyObjectType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } + function createIterableType(elementType: Type): Type { return globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [elementType]) : emptyObjectType; } @@ -6605,7 +6615,8 @@ module ts { function getSpreadArgumentIndex(args: Expression[]): number { for (let i = 0; i < args.length; i++) { - if (args[i].kind === SyntaxKind.SpreadElementExpression) { + let arg = args[i]; + if (arg && arg.kind === SyntaxKind.SpreadElementExpression) { return i; } } @@ -6616,7 +6627,8 @@ module ts { let adjustedArgCount: number; // Apparent number of arguments we will have in this call let typeArguments: NodeArray; // Type arguments (undefined if none) let callIsIncomplete: boolean; // In incomplete call we want to be lenient when we have too few arguments - + let isDecorator: boolean; + if (node.kind === SyntaxKind.TaggedTemplateExpression) { let tagExpression = node; @@ -6643,39 +6655,9 @@ module ts { } } else if (node.kind === SyntaxKind.Decorator) { - let decorator = node; - switch (decorator.parent.kind) { - case SyntaxKind.ClassDeclaration: - case SyntaxKind.ClassExpression: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - adjustedArgCount = 1; - typeArguments = undefined; - break; - - case SyntaxKind.PropertyDeclaration: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - adjustedArgCount = 2; - typeArguments = undefined; - break; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // A method or accessor declaration decorator will have two or three arguments (see - // `MethodDecorator` in core.d.ts) - adjustedArgCount = signature.parameters.length >= 3 ? 3 : 2; - typeArguments = undefined; - break; - - case SyntaxKind.Parameter: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - - adjustedArgCount = 3; - typeArguments = undefined; - break; - } + isDecorator = true; + typeArguments = undefined; + adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { let callExpression = node; @@ -6705,7 +6687,7 @@ module ts { // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. - let spreadArgIndex = getSpreadArgumentIndex(args); + let spreadArgIndex = !isDecorator ? getSpreadArgumentIndex(args) : -1; if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } @@ -6742,7 +6724,7 @@ module ts { return getSignatureInstantiation(signature, getInferredTypes(context)); } - function inferTypeArguments(signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): void { + function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): void { let typeParameters = signature.typeParameters; let inferenceMapper = createInferenceMapper(context); @@ -6770,33 +6752,12 @@ module ts { // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - for (let i = 0; i < args.length; i++) { - let arg = args[i]; - if (arg.kind !== SyntaxKind.OmittedExpression) { + let argCount = getEffectiveArgumentCount(node, args, signature); + for (let i = 0; i < argCount; i++) { + let arg = getEffectiveArgument(node, args, i); + if (!arg || arg.kind !== SyntaxKind.OmittedExpression) { let paramType = getTypeAtPosition(signature, i); - let argType: Type; - if (arg.parent.kind === SyntaxKind.Decorator) { - if (i === 0) { - argType = getDecoratorTargetArgumentType(arg.parent.parent); - } - else if (i === 1) { - argType = getDecoratorPropertyKeyArgumentType(arg.parent.parent); - } - else if (i === 2) { - argType = getDecoratorPropertyIndexOrDescriptorArgumentType(arg.parent.parent); - } - } - else if (i === 0 && arg.parent.kind === SyntaxKind.TaggedTemplateExpression) { - argType = globalTemplateStringsArrayType; - } - - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } - + let argType = getEffectiveArgumentType(node, i, arg, paramType, excludeArgument, inferenceMapper, /*reportErrors*/ false); inferTypes(context, argType, paramType); } } @@ -6804,8 +6765,10 @@ module ts { // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { - for (let i = 0; i < args.length; i++) { + for (let i = 0; i < argCount; i++) { // No need to check for omitted args and template expressions, their exlusion value is always undefined if (excludeArgument[i] === false) { let arg = args[i]; @@ -6818,7 +6781,7 @@ module ts { getInferredTypes(context); } - function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean, containingMessageChain?: DiagnosticMessageChain): boolean { + function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean, headMessage?: DiagnosticMessage): boolean { let typeParameters = signature.typeParameters; let typeArgumentsAreAssignable = true; for (let i = 0; i < typeParameters.length; i++) { @@ -6829,180 +6792,44 @@ module ts { if (typeArgumentsAreAssignable /* so far */) { let constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1, containingMessageChain); + let errorInfo: DiagnosticMessageChain; + let typeArgumentHeadMessage = Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + + typeArgumentsAreAssignable = checkTypeAssignableTo( + typeArgument, + constraint, + reportErrors ? typeArgNode : undefined, + typeArgumentHeadMessage, + errorInfo); } } } + return typeArgumentsAreAssignable; } - - function getTypeOfParentOfClassElement(node: ClassElement) { - let classSymbol = getSymbolOfNode(node.parent); - if (node.flags & NodeFlags.Static) { - return getTypeOfSymbol(classSymbol); - } - else { - return getDeclaredTypeOfSymbol(classSymbol); - } - } - - function createTypedPropertyDescriptorType(propertyType: Type): Type { - let globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); - return globalTypedPropertyDescriptorType !== emptyObjectType - ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) - : emptyObjectType; - } - - function getDecoratorTargetArgumentType(target: Node): Type { - // The first argument to a decorator is its `target`. - switch (target.kind) { - case SyntaxKind.ClassDeclaration: - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - let classSymbol = getSymbolOfNode(target); - return getTypeOfSymbol(classSymbol); - - case SyntaxKind.Parameter: - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - target = target.parent; - if (target.kind === SyntaxKind.Constructor) { - let classSymbol = getSymbolOfNode(target); - return getTypeOfSymbol(classSymbol); - } - - // fall-through - - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getTypeOfParentOfClassElement(target); - - default: - return undefined; - } - } - - function getDecoratorPropertyKeyArgumentType(target: Node) { - // The second argument to a decorator is its `propertyKey` - switch (target.kind) { - case SyntaxKind.ClassDeclaration: - Debug.fail("Class decorators should not have a second synthetic argument."); - - case SyntaxKind.Parameter: - target = target.parent; - if (target.kind === SyntaxKind.Constructor) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - - // fall-through - - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - let element = target; - switch (element.name.kind) { - case SyntaxKind.Identifier: - case SyntaxKind.NumericLiteral: - case SyntaxKind.StringLiteral: - return getStringLiteralType(element.name); - - case SyntaxKind.ComputedPropertyName: - let nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { - return nameType; - } - else { - return stringType; - } - } - } - } - - function getDecoratorPropertyIndexOrDescriptorArgumentType(parent: Node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a paramter decorator - switch (parent.kind) { - case SyntaxKind.ClassDeclaration: - Debug.fail("Class decorators should not have a third synthetic argument."); - break; - case SyntaxKind.Parameter: - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - - case SyntaxKind.PropertyDeclaration: - Debug.fail("Property decorators should not have a third synthetic argument."); - break; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - let propertyType: Type = getTypeOfNode(parent); - return createTypedPropertyDescriptorType(propertyType); - } - } - - function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean, containingMessageChain?: DiagnosticMessageChain) { - for (let i = 0; i < args.length; i++) { - let arg = args[i]; - if (arg.kind !== SyntaxKind.OmittedExpression) { + function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { + let argCount = getEffectiveArgumentCount(node, args, signature); + for (let i = 0; i < argCount; i++) { + let arg = getEffectiveArgument(node, args, i); + if (!arg || arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) let paramType = getTypeAtPosition(signature, i); - - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - let argType: Type; - if (arg.parent.kind === SyntaxKind.Decorator) { - if (i === 0) { - argType = getDecoratorTargetArgumentType(arg.parent.parent); - } - else if (i === 1) { - argType = getDecoratorPropertyKeyArgumentType(arg.parent.parent); - } - else if (i === 2) { - argType = getDecoratorPropertyIndexOrDescriptorArgumentType(arg.parent.parent); - } - } - else if (i === 0 && arg.parent.kind === SyntaxKind.TaggedTemplateExpression) { - argType = globalTemplateStringsArrayType; - } - - if (argType === undefined) { - if (arg.kind === SyntaxKind.StringLiteral && !reportErrors) { - argType = getStringLiteralType(arg); - } - else { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - } + let argType = getEffectiveArgumentType(node, i, arg, paramType, excludeArgument, /*inferenceMapper*/ undefined, reportErrors); // Use argument expression as error location when reporting errors - let errorNode = reportErrors ? arg : undefined; + let errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; let headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage, containingMessageChain)) { + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } } } + return true; } @@ -7011,17 +6838,15 @@ module ts { * * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is the template for error reporting purposes. - * If 'node' is a Decorator, a new argument list is constructed with the decorator - * expression as a placeholder to help when choosing an applicable signature and - * for error reporting purposes. + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node: CallLikeExpression): Expression[] { let args: Expression[]; if (node.kind === SyntaxKind.TaggedTemplateExpression) { let template = (node).template; - args = [template]; - + args = [undefined]; if (template.kind === SyntaxKind.TemplateExpression) { forEach((template).templateSpans, span => { args.push(span.expression); @@ -7029,21 +6854,10 @@ module ts { } } else if (node.kind === SyntaxKind.Decorator) { - let decorator = node; - switch (decorator.parent.kind) { - case SyntaxKind.ClassDeclaration: - args = [decorator.expression]; - break; - case SyntaxKind.PropertyDeclaration: - args = [decorator.expression, decorator.expression]; - break; - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.Parameter: - args = [decorator.expression, decorator.expression, decorator.expression]; - break; - } + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. + return undefined; } else { args = (node).arguments || emptyArray; @@ -7074,7 +6888,287 @@ module ts { } } - function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], containingMessageChain?: DiagnosticMessageChain): Signature { + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ + function getEffectiveArgumentCount(node: CallLikeExpression, args: Expression[], signature: Signature) { + if (node.kind === SyntaxKind.Decorator) { + switch (node.parent.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + return 1; + + case SyntaxKind.PropertyDeclaration: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + return 2; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. + return signature.parameters.length >= 3 ? 3 : 2; + + case SyntaxKind.Parameter: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + + return 3; + } + } + else { + return args.length; + } + } + + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ + function getEffectiveDecoratorFirstArgumentType(node: Node): Type { + // The first argument to a decorator is its `target`. + switch (node.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + let classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + + case SyntaxKind.Parameter: + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + node = node.parent; + if (node.kind === SyntaxKind.Constructor) { + let classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + + // fall-through + + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getParentTypeOfClassElement(node); + + default: + Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ + function getEffectiveDecoratorSecondArgumentType(node: Node) { + // The second argument to a decorator is its `propertyKey` + switch (node.kind) { + case SyntaxKind.ClassDeclaration: + Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + + case SyntaxKind.Parameter: + node = node.parent; + if (node.kind === SyntaxKind.Constructor) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + + // fall-through + + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + let element = node; + switch (element.name.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.NumericLiteral: + case SyntaxKind.StringLiteral: + return getStringLiteralType(element.name); + + case SyntaxKind.ComputedPropertyName: + let nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { + return nameType; + } + else { + return stringType; + } + + default: + Debug.fail("Unsupported property name."); + return unknownType; + } + + + default: + Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ + function getEffectiveDecoratorThirdArgumentType(node: Node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a paramter decorator + switch (node.kind) { + case SyntaxKind.ClassDeclaration: + Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + + case SyntaxKind.Parameter: + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + + case SyntaxKind.PropertyDeclaration: + Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + let propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + + default: + Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + + /** + * Returns the effective argument type for the provided argument to a decorator. + */ + function getEffectiveDecoratorArgumentType(node: Decorator, argIndex: number): Type { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + + Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + + /** + * Gets the effective argument type for an argument in a call expression. + */ + function getEffectiveArgumentType(node: CallLikeExpression, argIndex: number, arg: Expression, paramType: Type, excludeArgument: boolean[], inferenceMapper: TypeMapper, reportErrors: boolean): Type { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === SyntaxKind.Decorator) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === SyntaxKind.TaggedTemplateExpression) { + return globalTemplateStringsArrayType; + } + else if (!inferenceMapper && !reportErrors && arg.kind === SyntaxKind.StringLiteral) { + return getStringLiteralType(arg); + } + else { + let mapper: TypeMapper; + if (inferenceMapper) { + mapper = excludeArgument && excludeArgument[argIndex] !== undefined ? identityMapper : inferenceMapper; + } + else { + mapper = excludeArgument && excludeArgument[argIndex] ? identityMapper : undefined; + } + + return checkExpressionWithContextualType(arg, paramType, mapper); + } + } + + /** + * Gets the effective argument expression for an argument in a call expression. + */ + function getEffectiveArgument(node: CallLikeExpression, args: Expression[], argIndex: number) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === SyntaxKind.Decorator || + (argIndex === 0 && node.kind === SyntaxKind.TaggedTemplateExpression)) { + return undefined; + } + + return args[argIndex]; + } + + /** + * Gets the error node to use when reporting errors for an effective argument. + */ + function getEffectiveArgumentErrorNode(node: CallLikeExpression, argIndex: number, arg: Expression) { + if (node.kind === SyntaxKind.Decorator) { + // For a decorator, we use the expression of the decorator for error reporting. + return (node).expression; + } + else if (argIndex === 0 && node.kind === SyntaxKind.TaggedTemplateExpression) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. + return (node).template; + } + else { + return arg; + } + } + + function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], headMessage?: DiagnosticMessage): Signature { let isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; let isDecorator = node.kind === SyntaxKind.Decorator; @@ -7115,6 +7209,8 @@ module ts { // decorators are applied to a declaration by the emitter, and not to an expression. let excludeArgument: boolean[]; if (!isDecorator) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. for (let i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { @@ -7185,11 +7281,11 @@ module ts { // in arguments too early. If possible, we'd like to only type them once we know the correct // overload. However, this matters for the case where the call is correct. When the call is // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true, containingMessageChain); + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && (node).typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, containingMessageChain) + checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, headMessage) } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -7200,8 +7296,8 @@ module ts { Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (containingMessageChain) { - diagnosticChainHead = concatenateDiagnosticMessageChains(containingMessageChain, diagnosticChainHead); + if (headMessage) { + diagnosticChainHead = chainDiagnosticMessages(diagnosticChainHead, headMessage); } reportNoCommonSupertypeError(inferenceCandidates, (node).expression || (node).tag, diagnosticChainHead); @@ -7227,9 +7323,10 @@ module ts { return resolveErrorCall(node); function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { - let errorInfo = chainDiagnosticMessages(/*details*/ undefined, message, arg0, arg1, arg2); - if (containingMessageChain) { - errorInfo = concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + let errorInfo: DiagnosticMessageChain; + errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + if (headMessage) { + errorInfo = chainDiagnosticMessages(errorInfo, headMessage); } diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); @@ -7256,7 +7353,7 @@ module ts { typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false) } else { - inferTypeArguments(candidate, args, excludeArgument, inferenceContext); + inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; typeArgumentTypes = inferenceContext.inferredTypes; } @@ -7433,7 +7530,32 @@ module ts { return resolveCall(node, callSignatures, candidatesOutArray); } + + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node: Decorator) { + switch (node.parent.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + return Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + + case SyntaxKind.Parameter: + return Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + + case SyntaxKind.PropertyDeclaration: + return Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + /** + * Resolves a decorator as if it were a call expression. + */ function resolveDecorator(node: Decorator, candidatesOutArray: Signature[]): Signature { let funcType = checkExpression(node.expression); let apparentType = getApparentType(funcType); @@ -7446,43 +7568,16 @@ module ts { return resolveUntypedCall(node); } - let decoratorKind: string; - switch (node.parent.kind) { - case SyntaxKind.ClassDeclaration: - case SyntaxKind.ClassExpression: - decoratorKind = "class"; - break; - - case SyntaxKind.Parameter: - decoratorKind = "parameter"; - break; - - case SyntaxKind.PropertyDeclaration: - decoratorKind = "property"; - break; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - decoratorKind = "method"; - break; - - default: - Debug.fail("Invalid decorator target."); - break; - } - - let diagnosticChainHead = chainDiagnosticMessages( - /*details*/ undefined, - Diagnostics.Unable_to_resolve_signature_of_0_decorator_when_called_as_an_expression, decoratorKind); + let headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - let errorInfo = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); - errorInfo = concatenateDiagnosticMessageChains(diagnosticChainHead, errorInfo); + let errorInfo: DiagnosticMessageChain; + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(createDiagnosticForNodeFromMessageChain(node, errorInfo)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, diagnosticChainHead); + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); } // candidatesOutArray is passed by signature help in the language service, and collectCandidates @@ -9134,24 +9229,28 @@ module ts { } let expectedReturnType: Type; - let diagnosticChainHead: DiagnosticMessageChain; - let decoratorKind: string; + let headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + let errorInfo: DiagnosticMessageChain; switch (node.parent.kind) { case SyntaxKind.ClassDeclaration: let classSymbol = getSymbolOfNode(node.parent); let classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); - decoratorKind = "class"; break; case SyntaxKind.Parameter: expectedReturnType = voidType; - decoratorKind = "parameter"; - break; + errorInfo = chainDiagnosticMessages( + errorInfo, + Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case SyntaxKind.PropertyDeclaration: expectedReturnType = voidType; - decoratorKind = "property"; + errorInfo = chainDiagnosticMessages( + errorInfo, + Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case SyntaxKind.MethodDeclaration: @@ -9160,23 +9259,15 @@ module ts { let methodType = getTypeOfNode(node.parent); let descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); - decoratorKind = "method"; break; } - if (expectedReturnType === voidType) { - diagnosticChainHead = chainDiagnosticMessages( - diagnosticChainHead, - Diagnostics.The_return_type_of_a_0_decorator_function_must_be_either_void_or_any, - decoratorKind); - } - - diagnosticChainHead = chainDiagnosticMessages( - diagnosticChainHead, - Diagnostics.Unable_to_resolve_signature_of_0_decorator_when_called_as_an_expression, - decoratorKind); - - checkTypeAssignableTo(returnType, expectedReturnType, node, /*headMessage*/ undefined, diagnosticChainHead); + checkTypeAssignableTo( + returnType, + expectedReturnType, + node, + headMessage, + errorInfo); } /** Checks a type reference node as an expression. */ @@ -11815,6 +11906,17 @@ module ts { return checkExpression(expr); } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node: ClassElement) { + let classSymbol = getSymbolOfNode(node.parent); + return node.flags & NodeFlags.Static + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type: Type): Symbol[] { diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index a1b776611f7..1653b673503 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -174,8 +174,12 @@ module ts { Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: DiagnosticCategory.Error, key: "Export assignment is not supported when '--module' flag is 'system'." }, - The_return_type_of_a_0_decorator_function_must_be_either_void_or_any: { code: 1219, category: DiagnosticCategory.Error, key: "The return type of a {0} decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_0_decorator_when_called_as_an_expression: { code: 1220, category: DiagnosticCategory.Error, key: "Unable to resolve signature of {0} decorator when called as an expression." }, + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1219, category: DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." }, + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1220, category: DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." }, + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1221, category: DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." }, + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1222, category: DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." }, + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1223, category: DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." }, + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1224, category: DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 27238db5d95..006e1d6f1a9 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -683,14 +683,31 @@ "category": "Error", "code": 1218 }, - "The return type of a {0} decorator function must be either 'void' or 'any'.": { + "The return type of a property decorator function must be either 'void' or 'any'.": { "category": "Error", "code": 1219 }, - "Unable to resolve signature of {0} decorator when called as an expression.": { + "The return type of a parameter decorator function must be either 'void' or 'any'.": { "category": "Error", "code": 1220 }, + + "Unable to resolve signature of class decorator when called as an expression.": { + "category": "Error", + "code": 1221 + }, + "Unable to resolve signature of parameter decorator when called as an expression.": { + "category": "Error", + "code": 1222 + }, + "Unable to resolve signature of property decorator when called as an expression.": { + "category": "Error", + "code": 1223 + }, + "Unable to resolve signature of method decorator when called as an expression.": { + "category": "Error", + "code": 1224 + }, "Duplicate identifier '{0}'.": { "category": "Error", diff --git a/tests/baselines/reference/decoratorOnClass8.errors.txt b/tests/baselines/reference/decoratorOnClass8.errors.txt index b5e27b4b3cb..adda3c19095 100644 --- a/tests/baselines/reference/decoratorOnClass8.errors.txt +++ b/tests/baselines/reference/decoratorOnClass8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1220: Unable to resolve signature of class decorator when called as an expression. +tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1221: Unable to resolve signature of class decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -7,7 +7,7 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1220 @dec() ~~~~~~ -!!! error TS1220: Unable to resolve signature of class decorator when called as an expression. -!!! error TS1220: Supplied parameters do not match any signature of call target. +!!! error TS1221: Unable to resolve signature of class decorator when called as an expression. +!!! error TS1221: Supplied parameters do not match any signature of call target. class C { } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod10.errors.txt b/tests/baselines/reference/decoratorOnClassMethod10.errors.txt index 1d94f08f2a2..6499aa44e53 100644 --- a/tests/baselines/reference/decoratorOnClassMethod10.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod10.errors.txt @@ -1,6 +1,5 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6): error TS1220: Unable to resolve signature of method decorator when called as an expression. - Argument of type 'C' is not assignable to parameter of type 'Function'. - Property 'apply' is missing in type 'C'. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6): error TS2345: Argument of type 'C' is not assignable to parameter of type 'Function'. + Property 'apply' is missing in type 'C'. ==== tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts (1 errors) ==== @@ -9,7 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod10.ts(4,6) class C { @dec method() {} ~~~ -!!! error TS1220: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1220: Argument of type 'C' is not assignable to parameter of type 'Function'. -!!! error TS1220: Property 'apply' is missing in type 'C'. +!!! error TS2345: Argument of type 'C' is not assignable to parameter of type 'Function'. +!!! error TS2345: Property 'apply' is missing in type 'C'. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt index 2231d0da56d..206480dd135 100644 --- a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1220: Unable to resolve signature of method decorator when called as an expression. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1224: Unable to resolve signature of method decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): class C { @dec ["method"]() {} ~~~~ -!!! error TS1220: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1220: Supplied parameters do not match any signature of call target. +!!! error TS1224: Unable to resolve signature of method decorator when called as an expression. +!!! error TS1224: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt index d80fe7e05f7..832b8efbb34 100644 --- a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1220: Unable to resolve signature of method decorator when called as an expression. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1224: Unable to resolve signature of method decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): class C { @dec method() {} ~~~~ -!!! error TS1220: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1220: Supplied parameters do not match any signature of call target. +!!! error TS1224: Unable to resolve signature of method decorator when called as an expression. +!!! error TS1224: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt index 8dad5dc955f..9b153135639 100644 --- a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1220: Unable to resolve signature of property decorator when called as an expression. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1223: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts( class C { @dec prop; ~~~~ -!!! error TS1220: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1220: Supplied parameters do not match any signature of call target. +!!! error TS1223: Unable to resolve signature of property decorator when called as an expression. +!!! error TS1223: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt index eca97e803e0..8fa543a2734 100644 --- a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1220: Unable to resolve signature of property decorator when called as an expression. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1223: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4 class C { @dec prop; ~~~~ -!!! error TS1220: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1220: Supplied parameters do not match any signature of call target. +!!! error TS1223: Unable to resolve signature of property decorator when called as an expression. +!!! error TS1223: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt index 7f2249e5934..a467cfe5a27 100644 --- a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1220: Unable to resolve signature of property decorator when called as an expression. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1223: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4 class C { @dec prop; ~~~~ -!!! error TS1220: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1220: Supplied parameters do not match any signature of call target. +!!! error TS1223: Unable to resolve signature of property decorator when called as an expression. +!!! error TS1223: Supplied parameters do not match any signature of call target. } \ No newline at end of file From 87d0af10d00d49d8722e8264dbc0536a7812fb92 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 29 May 2015 11:00:19 -0700 Subject: [PATCH 09/79] Moved call for getSpreadArgumentIndex in hasCorrectArity --- src/compiler/checker.ts | 3 ++- src/compiler/diagnosticMessages.json | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 57e1f8190f0..04ff7a1eaa5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6628,6 +6628,7 @@ module ts { let typeArguments: NodeArray; // Type arguments (undefined if none) let callIsIncomplete: boolean; // In incomplete call we want to be lenient when we have too few arguments let isDecorator: boolean; + let spreadArgIndex = -1; if (node.kind === SyntaxKind.TaggedTemplateExpression) { let tagExpression = node; @@ -6675,6 +6676,7 @@ module ts { callIsIncomplete = (callExpression).arguments.end === callExpression.end; typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); } // If the user supplied type arguments, but the number of type arguments does not match @@ -6687,7 +6689,6 @@ module ts { // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. - let spreadArgIndex = !isDecorator ? getSpreadArgumentIndex(args) : -1; if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 006e1d6f1a9..264f2fdb55b 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -691,7 +691,6 @@ "category": "Error", "code": 1220 }, - "Unable to resolve signature of class decorator when called as an expression.": { "category": "Error", "code": 1221 From 910079a60e88686b34acc4df0f2db4c79af9ac2e Mon Sep 17 00:00:00 2001 From: SaschaNaz Date: Tue, 2 Jun 2015 15:28:29 +0900 Subject: [PATCH 10/79] exclude closeparen/propertyaccess tokens --- src/services/formatting/smartIndenter.ts | 7 ++++++- ...nsistenceOnIndentionsOfChainedFunctionCalls.ts | 2 +- .../fourslash/formattingOnChainedCallbacks.ts | 15 ++++++++++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 4bd7fd66411..f904cfe744d 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -296,7 +296,12 @@ module ts.formatting { } function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorOptions): number { - if (node.parent && ( + // actual indentation should not be used when: + // - node is close parenthesis - this is the end of the expression + // - node is property access expression + if (node.kind !== SyntaxKind.CloseParenToken && + node.kind !== SyntaxKind.PropertyAccessExpression && + node.parent && ( node.parent.kind === SyntaxKind.CallExpression || node.parent.kind === SyntaxKind.NewExpression)) { diff --git a/tests/cases/fourslash/consistenceOnIndentionsOfChainedFunctionCalls.ts b/tests/cases/fourslash/consistenceOnIndentionsOfChainedFunctionCalls.ts index ec2ae9b3c22..3692974f5fb 100644 --- a/tests/cases/fourslash/consistenceOnIndentionsOfChainedFunctionCalls.ts +++ b/tests/cases/fourslash/consistenceOnIndentionsOfChainedFunctionCalls.ts @@ -18,4 +18,4 @@ goTo.marker("1"); edit.insert("\r\n"); goTo.marker("0"); // Won't-fixed: Smart indent during chained function calls -verify.indentationIs(4); \ No newline at end of file +verify.indentationIs(8); \ No newline at end of file diff --git a/tests/cases/fourslash/formattingOnChainedCallbacks.ts b/tests/cases/fourslash/formattingOnChainedCallbacks.ts index 98f91de56fb..b8dbc55d8b6 100644 --- a/tests/cases/fourslash/formattingOnChainedCallbacks.ts +++ b/tests/cases/fourslash/formattingOnChainedCallbacks.ts @@ -13,6 +13,14 @@ //// })/*b*/ ////} +////Promise +//// .then( +//// /*n1*/ +//// ) +//// /*n2*/ +//// .then(); + + goTo.marker('1'); edit.insertLine(''); goTo.marker('2'); @@ -36,4 +44,9 @@ edit.insert(';'); verify.currentLineContentIs(' "";'); goTo.marker('b'); edit.insert(';'); -verify.currentLineContentIs(' });'); \ No newline at end of file +verify.currentLineContentIs(' });'); + +goTo.marker('n1'); +verify.indentationIs(8); +goTo.marker('n2'); +verify.indentationIs(4); \ No newline at end of file From 0fe60498d789bb9f4ea1ead3becde8c3861b088e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 17 Jun 2015 17:11:42 -0700 Subject: [PATCH 11/79] Adding SyntaxKind.ClassExpression in a bunch of places --- src/compiler/binder.ts | 6 +-- src/compiler/checker.ts | 89 +++++++++++++-------------------------- src/compiler/utilities.ts | 33 +++++++-------- 3 files changed, 49 insertions(+), 79 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index eaad8593eee..e403ed994e5 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -630,7 +630,7 @@ namespace ts { function getStrictModeIdentifierMessage(node: Node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. - if (getAncestor(node, SyntaxKind.ClassDeclaration) || getAncestor(node, SyntaxKind.ClassExpression)) { + if (getContainingClass(node)) { return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; } @@ -688,7 +688,7 @@ namespace ts { function getStrictModeEvalOrArgumentsMessage(node: Node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. - if (getAncestor(node, SyntaxKind.ClassDeclaration) || getAncestor(node, SyntaxKind.ClassExpression)) { + if (getContainingClass(node)) { return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } @@ -1031,7 +1031,7 @@ namespace ts { // containing class. if (node.flags & NodeFlags.AccessibilityModifier && node.parent.kind === SyntaxKind.Constructor && - (node.parent.parent.kind === SyntaxKind.ClassDeclaration || node.parent.parent.kind === SyntaxKind.ClassExpression)) { + isClassLike(node.parent.parent)) { let classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index efc3e32166e..232a3db419a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -386,8 +386,8 @@ namespace ts { // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (location.parent.kind === SyntaxKind.ClassDeclaration && !(location.flags & NodeFlags.Static)) { - let ctor = findConstructorDeclaration(location.parent); + if (isClassLike(location.parent) && !(location.flags & NodeFlags.Static)) { + let ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error @@ -397,6 +397,7 @@ namespace ts { } break; case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & SymbolFlags.Type)) { if (lastLocation && lastLocation.flags & NodeFlags.Static) { @@ -420,7 +421,7 @@ namespace ts { // case SyntaxKind.ComputedPropertyName: grandparent = location.parent.parent; - if (grandparent.kind === SyntaxKind.ClassDeclaration || grandparent.kind === SyntaxKind.InterfaceDeclaration) { + if (isClassLike(grandparent) || grandparent.kind === SyntaxKind.InterfaceDeclaration) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & SymbolFlags.Type)) { error(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -1009,7 +1010,7 @@ namespace ts { return false; } - function findConstructorDeclaration(node: ClassDeclaration): ConstructorDeclaration { + function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration { let members = node.members; for (let member of members) { if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { @@ -2562,10 +2563,10 @@ namespace ts { if (!node) { return typeParameters; } - if (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.FunctionDeclaration || - node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.MethodDeclaration || - node.kind === SyntaxKind.ArrowFunction) { - let declarations = (node).typeParameters; + if (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || + node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression || + node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.ArrowFunction) { + let declarations = (node).typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); } @@ -2575,8 +2576,8 @@ namespace ts { // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] { - var kind = symbol.flags & SymbolFlags.Class ? SyntaxKind.ClassDeclaration : SyntaxKind.InterfaceDeclaration; - return appendOuterTypeParameters(undefined, getDeclarationOfKind(symbol, kind)); + var declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -2584,7 +2585,8 @@ namespace ts { function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): TypeParameter[] { let result: TypeParameter[]; for (let node of symbol.declarations) { - if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) { + if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || + node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.TypeAliasDeclaration) { let declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -5884,9 +5886,9 @@ namespace ts { } function captureLexicalThis(node: Node, container: Node): void { - let classNode = container.parent && container.parent.kind === SyntaxKind.ClassDeclaration ? container.parent : undefined; getNodeLinks(node).flags |= NodeCheckFlags.LexicalThis; if (container.kind === SyntaxKind.PropertyDeclaration || container.kind === SyntaxKind.Constructor) { + let classNode = container.parent; getNodeLinks(classNode).flags |= NodeCheckFlags.CaptureThis; } else { @@ -5939,7 +5941,7 @@ namespace ts { captureLexicalThis(node, container); } - let classNode = container.parent && container.parent.kind === SyntaxKind.ClassDeclaration ? container.parent : undefined; + let classNode = isClassLike(container.parent) ? container.parent : undefined; if (classNode) { let symbol = getSymbolOfNode(classNode); return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); @@ -5958,7 +5960,7 @@ namespace ts { function checkSuperExpression(node: Node): Type { let isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; - let classDeclaration = getAncestor(node, SyntaxKind.ClassDeclaration); + let classDeclaration = getContainingClass(node); let classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); let baseClassType = classType && getBaseTypes(classType)[0]; @@ -5993,7 +5995,7 @@ namespace ts { } // topmost container must be something that is directly nested in the class declaration - if (container && container.parent && container.parent.kind === SyntaxKind.ClassDeclaration) { + if (container && isClassLike(container.parent)) { if (container.flags & NodeFlags.Static) { canUseSuperExpression = container.kind === SyntaxKind.MethodDeclaration || @@ -6652,7 +6654,7 @@ namespace ts { } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - let enclosingClassDeclaration = getAncestor(node, SyntaxKind.ClassDeclaration); + let enclosingClassDeclaration = getContainingClass(node); let enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; let declaringClass = getDeclaredTypeOfSymbol(prop.parent); // Private property is accessible if declaring and enclosing class are the same @@ -7426,7 +7428,7 @@ namespace ts { if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - let baseTypeNode = getClassExtendsHeritageClauseElement(getAncestor(node, SyntaxKind.ClassDeclaration)); + let baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node)); let baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } @@ -8354,7 +8356,7 @@ namespace ts { if (isFunctionLike(parent) && current === (parent).body) { return false; } - else if (current.kind === SyntaxKind.ClassDeclaration || current.kind === SyntaxKind.ClassExpression) { + else if (isClassLike(current)) { return true; } @@ -9648,7 +9650,7 @@ namespace ts { } // bubble up and find containing type - let enclosingClass = getAncestor(node, SyntaxKind.ClassDeclaration); + let enclosingClass = getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || isInAmbientContext(enclosingClass)) { return; @@ -10456,8 +10458,8 @@ namespace ts { checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); }); - if (type.flags & TypeFlags.Class && type.symbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration) { - let classDeclaration = type.symbol.valueDeclaration; + if (type.flags & TypeFlags.Class && isClassLike(type.symbol.valueDeclaration)) { + let classDeclaration = type.symbol.valueDeclaration; for (let member of classDeclaration.members) { // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, @@ -11727,6 +11729,11 @@ namespace ts { case SyntaxKind.EnumDeclaration: copySymbols(getSymbolOfNode(location).exports, meaning & SymbolFlags.EnumMember); break; + case SyntaxKind.ClassExpression: + if ((location).name) { + copySymbol(location.symbol, meaning); + } + // Fall through case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: if (!(memberFlags & NodeFlags.Static)) { @@ -11766,42 +11773,6 @@ namespace ts { } } } - - if (isInsideWithStatementBody(location)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return []; - } - - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case SyntaxKind.SourceFile: - if (!isExternalModule(location)) break; - case SyntaxKind.ModuleDeclaration: - copySymbols(getSymbolOfNode(location).exports, meaning & SymbolFlags.ModuleMember); - break; - case SyntaxKind.EnumDeclaration: - copySymbols(getSymbolOfNode(location).exports, meaning & SymbolFlags.EnumMember); - break; - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: - if (!(memberFlags & NodeFlags.Static)) { - copySymbols(getSymbolOfNode(location).members, meaning & SymbolFlags.Type); - } - break; - case SyntaxKind.FunctionExpression: - if ((location).name) { - copySymbol(location.symbol, meaning); - } - break; - } - memberFlags = location.flags; - location = location.parent; - } - copySymbols(globals, meaning); - return symbolsToArray(symbols); } function isTypeDeclarationName(name: Node): boolean { @@ -13213,7 +13184,7 @@ namespace ts { } } - if (node.parent.kind === SyntaxKind.ClassDeclaration) { + if (isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -13505,7 +13476,7 @@ namespace ts { } function checkGrammarProperty(node: PropertyDeclaration) { - if (node.parent.kind === SyntaxKind.ClassDeclaration) { + if (isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional) || checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { return true; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index e0fc5fc0269..7f9888c73d3 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -542,6 +542,7 @@ namespace ts { case SyntaxKind.ModuleDeclaration: case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -579,26 +580,15 @@ namespace ts { return true; } } - return false; } export function isAccessor(node: Node): boolean { - if (node) { - switch (node.kind) { - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - return true; - } - } - - return false; + return node && (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor); } export function isClassLike(node: Node): boolean { - if (node) { - return node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression; - } + return node && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression); } export function isFunctionLike(node: Node): boolean { @@ -620,7 +610,6 @@ namespace ts { return true; } } - return false; } @@ -641,6 +630,15 @@ namespace ts { } } + export function getContainingClass(node: Node): ClassLikeDeclaration { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; + } + } + } + export function getThisContainer(node: Node, includeArrowFunctions: boolean): Node { while (true) { node = node.parent; @@ -653,7 +651,7 @@ namespace ts { // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. - if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { + if (isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -708,7 +706,7 @@ namespace ts { // then the computed property is not a 'super' container. // A computed property name in a class needs to be a super container // so that we can error on it. - if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { + if (isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -1087,6 +1085,7 @@ namespace ts { case SyntaxKind.ArrowFunction: case SyntaxKind.BindingElement: case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: case SyntaxKind.Constructor: case SyntaxKind.EnumDeclaration: case SyntaxKind.EnumMember: @@ -1917,7 +1916,7 @@ namespace ts { export function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean { return node.kind === SyntaxKind.ExpressionWithTypeArguments && (node.parent).token === SyntaxKind.ExtendsKeyword && - node.parent.parent.kind === SyntaxKind.ClassDeclaration; + isClassLike(node.parent.parent); } // Returns false if this heritage clause element's expression contains something unsupported From 76ec1f0fec17be2937367e6a41af7d78958b0f45 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 17 Jun 2015 21:28:49 -0700 Subject: [PATCH 12/79] Add a non-generic construct signature to Map, Set, and WeakMap --- src/lib/es6.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/lib/es6.d.ts b/src/lib/es6.d.ts index 625a4eca9e1..71df6d77436 100644 --- a/src/lib/es6.d.ts +++ b/src/lib/es6.d.ts @@ -694,6 +694,7 @@ interface Map { } interface MapConstructor { + new (): Map; new (): Map; new (iterable: Iterable<[K, V]>): Map; prototype: Map; @@ -710,6 +711,7 @@ interface WeakMap { } interface WeakMapConstructor { + new (): WeakMap; new (): WeakMap; new (iterable: Iterable<[K, V]>): WeakMap; prototype: WeakMap; @@ -731,6 +733,7 @@ interface Set { } interface SetConstructor { + new (): Set; new (): Set; new (iterable: Iterable): Set; prototype: Set; @@ -746,6 +749,7 @@ interface WeakSet { } interface WeakSetConstructor { + new (): WeakSet; new (): WeakSet; new (iterable: Iterable): WeakSet; prototype: WeakSet; From 7c50c7c45e0d06d1f19bcae97c963365c3e1c608 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 17 Jun 2015 23:22:23 -0700 Subject: [PATCH 13/79] Accept baselines --- tests/baselines/reference/for-of37.symbols | 2 +- tests/baselines/reference/for-of38.symbols | 2 +- tests/baselines/reference/for-of40.symbols | 2 +- tests/baselines/reference/for-of45.symbols | 2 +- tests/baselines/reference/for-of50.symbols | 2 +- .../reference/iterableArrayPattern30.symbols | 2 +- .../promiseVoidErrorCallback.symbols | 16 +- tests/baselines/reference/typedArrays.symbols | 324 +++++++++--------- 8 files changed, 176 insertions(+), 176 deletions(-) diff --git a/tests/baselines/reference/for-of37.symbols b/tests/baselines/reference/for-of37.symbols index 739d9be0af0..11de20174a7 100644 --- a/tests/baselines/reference/for-of37.symbols +++ b/tests/baselines/reference/for-of37.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of37.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of37.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1887, 11)) for (var v of map) { >v : Symbol(v, Decl(for-of37.ts, 1, 8)) diff --git a/tests/baselines/reference/for-of38.symbols b/tests/baselines/reference/for-of38.symbols index 9322fea69e6..20af2cb65fb 100644 --- a/tests/baselines/reference/for-of38.symbols +++ b/tests/baselines/reference/for-of38.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of38.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of38.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1887, 11)) for (var [k, v] of map) { >k : Symbol(k, Decl(for-of38.ts, 1, 10)) diff --git a/tests/baselines/reference/for-of40.symbols b/tests/baselines/reference/for-of40.symbols index 72bbf78884e..eb77e578510 100644 --- a/tests/baselines/reference/for-of40.symbols +++ b/tests/baselines/reference/for-of40.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of40.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of40.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1887, 11)) for (var [k = "", v = false] of map) { >k : Symbol(k, Decl(for-of40.ts, 1, 10)) diff --git a/tests/baselines/reference/for-of45.symbols b/tests/baselines/reference/for-of45.symbols index e1e7717269f..b9e5bbacbfa 100644 --- a/tests/baselines/reference/for-of45.symbols +++ b/tests/baselines/reference/for-of45.symbols @@ -5,7 +5,7 @@ var k: string, v: boolean; var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of45.ts, 1, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1887, 11)) for ([k = "", v = false] of map) { >k : Symbol(k, Decl(for-of45.ts, 0, 3)) diff --git a/tests/baselines/reference/for-of50.symbols b/tests/baselines/reference/for-of50.symbols index 571dd9dc389..f3bd38be1df 100644 --- a/tests/baselines/reference/for-of50.symbols +++ b/tests/baselines/reference/for-of50.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of50.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of50.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1887, 11)) for (const [k, v] of map) { >k : Symbol(k, Decl(for-of50.ts, 1, 12)) diff --git a/tests/baselines/reference/iterableArrayPattern30.symbols b/tests/baselines/reference/iterableArrayPattern30.symbols index 715dd79c97a..38dacc59cc2 100644 --- a/tests/baselines/reference/iterableArrayPattern30.symbols +++ b/tests/baselines/reference/iterableArrayPattern30.symbols @@ -4,5 +4,5 @@ const [[k1, v1], [k2, v2]] = new Map([["", true], ["hello", true]]) >v1 : Symbol(v1, Decl(iterableArrayPattern30.ts, 0, 11)) >k2 : Symbol(k2, Decl(iterableArrayPattern30.ts, 0, 18)) >v2 : Symbol(v2, Decl(iterableArrayPattern30.ts, 0, 21)) ->Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1887, 11)) diff --git a/tests/baselines/reference/promiseVoidErrorCallback.symbols b/tests/baselines/reference/promiseVoidErrorCallback.symbols index 9a6e2ef47ba..d9e329885aa 100644 --- a/tests/baselines/reference/promiseVoidErrorCallback.symbols +++ b/tests/baselines/reference/promiseVoidErrorCallback.symbols @@ -22,13 +22,13 @@ interface T3 { function f1(): Promise { >f1 : Symbol(f1, Decl(promiseVoidErrorCallback.ts, 10, 1)) ->Promise : Symbol(Promise, Decl(lib.d.ts, 4766, 1), Decl(lib.d.ts, 4851, 11)) +>Promise : Symbol(Promise, Decl(lib.d.ts, 4770, 1), Decl(lib.d.ts, 4855, 11)) >T1 : Symbol(T1, Decl(promiseVoidErrorCallback.ts, 0, 0)) return Promise.resolve({ __t1: "foo_t1" }); ->Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.d.ts, 4833, 39), Decl(lib.d.ts, 4840, 54)) ->Promise : Symbol(Promise, Decl(lib.d.ts, 4766, 1), Decl(lib.d.ts, 4851, 11)) ->resolve : Symbol(PromiseConstructor.resolve, Decl(lib.d.ts, 4833, 39), Decl(lib.d.ts, 4840, 54)) +>Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.d.ts, 4837, 39), Decl(lib.d.ts, 4844, 54)) +>Promise : Symbol(Promise, Decl(lib.d.ts, 4770, 1), Decl(lib.d.ts, 4855, 11)) +>resolve : Symbol(PromiseConstructor.resolve, Decl(lib.d.ts, 4837, 39), Decl(lib.d.ts, 4844, 54)) >__t1 : Symbol(__t1, Decl(promiseVoidErrorCallback.ts, 13, 28)) } @@ -47,12 +47,12 @@ function f2(x: T1): T2 { var x3 = f1() >x3 : Symbol(x3, Decl(promiseVoidErrorCallback.ts, 20, 3)) ->f1() .then(f2, (e: Error) => { throw e;}) .then : Symbol(Promise.then, Decl(lib.d.ts, 4771, 22), Decl(lib.d.ts, 4778, 158)) ->f1() .then : Symbol(Promise.then, Decl(lib.d.ts, 4771, 22), Decl(lib.d.ts, 4778, 158)) +>f1() .then(f2, (e: Error) => { throw e;}) .then : Symbol(Promise.then, Decl(lib.d.ts, 4775, 22), Decl(lib.d.ts, 4782, 158)) +>f1() .then : Symbol(Promise.then, Decl(lib.d.ts, 4775, 22), Decl(lib.d.ts, 4782, 158)) >f1 : Symbol(f1, Decl(promiseVoidErrorCallback.ts, 10, 1)) .then(f2, (e: Error) => { ->then : Symbol(Promise.then, Decl(lib.d.ts, 4771, 22), Decl(lib.d.ts, 4778, 158)) +>then : Symbol(Promise.then, Decl(lib.d.ts, 4775, 22), Decl(lib.d.ts, 4782, 158)) >f2 : Symbol(f2, Decl(promiseVoidErrorCallback.ts, 14, 1)) >e : Symbol(e, Decl(promiseVoidErrorCallback.ts, 21, 15)) >Error : Symbol(Error, Decl(lib.d.ts, 876, 38), Decl(lib.d.ts, 889, 11)) @@ -62,7 +62,7 @@ var x3 = f1() }) .then((x: T2) => { ->then : Symbol(Promise.then, Decl(lib.d.ts, 4771, 22), Decl(lib.d.ts, 4778, 158)) +>then : Symbol(Promise.then, Decl(lib.d.ts, 4775, 22), Decl(lib.d.ts, 4782, 158)) >x : Symbol(x, Decl(promiseVoidErrorCallback.ts, 24, 11)) >T2 : Symbol(T2, Decl(promiseVoidErrorCallback.ts, 2, 1)) diff --git a/tests/baselines/reference/typedArrays.symbols b/tests/baselines/reference/typedArrays.symbols index 4ea9d0283a9..a6b8cb52a86 100644 --- a/tests/baselines/reference/typedArrays.symbols +++ b/tests/baselines/reference/typedArrays.symbols @@ -8,39 +8,39 @@ function CreateTypedArrayTypes() { typedArrays[0] = Int8Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) typedArrays[1] = Uint8Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) typedArrays[2] = Int16Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) typedArrays[3] = Uint16Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) typedArrays[4] = Int32Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) typedArrays[5] = Uint32Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) typedArrays[6] = Float32Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) typedArrays[7] = Float64Array; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) typedArrays[8] = Uint8ClampedArray; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) return typedArrays; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 2, 7)) @@ -55,47 +55,47 @@ function CreateTypedArrayInstancesFromLength(obj: number) { typedArrays[0] = new Int8Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[1] = new Uint8Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[2] = new Int16Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[3] = new Uint16Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[4] = new Int32Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[5] = new Uint32Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[6] = new Float32Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[7] = new Float64Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) typedArrays[8] = new Uint8ClampedArray(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 17, 7)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 16, 45)) return typedArrays; @@ -111,47 +111,47 @@ function CreateTypedArrayInstancesFromArray(obj: number[]) { typedArrays[0] = new Int8Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[1] = new Uint8Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[2] = new Int16Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[3] = new Uint16Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[4] = new Int32Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[5] = new Uint32Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[6] = new Float32Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[7] = new Float64Array(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) typedArrays[8] = new Uint8ClampedArray(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 32, 7)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) >obj : Symbol(obj, Decl(typedArrays.ts, 31, 44)) return typedArrays; @@ -167,65 +167,65 @@ function CreateIntegerTypedArraysFromArray2(obj:number[]) { typedArrays[0] = Int8Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) ->from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) +>Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) +>from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[1] = Uint8Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) ->from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) +>Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) +>from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[2] = Int16Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) ->from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) +>Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) +>from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[3] = Uint16Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) ->from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) +>Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) +>from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[4] = Int32Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) ->from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) +>Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) +>from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[5] = Uint32Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) ->from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) +>Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) +>from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[6] = Float32Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) ->from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) +>Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) +>from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[7] = Float64Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) ->from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) +>Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) +>from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) typedArrays[8] = Uint8ClampedArray.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 47, 7)) ->Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) ->from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) +>Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) +>from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) >obj : Symbol(obj, Decl(typedArrays.ts, 46, 44)) return typedArrays; @@ -242,65 +242,65 @@ function CreateIntegerTypedArraysFromArrayLike(obj:ArrayLike) { typedArrays[0] = Int8Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) ->from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) +>Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) +>from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[1] = Uint8Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) ->from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) +>Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) +>from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[2] = Int16Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) ->from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) +>Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) +>from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[3] = Uint16Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) ->from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) +>Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) +>from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[4] = Int32Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) ->from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) +>Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) +>from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[5] = Uint32Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) ->from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) +>Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) +>from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[6] = Float32Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) ->from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) +>Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) +>from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[7] = Float64Array.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) ->from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) +>Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) +>from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) typedArrays[8] = Uint8ClampedArray.from(obj); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 62, 7)) ->Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) ->from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) +>Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) +>from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) >obj : Symbol(obj, Decl(typedArrays.ts, 61, 47)) return typedArrays; @@ -332,57 +332,57 @@ function CreateTypedArraysOf2() { typedArrays[0] = Int8Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Int8Array.of : Symbol(Int8ArrayConstructor.of, Decl(lib.d.ts, 2378, 30)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) ->of : Symbol(Int8ArrayConstructor.of, Decl(lib.d.ts, 2378, 30)) +>Int8Array.of : Symbol(Int8ArrayConstructor.of, Decl(lib.d.ts, 2382, 30)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) +>of : Symbol(Int8ArrayConstructor.of, Decl(lib.d.ts, 2382, 30)) typedArrays[1] = Uint8Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Uint8Array.of : Symbol(Uint8ArrayConstructor.of, Decl(lib.d.ts, 2668, 30)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) ->of : Symbol(Uint8ArrayConstructor.of, Decl(lib.d.ts, 2668, 30)) +>Uint8Array.of : Symbol(Uint8ArrayConstructor.of, Decl(lib.d.ts, 2672, 30)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) +>of : Symbol(Uint8ArrayConstructor.of, Decl(lib.d.ts, 2672, 30)) typedArrays[2] = Int16Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Int16Array.of : Symbol(Int16ArrayConstructor.of, Decl(lib.d.ts, 3248, 30)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) ->of : Symbol(Int16ArrayConstructor.of, Decl(lib.d.ts, 3248, 30)) +>Int16Array.of : Symbol(Int16ArrayConstructor.of, Decl(lib.d.ts, 3252, 30)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) +>of : Symbol(Int16ArrayConstructor.of, Decl(lib.d.ts, 3252, 30)) typedArrays[3] = Uint16Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Uint16Array.of : Symbol(Uint16ArrayConstructor.of, Decl(lib.d.ts, 3538, 30)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) ->of : Symbol(Uint16ArrayConstructor.of, Decl(lib.d.ts, 3538, 30)) +>Uint16Array.of : Symbol(Uint16ArrayConstructor.of, Decl(lib.d.ts, 3542, 30)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) +>of : Symbol(Uint16ArrayConstructor.of, Decl(lib.d.ts, 3542, 30)) typedArrays[4] = Int32Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Int32Array.of : Symbol(Int32ArrayConstructor.of, Decl(lib.d.ts, 3828, 30)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) ->of : Symbol(Int32ArrayConstructor.of, Decl(lib.d.ts, 3828, 30)) +>Int32Array.of : Symbol(Int32ArrayConstructor.of, Decl(lib.d.ts, 3832, 30)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) +>of : Symbol(Int32ArrayConstructor.of, Decl(lib.d.ts, 3832, 30)) typedArrays[5] = Uint32Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Uint32Array.of : Symbol(Uint32ArrayConstructor.of, Decl(lib.d.ts, 4118, 30)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) ->of : Symbol(Uint32ArrayConstructor.of, Decl(lib.d.ts, 4118, 30)) +>Uint32Array.of : Symbol(Uint32ArrayConstructor.of, Decl(lib.d.ts, 4122, 30)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) +>of : Symbol(Uint32ArrayConstructor.of, Decl(lib.d.ts, 4122, 30)) typedArrays[6] = Float32Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Float32Array.of : Symbol(Float32ArrayConstructor.of, Decl(lib.d.ts, 4408, 30)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) ->of : Symbol(Float32ArrayConstructor.of, Decl(lib.d.ts, 4408, 30)) +>Float32Array.of : Symbol(Float32ArrayConstructor.of, Decl(lib.d.ts, 4412, 30)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) +>of : Symbol(Float32ArrayConstructor.of, Decl(lib.d.ts, 4412, 30)) typedArrays[7] = Float64Array.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Float64Array.of : Symbol(Float64ArrayConstructor.of, Decl(lib.d.ts, 4698, 30)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) ->of : Symbol(Float64ArrayConstructor.of, Decl(lib.d.ts, 4698, 30)) +>Float64Array.of : Symbol(Float64ArrayConstructor.of, Decl(lib.d.ts, 4702, 30)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) +>of : Symbol(Float64ArrayConstructor.of, Decl(lib.d.ts, 4702, 30)) typedArrays[8] = Uint8ClampedArray.of(1,2,3,4); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) ->Uint8ClampedArray.of : Symbol(Uint8ClampedArrayConstructor.of, Decl(lib.d.ts, 2958, 30)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) ->of : Symbol(Uint8ClampedArrayConstructor.of, Decl(lib.d.ts, 2958, 30)) +>Uint8ClampedArray.of : Symbol(Uint8ClampedArrayConstructor.of, Decl(lib.d.ts, 2962, 30)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) +>of : Symbol(Uint8ClampedArrayConstructor.of, Decl(lib.d.ts, 2962, 30)) return typedArrays; >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 94, 7)) @@ -401,73 +401,73 @@ function CreateTypedArraysFromMapFn(obj:ArrayLike, mapFn: (n:number, v:n typedArrays[0] = Int8Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) ->from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) +>Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) +>from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[1] = Uint8Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) ->from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) +>Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) +>from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[2] = Int16Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) ->from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) +>Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) +>from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[3] = Uint16Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) ->from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) +>Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) +>from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[4] = Int32Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) ->from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) +>Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) +>from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[5] = Uint32Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) ->from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) +>Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) +>from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[6] = Float32Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) ->from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) +>Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) +>from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[7] = Float64Array.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) ->from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) +>Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) +>from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) typedArrays[8] = Uint8ClampedArray.from(obj, mapFn); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 109, 7)) ->Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) ->from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) +>Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) +>from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) >obj : Symbol(obj, Decl(typedArrays.ts, 108, 36)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 108, 58)) @@ -489,81 +489,81 @@ function CreateTypedArraysFromThisObj(obj:ArrayLike, mapFn: (n:number, v typedArrays[0] = Int8Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) ->Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2104, 42), Decl(lib.d.ts, 2394, 11)) ->from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2384, 38)) +>Int8Array.from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) +>Int8Array : Symbol(Int8Array, Decl(lib.d.ts, 2108, 42), Decl(lib.d.ts, 2398, 11)) +>from : Symbol(Int8ArrayConstructor.from, Decl(lib.d.ts, 2388, 38)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[1] = Uint8Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2394, 44), Decl(lib.d.ts, 2684, 11)) ->from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2674, 39)) +>Uint8Array.from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.d.ts, 2398, 44), Decl(lib.d.ts, 2688, 11)) +>from : Symbol(Uint8ArrayConstructor.from, Decl(lib.d.ts, 2678, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[2] = Int16Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) ->Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2974, 60), Decl(lib.d.ts, 3264, 11)) ->from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3254, 39)) +>Int16Array.from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) +>Int16Array : Symbol(Int16Array, Decl(lib.d.ts, 2978, 60), Decl(lib.d.ts, 3268, 11)) +>from : Symbol(Int16ArrayConstructor.from, Decl(lib.d.ts, 3258, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[3] = Uint16Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) ->Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3264, 46), Decl(lib.d.ts, 3554, 11)) ->from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3544, 40)) +>Uint16Array.from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) +>Uint16Array : Symbol(Uint16Array, Decl(lib.d.ts, 3268, 46), Decl(lib.d.ts, 3558, 11)) +>from : Symbol(Uint16ArrayConstructor.from, Decl(lib.d.ts, 3548, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[4] = Int32Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) ->Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3554, 48), Decl(lib.d.ts, 3844, 11)) ->from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3834, 39)) +>Int32Array.from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) +>Int32Array : Symbol(Int32Array, Decl(lib.d.ts, 3558, 48), Decl(lib.d.ts, 3848, 11)) +>from : Symbol(Int32ArrayConstructor.from, Decl(lib.d.ts, 3838, 39)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[5] = Uint32Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) ->Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3844, 46), Decl(lib.d.ts, 4134, 11)) ->from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4124, 40)) +>Uint32Array.from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) +>Uint32Array : Symbol(Uint32Array, Decl(lib.d.ts, 3848, 46), Decl(lib.d.ts, 4138, 11)) +>from : Symbol(Uint32ArrayConstructor.from, Decl(lib.d.ts, 4128, 40)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[6] = Float32Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) ->Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4134, 48), Decl(lib.d.ts, 4424, 11)) ->from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4414, 41)) +>Float32Array.from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) +>Float32Array : Symbol(Float32Array, Decl(lib.d.ts, 4138, 48), Decl(lib.d.ts, 4428, 11)) +>from : Symbol(Float32ArrayConstructor.from, Decl(lib.d.ts, 4418, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[7] = Float64Array.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) ->Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4424, 50), Decl(lib.d.ts, 4714, 11)) ->from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4704, 41)) +>Float64Array.from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) +>Float64Array : Symbol(Float64Array, Decl(lib.d.ts, 4428, 50), Decl(lib.d.ts, 4718, 11)) +>from : Symbol(Float64ArrayConstructor.from, Decl(lib.d.ts, 4708, 41)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) typedArrays[8] = Uint8ClampedArray.from(obj, mapFn, thisArg); >typedArrays : Symbol(typedArrays, Decl(typedArrays.ts, 124, 7)) ->Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) ->Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2684, 46), Decl(lib.d.ts, 2974, 11)) ->from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2964, 46)) +>Uint8ClampedArray.from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) +>Uint8ClampedArray : Symbol(Uint8ClampedArray, Decl(lib.d.ts, 2688, 46), Decl(lib.d.ts, 2978, 11)) +>from : Symbol(Uint8ClampedArrayConstructor.from, Decl(lib.d.ts, 2968, 46)) >obj : Symbol(obj, Decl(typedArrays.ts, 123, 38)) >mapFn : Symbol(mapFn, Decl(typedArrays.ts, 123, 60)) >thisArg : Symbol(thisArg, Decl(typedArrays.ts, 123, 98)) From a264be5afaa8ac6f27f827303b789618a1dd068f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 18 Jun 2015 10:25:23 -0700 Subject: [PATCH 14/79] Actually check types in checkClassExpression --- src/compiler/checker.ts | 21 ++++++++------------- src/compiler/utilities.ts | 15 ++++++++++++++- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 232a3db419a..76bc4e9a94e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1402,15 +1402,8 @@ namespace ts { * for the name of the symbol if it is available to match how the user inputted the name. */ function appendSymbolNameOnly(symbol: Symbol, writer: SymbolWriter): void { - if (symbol.declarations && symbol.declarations.length > 0) { - let declaration = symbol.declarations[0]; - if (declaration.name) { - writer.writeSymbol(declarationNameToString(declaration.name), symbol); - return; - } - } - - writer.writeSymbol(symbol.name, symbol); + let name = symbol.declarations && symbol.declarations.length > 0 ? declarationToString(symbol.declarations[0]) : symbol.name; + writer.writeSymbol(name, symbol); } /** @@ -10565,9 +10558,8 @@ namespace ts { } function checkClassExpression(node: ClassExpression): Type { - grammarErrorOnNode(node, Diagnostics.class_expressions_are_not_currently_supported); - forEach(node.members, checkSourceElement); - return unknownType; + checkClassLikeDeclaration(node); + return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node: ClassDeclaration) { @@ -10575,7 +10567,10 @@ namespace ts { if (!node.name && !(node.flags & NodeFlags.Default)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } + checkClassLikeDeclaration(node); + } + function checkClassLikeDeclaration(node: ClassLikeDeclaration) { checkGrammarClassDeclarationHeritageClauses(node); checkDecorators(node); if (node.name) { @@ -12921,7 +12916,7 @@ namespace ts { } } - function checkGrammarClassDeclarationHeritageClauses(node: ClassDeclaration) { + function checkGrammarClassDeclarationHeritageClauses(node: ClassLikeDeclaration) { let seenExtendsClause = false; let seenImplementsClause = false; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7f9888c73d3..f50f280d861 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -247,6 +247,19 @@ namespace ts { declaration.parent.kind === SyntaxKind.CatchClause; } + export function declarationToString(declaration: Declaration) { + if (!declaration.name) { + switch (declaration.kind) { + case SyntaxKind.ClassExpression: + return "(Anonymous class)"; + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return "(Anonymous function)"; + } + } + return declarationNameToString(declaration.name); + } + // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. @@ -1234,7 +1247,7 @@ namespace ts { return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } - export function getClassImplementsHeritageClauseElements(node: ClassDeclaration) { + export function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration) { let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword); return heritageClause ? heritageClause.types : undefined; } From 23603a39b82abd9ce33a83f54345981c3471f370 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 18 Jun 2015 13:54:08 -0700 Subject: [PATCH 15/79] Defer checking of class expression bodies --- src/compiler/checker.ts | 67 ++++++++++++------- .../diagnosticInformationMap.generated.ts | 2 - src/compiler/diagnosticMessages.json | 9 --- src/compiler/utilities.ts | 13 ---- 4 files changed, 42 insertions(+), 49 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 76bc4e9a94e..4891bff8630 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -409,6 +409,13 @@ namespace ts { } break loop; } + if (location.kind === SyntaxKind.ClassExpression && meaning & SymbolFlags.Class) { + let className = (location).name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } + } break; // It is not legal to reference a class's own type parameters from a computed property name that @@ -455,15 +462,6 @@ namespace ts { } } break; - case SyntaxKind.ClassExpression: - if (meaning & SymbolFlags.Class) { - let className = (location).name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; case SyntaxKind.Decorator: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. @@ -1397,13 +1395,30 @@ namespace ts { // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. let _displayBuilder: SymbolDisplayBuilder; function getSymbolDisplayBuilder(): SymbolDisplayBuilder { + + function getNameOfSymbol(symbol: Symbol): string { + if (symbol.declarations && symbol.declarations.length) { + let declaration = symbol.declarations[0]; + if (declaration.name) { + return declarationNameToString(declaration.name); + } + switch (declaration.kind) { + case SyntaxKind.ClassExpression: + return "(Anonymous class)"; + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return "(Anonymous function)"; + } + } + return symbol.name; + } + /** * Writes only the name of the symbol out to the writer. Uses the original source text * for the name of the symbol if it is available to match how the user inputted the name. */ function appendSymbolNameOnly(symbol: Symbol, writer: SymbolWriter): void { - let name = symbol.declarations && symbol.declarations.length > 0 ? declarationToString(symbol.declarations[0]) : symbol.name; - writer.writeSymbol(name, symbol); + writer.writeSymbol(getNameOfSymbol(symbol), symbol); } /** @@ -7851,7 +7866,7 @@ namespace ts { if (node.type) { checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, /*headMessage*/ undefined); } - checkFunctionExpressionBodies(node.body); + checkFunctionAndClassExpressionBodies(node.body); } } } @@ -9567,7 +9582,7 @@ namespace ts { forEach(node.statements, checkSourceElement); if (isFunctionBlock(node) || node.kind === SyntaxKind.ModuleBlock) { - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); } } @@ -10563,11 +10578,11 @@ namespace ts { } function checkClassDeclaration(node: ClassDeclaration) { - // Grammar checking if (!node.name && !(node.flags & NodeFlags.Default)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); + forEach(node.members, checkSourceElement); } function checkClassLikeDeclaration(node: ClassLikeDeclaration) { @@ -10638,7 +10653,6 @@ namespace ts { }); } - forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -11511,8 +11525,8 @@ namespace ts { } } - // Function expression bodies are checked after all statements in the enclosing body. This is to ensure - // constructs like the following are permitted: + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: // let foo = function () { // let s = foo(); // return "hello"; @@ -11520,17 +11534,20 @@ namespace ts { // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionExpressionBodies(node: Node): void { + function checkFunctionAndClassExpressionBodies(node: Node): void { switch (node.kind) { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - forEach((node).parameters, checkFunctionExpressionBodies); + forEach((node).parameters, checkFunctionAndClassExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case SyntaxKind.ClassExpression: + forEach((node).members, checkSourceElement); + break; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - forEach(node.decorators, checkFunctionExpressionBodies); - forEach((node).parameters, checkFunctionExpressionBodies); + forEach(node.decorators, checkFunctionAndClassExpressionBodies); + forEach((node).parameters, checkFunctionAndClassExpressionBodies); if (isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } @@ -11539,10 +11556,10 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionDeclaration: - forEach((node).parameters, checkFunctionExpressionBodies); + forEach((node).parameters, checkFunctionAndClassExpressionBodies); break; case SyntaxKind.WithStatement: - checkFunctionExpressionBodies((node).expression); + checkFunctionAndClassExpressionBodies((node).expression); break; case SyntaxKind.Decorator: case SyntaxKind.Parameter: @@ -11599,7 +11616,7 @@ namespace ts { case SyntaxKind.EnumMember: case SyntaxKind.ExportAssignment: case SyntaxKind.SourceFile: - forEachChild(node, checkFunctionExpressionBodies); + forEachChild(node, checkFunctionAndClassExpressionBodies); break; } } @@ -11631,7 +11648,7 @@ namespace ts { potentialThisCollisions.length = 0; forEach(node.statements, checkSourceElement); - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); if (isExternalModule(node)) { checkExternalModuleExports(node); diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 09b009711fe..bfe103757c5 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -567,7 +567,5 @@ namespace ts { enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, }; } \ No newline at end of file diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index fee46a84c1e..3e4ef26507f 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2259,14 +2259,5 @@ "'decorators' can only be used in a .ts file.": { "category": "Error", "code": 8017 - }, - - "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": { - "category": "Error", - "code": 9002 - }, - "'class' expressions are not currently supported.": { - "category": "Error", - "code": 9003 } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index f50f280d861..c820c588689 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -247,19 +247,6 @@ namespace ts { declaration.parent.kind === SyntaxKind.CatchClause; } - export function declarationToString(declaration: Declaration) { - if (!declaration.name) { - switch (declaration.kind) { - case SyntaxKind.ClassExpression: - return "(Anonymous class)"; - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - return "(Anonymous function)"; - } - } - return declarationNameToString(declaration.name); - } - // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. From b518dc1e5b3126390d14a34236748c6ba6778502 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 18 Jun 2015 13:56:21 -0700 Subject: [PATCH 16/79] Accepting new baselines --- .../anonymousClassExpression1.errors.txt | 9 ----- .../anonymousClassExpression1.symbols | 6 +++ .../reference/anonymousClassExpression1.types | 10 +++++ .../reference/classExpression.errors.txt | 24 ----------- .../reference/classExpression.symbols | 23 +++++++++++ .../baselines/reference/classExpression.types | 27 +++++++++++++ .../reference/classExpression1.errors.txt | 7 ---- .../reference/classExpression1.symbols | 5 +++ .../reference/classExpression1.types | 6 +++ .../reference/classExpression2.errors.txt | 8 ---- tests/baselines/reference/classExpression2.js | 5 +++ .../reference/classExpression2.symbols | 9 +++++ .../reference/classExpression2.types | 10 +++++ .../reference/classExpressionES61.errors.txt | 7 ---- .../reference/classExpressionES61.symbols | 5 +++ .../reference/classExpressionES61.types | 6 +++ .../reference/classExpressionES62.errors.txt | 8 ---- .../reference/classExpressionES62.symbols | 9 +++++ .../reference/classExpressionES62.types | 10 +++++ .../reference/classExpressionTest2.errors.txt | 21 ---------- .../reference/classExpressionTest2.symbols | 36 +++++++++++++++++ .../reference/classExpressionTest2.types | 40 +++++++++++++++++++ ...solutionOfNamespaceOfSameName01.errors.txt | 14 ------- ...hResolutionOfNamespaceOfSameName01.symbols | 18 +++++++++ ...ithResolutionOfNamespaceOfSameName01.types | 19 +++++++++ ...ExpressionWithStaticProperties1.errors.txt | 7 ---- ...assExpressionWithStaticProperties1.symbols | 7 ++++ ...classExpressionWithStaticProperties1.types | 10 +++++ ...ExpressionWithStaticProperties2.errors.txt | 7 ---- ...assExpressionWithStaticProperties2.symbols | 7 ++++ ...classExpressionWithStaticProperties2.types | 9 +++++ ...ressionWithStaticPropertiesES61.errors.txt | 7 ---- ...ExpressionWithStaticPropertiesES61.symbols | 7 ++++ ...ssExpressionWithStaticPropertiesES61.types | 10 +++++ ...ressionWithStaticPropertiesES62.errors.txt | 7 ---- ...ExpressionWithStaticPropertiesES62.symbols | 7 ++++ ...ssExpressionWithStaticPropertiesES62.types | 9 +++++ .../exportAssignNonIdentifier.errors.txt | 5 +-- .../reference/generatorTypeCheck55.errors.txt | 11 +++-- .../reference/generatorTypeCheck56.errors.txt | 5 +-- .../strictModeReservedWord.errors.txt | 6 +-- .../reference/strictModeReservedWord.js | 5 +++ 42 files changed, 327 insertions(+), 141 deletions(-) delete mode 100644 tests/baselines/reference/anonymousClassExpression1.errors.txt create mode 100644 tests/baselines/reference/anonymousClassExpression1.symbols create mode 100644 tests/baselines/reference/anonymousClassExpression1.types delete mode 100644 tests/baselines/reference/classExpression.errors.txt create mode 100644 tests/baselines/reference/classExpression.symbols create mode 100644 tests/baselines/reference/classExpression.types delete mode 100644 tests/baselines/reference/classExpression1.errors.txt create mode 100644 tests/baselines/reference/classExpression1.symbols create mode 100644 tests/baselines/reference/classExpression1.types delete mode 100644 tests/baselines/reference/classExpression2.errors.txt create mode 100644 tests/baselines/reference/classExpression2.symbols create mode 100644 tests/baselines/reference/classExpression2.types delete mode 100644 tests/baselines/reference/classExpressionES61.errors.txt create mode 100644 tests/baselines/reference/classExpressionES61.symbols create mode 100644 tests/baselines/reference/classExpressionES61.types delete mode 100644 tests/baselines/reference/classExpressionES62.errors.txt create mode 100644 tests/baselines/reference/classExpressionES62.symbols create mode 100644 tests/baselines/reference/classExpressionES62.types delete mode 100644 tests/baselines/reference/classExpressionTest2.errors.txt create mode 100644 tests/baselines/reference/classExpressionTest2.symbols create mode 100644 tests/baselines/reference/classExpressionTest2.types delete mode 100644 tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt create mode 100644 tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.symbols create mode 100644 tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.types delete mode 100644 tests/baselines/reference/classExpressionWithStaticProperties1.errors.txt create mode 100644 tests/baselines/reference/classExpressionWithStaticProperties1.symbols create mode 100644 tests/baselines/reference/classExpressionWithStaticProperties1.types delete mode 100644 tests/baselines/reference/classExpressionWithStaticProperties2.errors.txt create mode 100644 tests/baselines/reference/classExpressionWithStaticProperties2.symbols create mode 100644 tests/baselines/reference/classExpressionWithStaticProperties2.types delete mode 100644 tests/baselines/reference/classExpressionWithStaticPropertiesES61.errors.txt create mode 100644 tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols create mode 100644 tests/baselines/reference/classExpressionWithStaticPropertiesES61.types delete mode 100644 tests/baselines/reference/classExpressionWithStaticPropertiesES62.errors.txt create mode 100644 tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols create mode 100644 tests/baselines/reference/classExpressionWithStaticPropertiesES62.types diff --git a/tests/baselines/reference/anonymousClassExpression1.errors.txt b/tests/baselines/reference/anonymousClassExpression1.errors.txt deleted file mode 100644 index db4c5b4ce3d..00000000000 --- a/tests/baselines/reference/anonymousClassExpression1.errors.txt +++ /dev/null @@ -1,9 +0,0 @@ -tests/cases/compiler/anonymousClassExpression1.ts(2,19): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/compiler/anonymousClassExpression1.ts (1 errors) ==== - function f() { - return typeof class {} === "function"; - ~~~~~ -!!! error TS9003: 'class' expressions are not currently supported. - } \ No newline at end of file diff --git a/tests/baselines/reference/anonymousClassExpression1.symbols b/tests/baselines/reference/anonymousClassExpression1.symbols new file mode 100644 index 00000000000..114bfc96097 --- /dev/null +++ b/tests/baselines/reference/anonymousClassExpression1.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/anonymousClassExpression1.ts === +function f() { +>f : Symbol(f, Decl(anonymousClassExpression1.ts, 0, 0)) + + return typeof class {} === "function"; +} diff --git a/tests/baselines/reference/anonymousClassExpression1.types b/tests/baselines/reference/anonymousClassExpression1.types new file mode 100644 index 00000000000..1e38399f01e --- /dev/null +++ b/tests/baselines/reference/anonymousClassExpression1.types @@ -0,0 +1,10 @@ +=== tests/cases/compiler/anonymousClassExpression1.ts === +function f() { +>f : () => boolean + + return typeof class {} === "function"; +>typeof class {} === "function" : boolean +>typeof class {} : string +>class {} : typeof (Anonymous class) +>"function" : string +} diff --git a/tests/baselines/reference/classExpression.errors.txt b/tests/baselines/reference/classExpression.errors.txt deleted file mode 100644 index c8266d0e879..00000000000 --- a/tests/baselines/reference/classExpression.errors.txt +++ /dev/null @@ -1,24 +0,0 @@ -tests/cases/conformance/classes/classExpression.ts(1,15): error TS9003: 'class' expressions are not currently supported. -tests/cases/conformance/classes/classExpression.ts(5,16): error TS9003: 'class' expressions are not currently supported. -tests/cases/conformance/classes/classExpression.ts(10,19): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/conformance/classes/classExpression.ts (3 errors) ==== - var x = class C { - ~ -!!! error TS9003: 'class' expressions are not currently supported. - } - - var y = { - foo: class C2 { - ~~ -!!! error TS9003: 'class' expressions are not currently supported. - } - } - - module M { - var z = class C4 { - ~~ -!!! error TS9003: 'class' expressions are not currently supported. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/classExpression.symbols b/tests/baselines/reference/classExpression.symbols new file mode 100644 index 00000000000..f4d44236499 --- /dev/null +++ b/tests/baselines/reference/classExpression.symbols @@ -0,0 +1,23 @@ +=== tests/cases/conformance/classes/classExpression.ts === +var x = class C { +>x : Symbol(x, Decl(classExpression.ts, 0, 3)) +>C : Symbol(C, Decl(classExpression.ts, 0, 7)) +} + +var y = { +>y : Symbol(y, Decl(classExpression.ts, 3, 3)) + + foo: class C2 { +>foo : Symbol(foo, Decl(classExpression.ts, 3, 9)) +>C2 : Symbol(C2, Decl(classExpression.ts, 4, 8)) + } +} + +module M { +>M : Symbol(M, Decl(classExpression.ts, 6, 1)) + + var z = class C4 { +>z : Symbol(z, Decl(classExpression.ts, 9, 7)) +>C4 : Symbol(C4, Decl(classExpression.ts, 9, 11)) + } +} diff --git a/tests/baselines/reference/classExpression.types b/tests/baselines/reference/classExpression.types new file mode 100644 index 00000000000..1c55ce89544 --- /dev/null +++ b/tests/baselines/reference/classExpression.types @@ -0,0 +1,27 @@ +=== tests/cases/conformance/classes/classExpression.ts === +var x = class C { +>x : typeof C +>class C {} : typeof C +>C : typeof C +} + +var y = { +>y : { foo: typeof C2; } +>{ foo: class C2 { }} : { foo: typeof C2; } + + foo: class C2 { +>foo : typeof C2 +>class C2 { } : typeof C2 +>C2 : typeof C2 + } +} + +module M { +>M : typeof M + + var z = class C4 { +>z : typeof C4 +>class C4 { } : typeof C4 +>C4 : typeof C4 + } +} diff --git a/tests/baselines/reference/classExpression1.errors.txt b/tests/baselines/reference/classExpression1.errors.txt deleted file mode 100644 index 9d7d14d8571..00000000000 --- a/tests/baselines/reference/classExpression1.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/conformance/classes/classExpressions/classExpression1.ts(1,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/conformance/classes/classExpressions/classExpression1.ts (1 errors) ==== - var v = class C {}; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpression1.symbols b/tests/baselines/reference/classExpression1.symbols new file mode 100644 index 00000000000..8d3bad269b4 --- /dev/null +++ b/tests/baselines/reference/classExpression1.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression1.ts === +var v = class C {}; +>v : Symbol(v, Decl(classExpression1.ts, 0, 3)) +>C : Symbol(C, Decl(classExpression1.ts, 0, 7)) + diff --git a/tests/baselines/reference/classExpression1.types b/tests/baselines/reference/classExpression1.types new file mode 100644 index 00000000000..4bea3183118 --- /dev/null +++ b/tests/baselines/reference/classExpression1.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression1.ts === +var v = class C {}; +>v : typeof C +>class C {} : typeof C +>C : typeof C + diff --git a/tests/baselines/reference/classExpression2.errors.txt b/tests/baselines/reference/classExpression2.errors.txt deleted file mode 100644 index e2f3ccd77cd..00000000000 --- a/tests/baselines/reference/classExpression2.errors.txt +++ /dev/null @@ -1,8 +0,0 @@ -tests/cases/conformance/classes/classExpressions/classExpression2.ts(2,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/conformance/classes/classExpressions/classExpression2.ts (1 errors) ==== - class D { } - var v = class C extends D {}; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpression2.js b/tests/baselines/reference/classExpression2.js index 4220b88fb11..f74bb8bd5e2 100644 --- a/tests/baselines/reference/classExpression2.js +++ b/tests/baselines/reference/classExpression2.js @@ -3,6 +3,11 @@ class D { } var v = class C extends D {}; //// [classExpression2.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; var D = (function () { function D() { } diff --git a/tests/baselines/reference/classExpression2.symbols b/tests/baselines/reference/classExpression2.symbols new file mode 100644 index 00000000000..11c78a2cad2 --- /dev/null +++ b/tests/baselines/reference/classExpression2.symbols @@ -0,0 +1,9 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression2.ts === +class D { } +>D : Symbol(D, Decl(classExpression2.ts, 0, 0)) + +var v = class C extends D {}; +>v : Symbol(v, Decl(classExpression2.ts, 1, 3)) +>C : Symbol(C, Decl(classExpression2.ts, 1, 7)) +>D : Symbol(D, Decl(classExpression2.ts, 0, 0)) + diff --git a/tests/baselines/reference/classExpression2.types b/tests/baselines/reference/classExpression2.types new file mode 100644 index 00000000000..4dd6595fb49 --- /dev/null +++ b/tests/baselines/reference/classExpression2.types @@ -0,0 +1,10 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression2.ts === +class D { } +>D : D + +var v = class C extends D {}; +>v : typeof C +>class C extends D {} : typeof C +>C : typeof C +>D : D + diff --git a/tests/baselines/reference/classExpressionES61.errors.txt b/tests/baselines/reference/classExpressionES61.errors.txt deleted file mode 100644 index abaa5ab893c..00000000000 --- a/tests/baselines/reference/classExpressionES61.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/conformance/es6/classExpressions/classExpressionES61.ts(1,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/conformance/es6/classExpressions/classExpressionES61.ts (1 errors) ==== - var v = class C {}; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionES61.symbols b/tests/baselines/reference/classExpressionES61.symbols new file mode 100644 index 00000000000..1f49229fbc7 --- /dev/null +++ b/tests/baselines/reference/classExpressionES61.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES61.ts === +var v = class C {}; +>v : Symbol(v, Decl(classExpressionES61.ts, 0, 3)) +>C : Symbol(C, Decl(classExpressionES61.ts, 0, 7)) + diff --git a/tests/baselines/reference/classExpressionES61.types b/tests/baselines/reference/classExpressionES61.types new file mode 100644 index 00000000000..e04570308e8 --- /dev/null +++ b/tests/baselines/reference/classExpressionES61.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES61.ts === +var v = class C {}; +>v : typeof C +>class C {} : typeof C +>C : typeof C + diff --git a/tests/baselines/reference/classExpressionES62.errors.txt b/tests/baselines/reference/classExpressionES62.errors.txt deleted file mode 100644 index 1e28367a17e..00000000000 --- a/tests/baselines/reference/classExpressionES62.errors.txt +++ /dev/null @@ -1,8 +0,0 @@ -tests/cases/conformance/es6/classExpressions/classExpressionES62.ts(2,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/conformance/es6/classExpressions/classExpressionES62.ts (1 errors) ==== - class D { } - var v = class C extends D {}; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionES62.symbols b/tests/baselines/reference/classExpressionES62.symbols new file mode 100644 index 00000000000..18e1a48ca30 --- /dev/null +++ b/tests/baselines/reference/classExpressionES62.symbols @@ -0,0 +1,9 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES62.ts === +class D { } +>D : Symbol(D, Decl(classExpressionES62.ts, 0, 0)) + +var v = class C extends D {}; +>v : Symbol(v, Decl(classExpressionES62.ts, 1, 3)) +>C : Symbol(C, Decl(classExpressionES62.ts, 1, 7)) +>D : Symbol(D, Decl(classExpressionES62.ts, 0, 0)) + diff --git a/tests/baselines/reference/classExpressionES62.types b/tests/baselines/reference/classExpressionES62.types new file mode 100644 index 00000000000..8bb4e1a39ff --- /dev/null +++ b/tests/baselines/reference/classExpressionES62.types @@ -0,0 +1,10 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES62.ts === +class D { } +>D : D + +var v = class C extends D {}; +>v : typeof C +>class C extends D {} : typeof C +>C : typeof C +>D : D + diff --git a/tests/baselines/reference/classExpressionTest2.errors.txt b/tests/baselines/reference/classExpressionTest2.errors.txt deleted file mode 100644 index 424eb590611..00000000000 --- a/tests/baselines/reference/classExpressionTest2.errors.txt +++ /dev/null @@ -1,21 +0,0 @@ -tests/cases/compiler/classExpressionTest2.ts(2,19): error TS9003: 'class' expressions are not currently supported. -tests/cases/compiler/classExpressionTest2.ts(5,20): error TS2304: Cannot find name 'X'. - - -==== tests/cases/compiler/classExpressionTest2.ts (2 errors) ==== - function M() { - var m = class C { - ~ -!!! error TS9003: 'class' expressions are not currently supported. - f() { - var t: T; - var x: X; - ~ -!!! error TS2304: Cannot find name 'X'. - return { t, x }; - } - } - - var v = new m(); - return v.f(); - } \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionTest2.symbols b/tests/baselines/reference/classExpressionTest2.symbols new file mode 100644 index 00000000000..62143cf0b9f --- /dev/null +++ b/tests/baselines/reference/classExpressionTest2.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/classExpressionTest2.ts === +function M() { +>M : Symbol(M, Decl(classExpressionTest2.ts, 0, 0)) + + var m = class C { +>m : Symbol(m, Decl(classExpressionTest2.ts, 1, 7)) +>C : Symbol(C, Decl(classExpressionTest2.ts, 1, 11)) +>X : Symbol(X, Decl(classExpressionTest2.ts, 1, 20)) + + f() { +>f : Symbol(C.f, Decl(classExpressionTest2.ts, 1, 24)) +>T : Symbol(T, Decl(classExpressionTest2.ts, 2, 10)) + + var t: T; +>t : Symbol(t, Decl(classExpressionTest2.ts, 3, 15)) +>T : Symbol(T, Decl(classExpressionTest2.ts, 2, 10)) + + var x: X; +>x : Symbol(x, Decl(classExpressionTest2.ts, 4, 15)) +>X : Symbol(X, Decl(classExpressionTest2.ts, 1, 20)) + + return { t, x }; +>t : Symbol(t, Decl(classExpressionTest2.ts, 5, 20)) +>x : Symbol(x, Decl(classExpressionTest2.ts, 5, 23)) + } + } + + var v = new m(); +>v : Symbol(v, Decl(classExpressionTest2.ts, 9, 7)) +>m : Symbol(m, Decl(classExpressionTest2.ts, 1, 7)) + + return v.f(); +>v.f : Symbol(C.f, Decl(classExpressionTest2.ts, 1, 24)) +>v : Symbol(v, Decl(classExpressionTest2.ts, 9, 7)) +>f : Symbol(C.f, Decl(classExpressionTest2.ts, 1, 24)) +} diff --git a/tests/baselines/reference/classExpressionTest2.types b/tests/baselines/reference/classExpressionTest2.types new file mode 100644 index 00000000000..5586b451d3a --- /dev/null +++ b/tests/baselines/reference/classExpressionTest2.types @@ -0,0 +1,40 @@ +=== tests/cases/compiler/classExpressionTest2.ts === +function M() { +>M : () => { t: string; x: number; } + + var m = class C { +>m : typeof C +>class C { f() { var t: T; var x: X; return { t, x }; } } : typeof C +>C : typeof C +>X : X + + f() { +>f : () => { t: T; x: X; } +>T : T + + var t: T; +>t : T +>T : T + + var x: X; +>x : X +>X : X + + return { t, x }; +>{ t, x } : { t: T; x: X; } +>t : T +>x : X + } + } + + var v = new m(); +>v : +>new m() : +>m : typeof C + + return v.f(); +>v.f() : { t: string; x: number; } +>v.f : () => { t: T; x: number; } +>v : +>f : () => { t: T; x: number; } +} diff --git a/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt deleted file mode 100644 index 8edc1d8f74b..00000000000 --- a/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt +++ /dev/null @@ -1,14 +0,0 @@ -tests/cases/compiler/classExpressionWithResolutionOfNamespaceOfSameName01.ts(6,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/compiler/classExpressionWithResolutionOfNamespaceOfSameName01.ts (1 errors) ==== - namespace C { - export interface type { - } - } - - var x = class C { - ~ -!!! error TS9003: 'class' expressions are not currently supported. - prop: C.type; - } \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.symbols b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.symbols new file mode 100644 index 00000000000..fcd4f0388db --- /dev/null +++ b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/classExpressionWithResolutionOfNamespaceOfSameName01.ts === +namespace C { +>C : Symbol(C, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 0, 0)) + + export interface type { +>type : Symbol(type, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 0, 13)) + } +} + +var x = class C { +>x : Symbol(x, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 5, 3)) +>C : Symbol(C, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 5, 7)) + + prop: C.type; +>prop : Symbol(C.prop, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 5, 17)) +>C : Symbol(C, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 0, 0)) +>type : Symbol(C.type, Decl(classExpressionWithResolutionOfNamespaceOfSameName01.ts, 0, 13)) +} diff --git a/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.types b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.types new file mode 100644 index 00000000000..643cf65d2e0 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.types @@ -0,0 +1,19 @@ +=== tests/cases/compiler/classExpressionWithResolutionOfNamespaceOfSameName01.ts === +namespace C { +>C : any + + export interface type { +>type : type + } +} + +var x = class C { +>x : typeof C +>class C { prop: C.type;} : typeof C +>C : typeof C + + prop: C.type; +>prop : C.type +>C : any +>type : C.type +} diff --git a/tests/baselines/reference/classExpressionWithStaticProperties1.errors.txt b/tests/baselines/reference/classExpressionWithStaticProperties1.errors.txt deleted file mode 100644 index 28e42dd33f1..00000000000 --- a/tests/baselines/reference/classExpressionWithStaticProperties1.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/compiler/classExpressionWithStaticProperties1.ts(1,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/compiler/classExpressionWithStaticProperties1.ts (1 errors) ==== - var v = class C { static a = 1; static b = 2 }; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionWithStaticProperties1.symbols b/tests/baselines/reference/classExpressionWithStaticProperties1.symbols new file mode 100644 index 00000000000..d4c811daebe --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticProperties1.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/classExpressionWithStaticProperties1.ts === +var v = class C { static a = 1; static b = 2 }; +>v : Symbol(v, Decl(classExpressionWithStaticProperties1.ts, 0, 3)) +>C : Symbol(C, Decl(classExpressionWithStaticProperties1.ts, 0, 7)) +>a : Symbol(C.a, Decl(classExpressionWithStaticProperties1.ts, 0, 17)) +>b : Symbol(C.b, Decl(classExpressionWithStaticProperties1.ts, 0, 31)) + diff --git a/tests/baselines/reference/classExpressionWithStaticProperties1.types b/tests/baselines/reference/classExpressionWithStaticProperties1.types new file mode 100644 index 00000000000..b014f78abf7 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticProperties1.types @@ -0,0 +1,10 @@ +=== tests/cases/compiler/classExpressionWithStaticProperties1.ts === +var v = class C { static a = 1; static b = 2 }; +>v : typeof C +>class C { static a = 1; static b = 2 } : typeof C +>C : typeof C +>a : number +>1 : number +>b : number +>2 : number + diff --git a/tests/baselines/reference/classExpressionWithStaticProperties2.errors.txt b/tests/baselines/reference/classExpressionWithStaticProperties2.errors.txt deleted file mode 100644 index 9a915f70193..00000000000 --- a/tests/baselines/reference/classExpressionWithStaticProperties2.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/compiler/classExpressionWithStaticProperties2.ts(1,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/compiler/classExpressionWithStaticProperties2.ts (1 errors) ==== - var v = class C { static a = 1; static b }; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionWithStaticProperties2.symbols b/tests/baselines/reference/classExpressionWithStaticProperties2.symbols new file mode 100644 index 00000000000..480123a1c3b --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticProperties2.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/classExpressionWithStaticProperties2.ts === +var v = class C { static a = 1; static b }; +>v : Symbol(v, Decl(classExpressionWithStaticProperties2.ts, 0, 3)) +>C : Symbol(C, Decl(classExpressionWithStaticProperties2.ts, 0, 7)) +>a : Symbol(C.a, Decl(classExpressionWithStaticProperties2.ts, 0, 17)) +>b : Symbol(C.b, Decl(classExpressionWithStaticProperties2.ts, 0, 31)) + diff --git a/tests/baselines/reference/classExpressionWithStaticProperties2.types b/tests/baselines/reference/classExpressionWithStaticProperties2.types new file mode 100644 index 00000000000..9bfd6732350 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticProperties2.types @@ -0,0 +1,9 @@ +=== tests/cases/compiler/classExpressionWithStaticProperties2.ts === +var v = class C { static a = 1; static b }; +>v : typeof C +>class C { static a = 1; static b } : typeof C +>C : typeof C +>a : number +>1 : number +>b : any + diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.errors.txt b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.errors.txt deleted file mode 100644 index bc015a3d8f0..00000000000 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts(1,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts (1 errors) ==== - var v = class C { static a = 1; static b = 2 }; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols new file mode 100644 index 00000000000..c5f53e19bff --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts === +var v = class C { static a = 1; static b = 2 }; +>v : Symbol(v, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 3)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 7)) +>a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 17)) +>b : Symbol(C.b, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 31)) + diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types new file mode 100644 index 00000000000..02c385b7525 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types @@ -0,0 +1,10 @@ +=== tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts === +var v = class C { static a = 1; static b = 2 }; +>v : typeof C +>class C { static a = 1; static b = 2 } : typeof C +>C : typeof C +>a : number +>1 : number +>b : number +>2 : number + diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.errors.txt b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.errors.txt deleted file mode 100644 index bed4b2c01aa..00000000000 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts(1,15): error TS9003: 'class' expressions are not currently supported. - - -==== tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts (1 errors) ==== - var v = class C { static a = 1; static b }; - ~ -!!! error TS9003: 'class' expressions are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols new file mode 100644 index 00000000000..be57a289f53 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts === +var v = class C { static a = 1; static b }; +>v : Symbol(v, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 3)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 7)) +>a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 17)) +>b : Symbol(C.b, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 31)) + diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types new file mode 100644 index 00000000000..e8ded1422f1 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types @@ -0,0 +1,9 @@ +=== tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts === +var v = class C { static a = 1; static b }; +>v : typeof C +>class C { static a = 1; static b } : typeof C +>C : typeof C +>a : number +>1 : number +>b : any + diff --git a/tests/baselines/reference/exportAssignNonIdentifier.errors.txt b/tests/baselines/reference/exportAssignNonIdentifier.errors.txt index 09e86ec12c4..c3d58c9b36f 100644 --- a/tests/baselines/reference/exportAssignNonIdentifier.errors.txt +++ b/tests/baselines/reference/exportAssignNonIdentifier.errors.txt @@ -1,5 +1,4 @@ tests/cases/conformance/externalModules/foo1.ts(2,1): error TS1148: Cannot compile modules unless the '--module' flag is provided. -tests/cases/conformance/externalModules/foo3.ts(1,16): error TS9003: 'class' expressions are not currently supported. tests/cases/conformance/externalModules/foo6.ts(1,14): error TS1109: Expression expected. @@ -12,10 +11,8 @@ tests/cases/conformance/externalModules/foo6.ts(1,14): error TS1109: Expression ==== tests/cases/conformance/externalModules/foo2.ts (0 errors) ==== export = "sausages"; // Ok -==== tests/cases/conformance/externalModules/foo3.ts (1 errors) ==== +==== tests/cases/conformance/externalModules/foo3.ts (0 errors) ==== export = class Foo3 {}; // Error, not an expression - ~~~~ -!!! error TS9003: 'class' expressions are not currently supported. ==== tests/cases/conformance/externalModules/foo4.ts (0 errors) ==== export = true; // Ok diff --git a/tests/baselines/reference/generatorTypeCheck55.errors.txt b/tests/baselines/reference/generatorTypeCheck55.errors.txt index 0846d1c28ad..854c1801efd 100644 --- a/tests/baselines/reference/generatorTypeCheck55.errors.txt +++ b/tests/baselines/reference/generatorTypeCheck55.errors.txt @@ -1,9 +1,12 @@ -tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts(2,19): error TS9003: 'class' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts(2,29): error TS2507: Type 'any' is not a constructor function type. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts(2,30): error TS1163: A 'yield' expression is only allowed in a generator body. -==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts (1 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts (2 errors) ==== function* g() { var x = class C extends (yield) {}; - ~ -!!! error TS9003: 'class' expressions are not currently supported. + ~~~~~~~ +!!! error TS2507: Type 'any' is not a constructor function type. + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck56.errors.txt b/tests/baselines/reference/generatorTypeCheck56.errors.txt index 99e3b00de41..20961935807 100644 --- a/tests/baselines/reference/generatorTypeCheck56.errors.txt +++ b/tests/baselines/reference/generatorTypeCheck56.errors.txt @@ -1,12 +1,9 @@ -tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts(2,19): error TS9003: 'class' expressions are not currently supported. tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts(3,11): error TS1163: A 'yield' expression is only allowed in a generator body. -==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts (2 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts (1 errors) ==== function* g() { var x = class C { - ~ -!!! error TS9003: 'class' expressions are not currently supported. *[yield 0]() { ~~~~~ !!! error TS1163: A 'yield' expression is only allowed in a generator body. diff --git a/tests/baselines/reference/strictModeReservedWord.errors.txt b/tests/baselines/reference/strictModeReservedWord.errors.txt index b6e9161ce7e..6f6a387429d 100644 --- a/tests/baselines/reference/strictModeReservedWord.errors.txt +++ b/tests/baselines/reference/strictModeReservedWord.errors.txt @@ -17,8 +17,8 @@ tests/cases/compiler/strictModeReservedWord.ts(13,11): error TS1212: Identifier tests/cases/compiler/strictModeReservedWord.ts(13,20): error TS1212: Identifier expected. 'public' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(13,28): error TS1212: Identifier expected. 'package' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(15,25): error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. -tests/cases/compiler/strictModeReservedWord.ts(15,25): error TS9003: 'class' expressions are not currently supported. tests/cases/compiler/strictModeReservedWord.ts(15,41): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. +tests/cases/compiler/strictModeReservedWord.ts(15,41): error TS2507: Type 'number' is not a constructor function type. tests/cases/compiler/strictModeReservedWord.ts(17,9): error TS2300: Duplicate identifier 'b'. tests/cases/compiler/strictModeReservedWord.ts(17,12): error TS1212: Identifier expected. 'public' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(17,12): error TS2503: Cannot find namespace 'public'. @@ -95,10 +95,10 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok var myClass = class package extends public {} ~~~~~~~ !!! error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. - ~~~~~~~ -!!! error TS9003: 'class' expressions are not currently supported. ~~~~~~ !!! error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. + ~~~~~~ +!!! error TS2507: Type 'number' is not a constructor function type. var b: public.bar; ~ diff --git a/tests/baselines/reference/strictModeReservedWord.js b/tests/baselines/reference/strictModeReservedWord.js index 9be21b20ae6..bec159dee6f 100644 --- a/tests/baselines/reference/strictModeReservedWord.js +++ b/tests/baselines/reference/strictModeReservedWord.js @@ -28,6 +28,11 @@ function foo() { //// [strictModeReservedWord.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; var let = 10; function foo() { "use strict"; From 413f27842472e5b8ad9c2fc5787a9740abadebe0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 18 Jun 2015 14:17:13 -0700 Subject: [PATCH 17/79] Generate names of form class_N for anonymous classes --- src/compiler/emitter.ts | 7 ++++++- tests/baselines/reference/anonymousClassExpression1.js | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 469b13294ad..8e4a038dde4 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -264,6 +264,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return makeUniqueName("default"); } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForNode(node: Node) { switch (node.kind) { case SyntaxKind.Identifier: @@ -276,9 +280,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return generateNameForImportOrExportDeclaration(node); case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: - case SyntaxKind.ClassExpression: case SyntaxKind.ExportAssignment: return generateNameForExportDefault(); + case SyntaxKind.ClassExpression: + return generateNameForClassExpression(); } } diff --git a/tests/baselines/reference/anonymousClassExpression1.js b/tests/baselines/reference/anonymousClassExpression1.js index 78cf5b05c51..5ced5120979 100644 --- a/tests/baselines/reference/anonymousClassExpression1.js +++ b/tests/baselines/reference/anonymousClassExpression1.js @@ -6,8 +6,8 @@ function f() { //// [anonymousClassExpression1.js] function f() { return typeof (function () { - function default_1() { + function class_1() { } - return default_1; + return class_1; })() === "function"; } From f578ee8e05b949fc384d81997b2b1dce6aa87f2b Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 18 Jun 2015 15:07:49 -0700 Subject: [PATCH 18/79] Adding a few tests --- tests/baselines/reference/classExpression3.js | 38 +++++++++++++++++++ .../reference/classExpression3.symbols | 26 +++++++++++++ .../reference/classExpression3.types | 33 ++++++++++++++++ tests/baselines/reference/classExpression4.js | 19 ++++++++++ .../reference/classExpression4.symbols | 17 +++++++++ .../reference/classExpression4.types | 22 +++++++++++ .../classExpressions/classExpression3.ts | 5 +++ .../classExpressions/classExpression4.ts | 6 +++ 8 files changed, 166 insertions(+) create mode 100644 tests/baselines/reference/classExpression3.js create mode 100644 tests/baselines/reference/classExpression3.symbols create mode 100644 tests/baselines/reference/classExpression3.types create mode 100644 tests/baselines/reference/classExpression4.js create mode 100644 tests/baselines/reference/classExpression4.symbols create mode 100644 tests/baselines/reference/classExpression4.types create mode 100644 tests/cases/conformance/classes/classExpressions/classExpression3.ts create mode 100644 tests/cases/conformance/classes/classExpressions/classExpression4.ts diff --git a/tests/baselines/reference/classExpression3.js b/tests/baselines/reference/classExpression3.js new file mode 100644 index 00000000000..ec9581eaf39 --- /dev/null +++ b/tests/baselines/reference/classExpression3.js @@ -0,0 +1,38 @@ +//// [classExpression3.ts] +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +let c = new C(); +c.a; +c.b; +c.c; + + +//// [classExpression3.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C = (function (_super) { + __extends(class_1, _super); + function class_1() { + _super.apply(this, arguments); + this.c = 3; + } + return class_1; +})((function (_super) { + __extends(class_2, _super); + function class_2() { + _super.apply(this, arguments); + this.b = 2; + } + return class_2; +})((function () { + function class_3() { + this.a = 1; + } + return class_3; +})())); +var c = new C(); +c.a; +c.b; +c.c; diff --git a/tests/baselines/reference/classExpression3.symbols b/tests/baselines/reference/classExpression3.symbols new file mode 100644 index 00000000000..bc1b263a000 --- /dev/null +++ b/tests/baselines/reference/classExpression3.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression3.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : Symbol(C, Decl(classExpression3.ts, 0, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpression3.ts, 0, 43)) +>b : Symbol((Anonymous class).b, Decl(classExpression3.ts, 0, 53)) +>c : Symbol((Anonymous class).c, Decl(classExpression3.ts, 0, 63)) + +let c = new C(); +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>C : Symbol(C, Decl(classExpression3.ts, 0, 3)) + +c.a; +>c.a : Symbol((Anonymous class).a, Decl(classExpression3.ts, 0, 43)) +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpression3.ts, 0, 43)) + +c.b; +>c.b : Symbol((Anonymous class).b, Decl(classExpression3.ts, 0, 53)) +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>b : Symbol((Anonymous class).b, Decl(classExpression3.ts, 0, 53)) + +c.c; +>c.c : Symbol((Anonymous class).c, Decl(classExpression3.ts, 0, 63)) +>c : Symbol(c, Decl(classExpression3.ts, 1, 3)) +>c : Symbol((Anonymous class).c, Decl(classExpression3.ts, 0, 63)) + diff --git a/tests/baselines/reference/classExpression3.types b/tests/baselines/reference/classExpression3.types new file mode 100644 index 00000000000..87423ecf0bd --- /dev/null +++ b/tests/baselines/reference/classExpression3.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression3.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : typeof (Anonymous class) +>class extends class extends class { a = 1 } { b = 2 } { c = 3 } : typeof (Anonymous class) +>class extends class { a = 1 } { b = 2 } : (Anonymous class) +>class { a = 1 } : (Anonymous class) +>a : number +>1 : number +>b : number +>2 : number +>c : number +>3 : number + +let c = new C(); +>c : (Anonymous class) +>new C() : (Anonymous class) +>C : typeof (Anonymous class) + +c.a; +>c.a : number +>c : (Anonymous class) +>a : number + +c.b; +>c.b : number +>c : (Anonymous class) +>b : number + +c.c; +>c.c : number +>c : (Anonymous class) +>c : number + diff --git a/tests/baselines/reference/classExpression4.js b/tests/baselines/reference/classExpression4.js new file mode 100644 index 00000000000..c2ead0474e2 --- /dev/null +++ b/tests/baselines/reference/classExpression4.js @@ -0,0 +1,19 @@ +//// [classExpression4.ts] +let C = class { + foo() { + return new C(); + } +}; +let x = (new C).foo(); + + +//// [classExpression4.js] +var C = (function () { + function class_1() { + } + class_1.prototype.foo = function () { + return new C(); + }; + return class_1; +})(); +var x = (new C).foo(); diff --git a/tests/baselines/reference/classExpression4.symbols b/tests/baselines/reference/classExpression4.symbols new file mode 100644 index 00000000000..4df5302cecc --- /dev/null +++ b/tests/baselines/reference/classExpression4.symbols @@ -0,0 +1,17 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression4.ts === +let C = class { +>C : Symbol(C, Decl(classExpression4.ts, 0, 3)) + + foo() { +>foo : Symbol((Anonymous class).foo, Decl(classExpression4.ts, 0, 15)) + + return new C(); +>C : Symbol(C, Decl(classExpression4.ts, 0, 3)) + } +}; +let x = (new C).foo(); +>x : Symbol(x, Decl(classExpression4.ts, 5, 3)) +>(new C).foo : Symbol((Anonymous class).foo, Decl(classExpression4.ts, 0, 15)) +>C : Symbol(C, Decl(classExpression4.ts, 0, 3)) +>foo : Symbol((Anonymous class).foo, Decl(classExpression4.ts, 0, 15)) + diff --git a/tests/baselines/reference/classExpression4.types b/tests/baselines/reference/classExpression4.types new file mode 100644 index 00000000000..066f169ae74 --- /dev/null +++ b/tests/baselines/reference/classExpression4.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/classes/classExpressions/classExpression4.ts === +let C = class { +>C : typeof (Anonymous class) +>class { foo() { return new C(); }} : typeof (Anonymous class) + + foo() { +>foo : () => (Anonymous class) + + return new C(); +>new C() : (Anonymous class) +>C : typeof (Anonymous class) + } +}; +let x = (new C).foo(); +>x : (Anonymous class) +>(new C).foo() : (Anonymous class) +>(new C).foo : () => (Anonymous class) +>(new C) : (Anonymous class) +>new C : (Anonymous class) +>C : typeof (Anonymous class) +>foo : () => (Anonymous class) + diff --git a/tests/cases/conformance/classes/classExpressions/classExpression3.ts b/tests/cases/conformance/classes/classExpressions/classExpression3.ts new file mode 100644 index 00000000000..4267429f759 --- /dev/null +++ b/tests/cases/conformance/classes/classExpressions/classExpression3.ts @@ -0,0 +1,5 @@ +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +let c = new C(); +c.a; +c.b; +c.c; diff --git a/tests/cases/conformance/classes/classExpressions/classExpression4.ts b/tests/cases/conformance/classes/classExpressions/classExpression4.ts new file mode 100644 index 00000000000..9365475fd87 --- /dev/null +++ b/tests/cases/conformance/classes/classExpressions/classExpression4.ts @@ -0,0 +1,6 @@ +let C = class { + foo() { + return new C(); + } +}; +let x = (new C).foo(); From 5e672b77918ecf0c76e47957f60ab570894e3984 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 12 Jun 2015 13:49:38 -0700 Subject: [PATCH 19/79] Don't log by default. On the managed side tracing is disabled by default anyways. By logging we still cause tons of allocations of strings on the managed side. These then cause expensive GCs which can pause editing. --- src/services/shims.ts | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/services/shims.ts b/src/services/shims.ts index 004393fb3b5..d6f9f7a968a 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -246,16 +246,22 @@ module ts { export class LanguageServiceShimHostAdapter implements LanguageServiceHost { private files: string[]; + private loggingEnabled = false; + private tracingEnabled = false; constructor(private shimHost: LanguageServiceShimHost) { } public log(s: string): void { - this.shimHost.log(s); + if (this.loggingEnabled) { + this.shimHost.log(s); + } } public trace(s: string): void { - this.shimHost.trace(s); + if (this.tracingEnabled) { + this.shimHost.trace(s); + } } public error(s: string): void { @@ -349,15 +355,15 @@ module ts { } } - function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, noPerfLogging: boolean): any { - if (!noPerfLogging) { + function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): any { + if (logPerformance) { logger.log(actionDescription); var start = Date.now(); } var result = action(); - if (!noPerfLogging) { + if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof (result) === "string") { @@ -372,9 +378,9 @@ module ts { return result; } - function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, noPerfLogging: boolean): string { + function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): string { try { - var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging); + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); return JSON.stringify({ result: result }); } catch (err) { @@ -413,6 +419,7 @@ module ts { class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim { private logger: Logger; + private logPerformance = false; constructor(factory: ShimFactory, private host: LanguageServiceShimHost, @@ -422,7 +429,7 @@ module ts { } public forwardJSONCall(actionDescription: string, action: () => any): string { - return forwardJSONCall(this.logger, actionDescription, action, /*noPerfLogging:*/ false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); } /// DISPOSE @@ -811,6 +818,7 @@ module ts { class ClassifierShimObject extends ShimBase implements ClassifierShim { public classifier: Classifier; + private logPerformance = false; constructor(factory: ShimFactory, private logger: Logger) { super(factory); @@ -820,7 +828,7 @@ module ts { public getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string { return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), - /*noPerfLogging:*/ true); + this.logPerformance); } /// COLORIZATION @@ -838,13 +846,14 @@ module ts { } class CoreServicesShimObject extends ShimBase implements CoreServicesShim { + private logPerformance = false; constructor(factory: ShimFactory, public logger: Logger, private host: CoreServicesShimHostAdapter) { super(factory); } private forwardJSONCall(actionDescription: string, action: () => any): any { - return forwardJSONCall(this.logger, actionDescription, action, /*noPerfLogging:*/ false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); } public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string { From 331b63df7d05c9476b6b9cae97a7a158eba303ca Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Fri, 19 Jun 2015 16:01:27 -0700 Subject: [PATCH 20/79] update LKG --- bin/tsc.js | 83 +++++++++++----- bin/tsserver.js | 134 ++++++++++++++++---------- bin/typescript.d.ts | 14 ++- bin/typescript.js | 182 ++++++++++++++++++++++++------------ bin/typescriptServices.d.ts | 14 ++- bin/typescriptServices.js | 182 ++++++++++++++++++++++++------------ 6 files changed, 415 insertions(+), 194 deletions(-) diff --git a/bin/tsc.js b/bin/tsc.js index e7a41e8aa7e..0aa82496955 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -31,6 +31,36 @@ var ts; /// var ts; (function (ts) { + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -7758,7 +7788,7 @@ var ts; token === 18) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { var name_3 = createMissingNode(65, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); } @@ -8162,7 +8192,7 @@ var ts; case 85: return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); default: - if (decorators) { + if (decorators || modifiers) { var node = createMissingNode(219, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; @@ -8238,7 +8268,7 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { @@ -8849,21 +8879,24 @@ var ts; if (!ts.isExternalModule(location)) break; case 206: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931)) { - if (result.flags & meaning || !(result.flags & 8388608 && getDeclarationOfAliasSymbol(result).kind === 218)) { - break loop; - } - result = undefined; - } - else if (location.kind === 228 || + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 228 || (location.kind === 206 && location.name.kind === 8)) { - result = getSymbolOfNode(location).exports["default"]; + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 && + ts.getDeclarationOfKind(moduleExports[name], 218)) { + break; + } + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + break loop; + } break; case 205: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { @@ -24450,10 +24483,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -24553,7 +24586,11 @@ var ts; collectExternalModuleInfo(node); ts.Debug.assert(!exportFunctionForFile); exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -24626,8 +24663,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -25201,7 +25238,6 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); var seenNoDefaultLib = options.noLib; var commonSourceDirectory; @@ -25209,6 +25245,7 @@ var ts; var noDiagnosticsTypeChecker; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!seenNoDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -25264,8 +25301,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -25361,16 +25397,16 @@ var ts; } function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -25378,9 +25414,10 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); @@ -25396,7 +25433,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { diff --git a/bin/tsserver.js b/bin/tsserver.js index 8536491127d..040eac2ef75 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -31,6 +31,36 @@ var ts; /// var ts; (function (ts) { + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -7635,7 +7665,7 @@ var ts; token === 18) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { var name_3 = createMissingNode(65, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); } @@ -8039,7 +8069,7 @@ var ts; case 85: return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); default: - if (decorators) { + if (decorators || modifiers) { var node = createMissingNode(219, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; @@ -8115,7 +8145,7 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { @@ -9239,21 +9269,24 @@ var ts; if (!ts.isExternalModule(location)) break; case 206: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931)) { - if (result.flags & meaning || !(result.flags & 8388608 && getDeclarationOfAliasSymbol(result).kind === 218)) { - break loop; - } - result = undefined; - } - else if (location.kind === 228 || + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 228 || (location.kind === 206 && location.name.kind === 8)) { - result = getSymbolOfNode(location).exports["default"]; + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 && + ts.getDeclarationOfKind(moduleExports[name], 218)) { + break; + } + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + break loop; + } break; case 205: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { @@ -24840,10 +24873,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -24943,7 +24976,11 @@ var ts; collectExternalModuleInfo(node); ts.Debug.assert(!exportFunctionForFile); exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -25016,8 +25053,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -25591,7 +25628,6 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); var seenNoDefaultLib = options.noLib; var commonSourceDirectory; @@ -25599,6 +25635,7 @@ var ts; var noDiagnosticsTypeChecker; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!seenNoDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -25654,8 +25691,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -25751,16 +25787,16 @@ var ts; } function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -25768,9 +25804,10 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); @@ -25786,7 +25823,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -31308,8 +31345,7 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; - this.fileNameToEntry = {}; + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); var rootFileNames = host.getScriptFileNames(); for (var _i = 0; _i < rootFileNames.length; _i++) { var fileName = rootFileNames[_i]; @@ -31320,9 +31356,6 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.normalizeFileName = function (fileName) { - return this.getCanonicalFileName(ts.normalizeSlashes(fileName)); - }; HostCache.prototype.createEntry = function (fileName) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -31333,13 +31366,14 @@ var ts; scriptSnapshot: scriptSnapshot }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; }; HostCache.prototype.getEntry = function (fileName) { - return ts.lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); }; HostCache.prototype.contains = function (fileName) { - return ts.hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); }; HostCache.prototype.getOrCreateEntry = function (fileName) { if (this.contains(fileName)) { @@ -31348,12 +31382,10 @@ var ts; return this.createEntry(fileName); }; HostCache.prototype.getRootFileNames = function () { - var _this = this; var fileNames = []; - ts.forEachKey(this.fileNameToEntry, function (key) { - var entry = _this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); } }); return fileNames; @@ -31400,7 +31432,7 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - function transpile(input, compilerOptions, fileName, diagnostics) { + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var options = compilerOptions ? ts.clone(compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; options.allowNonTsExtensions = true; @@ -31408,6 +31440,9 @@ var ts; options.noResolve = true; var inputFileName = fileName || "module.ts"; var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (moduleName) { + sourceFile.moduleName = moduleName; + } if (diagnostics && sourceFile.parseDiagnostics) { diagnostics.push.apply(diagnostics, sourceFile.parseDiagnostics); } @@ -31474,8 +31509,14 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry() { + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + function createDocumentRegistry(useCaseSensitiveFileNames) { var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { return "_" + settings.target; } @@ -31483,7 +31524,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); } return bucket; } @@ -31492,7 +31533,7 @@ var ts; var entries = ts.lookUp(buckets, name); var sourceFiles = []; for (var i in entries) { - var entry = entries[i]; + var entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -31515,15 +31556,16 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { if (entry.sourceFile.version !== version) { @@ -31538,11 +31580,11 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } return { @@ -31887,9 +31929,7 @@ var ts; host.log(message); } } - function getCanonicalFileName(fileName) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { fileName = ts.normalizeSlashes(fileName); var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index 50f5c1ade22..11169b6fa28 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -17,6 +17,13 @@ declare module "typescript" { interface Map { [index: string]: T; } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + } interface TextRange { pos: number; end: number; @@ -748,7 +755,7 @@ declare module "typescript" { path: string; name: string; }[]; - amdModuleName: string; + moduleName: string; referencedFiles: FileReference[]; hasNoDefaultLib: boolean; languageVersion: ScriptTarget; @@ -1391,6 +1398,7 @@ declare module "typescript" { log?(s: string): void; trace?(s: string): void; error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1847,11 +1855,11 @@ declare module "typescript" { isCancellationRequested(): boolean; throwIfCancellationRequested(): void; } - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; diff --git a/bin/typescript.js b/bin/typescript.js index b393f2ee881..c2f23126ea8 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -706,6 +706,36 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -9703,7 +9733,7 @@ var ts; token === 18 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { // treat this as a property declaration with a missing name. var name_3 = createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); @@ -10161,7 +10191,7 @@ var ts; case 85 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); default: - if (decorators) { + if (decorators || modifiers) { // We reached this point because we encountered an AtToken and assumed a declaration would // follow. For recovery and error reporting purposes, return an incomplete declaration. var node = createMissingNode(219 /* MissingDeclaration */, true, ts.Diagnostics.Declaration_expected); @@ -10242,7 +10272,7 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { @@ -11085,21 +11115,35 @@ var ts; if (!ts.isExternalModule(location)) break; case 206 /* ModuleDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931 /* ModuleMember */)) { - if (result.flags & meaning || !(result.flags & 8388608 /* Alias */ && getDeclarationOfAliasSymbol(result).kind === 218 /* ExportSpecifier */)) { - break loop; - } - result = undefined; - } - else if (location.kind === 228 /* SourceFile */ || + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 228 /* SourceFile */ || (location.kind === 206 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { - result = getSymbolOfNode(location).exports["default"]; + // It's an external module. Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. Therefore, + // if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 /* Alias */ && + ts.getDeclarationOfKind(moduleExports[name], 218 /* ExportSpecifier */)) { + break; + } + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + break loop; + } break; case 205 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { @@ -28972,10 +29016,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); // return + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -29108,7 +29152,11 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -29188,8 +29236,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -29810,7 +29858,6 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); var seenNoDefaultLib = options.noLib; var commonSourceDirectory; @@ -29818,6 +29865,7 @@ var ts; var noDiagnosticsTypeChecker; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!seenNoDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -29883,8 +29931,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -29982,18 +30029,18 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { // We've already looked for this file, use cached result return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } // We haven't looked for this file, do so now and cache result - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -30001,10 +30048,11 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; // Set the source file for normalized absolute path - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); @@ -30020,7 +30068,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -36625,9 +36673,8 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = {}; + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0; _i < rootFileNames.length; _i++) { @@ -36640,9 +36687,6 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.normalizeFileName = function (fileName) { - return this.getCanonicalFileName(ts.normalizeSlashes(fileName)); - }; HostCache.prototype.createEntry = function (fileName) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -36653,13 +36697,14 @@ var ts; scriptSnapshot: scriptSnapshot }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; }; HostCache.prototype.getEntry = function (fileName) { - return ts.lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); }; HostCache.prototype.contains = function (fileName) { - return ts.hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); }; HostCache.prototype.getOrCreateEntry = function (fileName) { if (this.contains(fileName)) { @@ -36668,12 +36713,10 @@ var ts; return this.createEntry(fileName); }; HostCache.prototype.getRootFileNames = function () { - var _this = this; var fileNames = []; - ts.forEachKey(this.fileNameToEntry, function (key) { - var entry = _this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); } }); return fileNames; @@ -36733,7 +36776,7 @@ var ts; * - noLib = true * - noResolve = true */ - function transpile(input, compilerOptions, fileName, diagnostics) { + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var options = compilerOptions ? ts.clone(compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; // Filename can be non-ts file. @@ -36747,6 +36790,9 @@ var ts; // Parse var inputFileName = fileName || "module.ts"; var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (moduleName) { + sourceFile.moduleName = moduleName; + } // Store syntactic diagnostics if (diagnostics && sourceFile.parseDiagnostics) { diagnostics.push.apply(diagnostics, sourceFile.parseDiagnostics); @@ -36829,10 +36875,16 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry() { + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + function createDocumentRegistry(useCaseSensitiveFileNames) { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString() } @@ -36840,7 +36892,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); } return bucket; } @@ -36849,7 +36901,7 @@ var ts; var entries = ts.lookUp(buckets, name); var sourceFiles = []; for (var i in entries) { - var entry = entries[i]; + var entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -36872,16 +36924,17 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -36904,11 +36957,11 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } return { @@ -37305,9 +37358,7 @@ var ts; host.log(message); } } - function getCanonicalFileName(fileName) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { fileName = ts.normalizeSlashes(fileName); var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); @@ -41901,12 +41952,18 @@ var ts; var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; } LanguageServiceShimHostAdapter.prototype.log = function (s) { - this.shimHost.log(s); + if (this.loggingEnabled) { + this.shimHost.log(s); + } }; LanguageServiceShimHostAdapter.prototype.trace = function (s) { - this.shimHost.trace(s); + if (this.tracingEnabled) { + this.shimHost.trace(s); + } }; LanguageServiceShimHostAdapter.prototype.error = function (s) { this.shimHost.error(s); @@ -41918,6 +41975,9 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { var settingsJson = this.shimHost.getCompilationSettings(); if (settingsJson == null || settingsJson == "") { @@ -41985,13 +42045,13 @@ var ts; return CoreServicesShimHostAdapter; })(); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; - function simpleForwardCall(logger, actionDescription, action, noPerfLogging) { - if (!noPerfLogging) { + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + if (logPerformance) { logger.log(actionDescription); var start = Date.now(); } var result = action(); - if (!noPerfLogging) { + if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof (result) === "string") { @@ -42004,9 +42064,9 @@ var ts; } return result; } - function forwardJSONCall(logger, actionDescription, action, noPerfLogging) { + function forwardJSONCall(logger, actionDescription, action, logPerformance) { try { - var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging); + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); return JSON.stringify({ result: result }); } catch (err) { @@ -42048,10 +42108,11 @@ var ts; _super.call(this, factory); this.host = host; this.languageService = languageService; + this.logPerformance = false; this.logger = this.host; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; /// DISPOSE /** @@ -42358,12 +42419,12 @@ var ts; function ClassifierShimObject(factory, logger) { _super.call(this, factory); this.logger = logger; + this.logPerformance = false; this.classifier = ts.createClassifier(); } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; - return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, - /*noPerfLogging:*/ true); + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { @@ -42385,9 +42446,10 @@ var ts; _super.call(this, factory); this.logger = logger; this.host = host; + this.logPerformance = false; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { @@ -42444,7 +42506,6 @@ var ts; var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); } /* * Returns script API version. @@ -42454,6 +42515,9 @@ var ts; }; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); return new LanguageServiceShimObject(this, host, languageService); diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index 558504fcede..ae49ab102ad 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -17,6 +17,13 @@ declare module ts { interface Map { [index: string]: T; } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + } interface TextRange { pos: number; end: number; @@ -748,7 +755,7 @@ declare module ts { path: string; name: string; }[]; - amdModuleName: string; + moduleName: string; referencedFiles: FileReference[]; hasNoDefaultLib: boolean; languageVersion: ScriptTarget; @@ -1391,6 +1398,7 @@ declare module ts { log?(s: string): void; trace?(s: string): void; error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1847,11 +1855,11 @@ declare module ts { isCancellationRequested(): boolean; throwIfCancellationRequested(): void; } - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index b393f2ee881..c2f23126ea8 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -706,6 +706,36 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -9703,7 +9733,7 @@ var ts; token === 18 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { // treat this as a property declaration with a missing name. var name_3 = createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); @@ -10161,7 +10191,7 @@ var ts; case 85 /* ImportKeyword */: return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); default: - if (decorators) { + if (decorators || modifiers) { // We reached this point because we encountered an AtToken and assumed a declaration would // follow. For recovery and error reporting purposes, return an incomplete declaration. var node = createMissingNode(219 /* MissingDeclaration */, true, ts.Diagnostics.Declaration_expected); @@ -10242,7 +10272,7 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { @@ -11085,21 +11115,35 @@ var ts; if (!ts.isExternalModule(location)) break; case 206 /* ModuleDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931 /* ModuleMember */)) { - if (result.flags & meaning || !(result.flags & 8388608 /* Alias */ && getDeclarationOfAliasSymbol(result).kind === 218 /* ExportSpecifier */)) { - break loop; - } - result = undefined; - } - else if (location.kind === 228 /* SourceFile */ || + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 228 /* SourceFile */ || (location.kind === 206 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { - result = getSymbolOfNode(location).exports["default"]; + // It's an external module. Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. Therefore, + // if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 /* Alias */ && + ts.getDeclarationOfKind(moduleExports[name], 218 /* ExportSpecifier */)) { + break; + } + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + break loop; + } break; case 205 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { @@ -28972,10 +29016,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); // return + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -29108,7 +29152,11 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -29188,8 +29236,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -29810,7 +29858,6 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); var seenNoDefaultLib = options.noLib; var commonSourceDirectory; @@ -29818,6 +29865,7 @@ var ts; var noDiagnosticsTypeChecker; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!seenNoDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -29883,8 +29931,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -29982,18 +30029,18 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { // We've already looked for this file, use cached result return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } // We haven't looked for this file, do so now and cache result - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -30001,10 +30048,11 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; // Set the source file for normalized absolute path - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); @@ -30020,7 +30068,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -36625,9 +36673,8 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = {}; + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0; _i < rootFileNames.length; _i++) { @@ -36640,9 +36687,6 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.normalizeFileName = function (fileName) { - return this.getCanonicalFileName(ts.normalizeSlashes(fileName)); - }; HostCache.prototype.createEntry = function (fileName) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -36653,13 +36697,14 @@ var ts; scriptSnapshot: scriptSnapshot }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; }; HostCache.prototype.getEntry = function (fileName) { - return ts.lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); }; HostCache.prototype.contains = function (fileName) { - return ts.hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); }; HostCache.prototype.getOrCreateEntry = function (fileName) { if (this.contains(fileName)) { @@ -36668,12 +36713,10 @@ var ts; return this.createEntry(fileName); }; HostCache.prototype.getRootFileNames = function () { - var _this = this; var fileNames = []; - ts.forEachKey(this.fileNameToEntry, function (key) { - var entry = _this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); } }); return fileNames; @@ -36733,7 +36776,7 @@ var ts; * - noLib = true * - noResolve = true */ - function transpile(input, compilerOptions, fileName, diagnostics) { + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var options = compilerOptions ? ts.clone(compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; // Filename can be non-ts file. @@ -36747,6 +36790,9 @@ var ts; // Parse var inputFileName = fileName || "module.ts"; var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (moduleName) { + sourceFile.moduleName = moduleName; + } // Store syntactic diagnostics if (diagnostics && sourceFile.parseDiagnostics) { diagnostics.push.apply(diagnostics, sourceFile.parseDiagnostics); @@ -36829,10 +36875,16 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry() { + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + function createDocumentRegistry(useCaseSensitiveFileNames) { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString() } @@ -36840,7 +36892,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); } return bucket; } @@ -36849,7 +36901,7 @@ var ts; var entries = ts.lookUp(buckets, name); var sourceFiles = []; for (var i in entries) { - var entry = entries[i]; + var entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -36872,16 +36924,17 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -36904,11 +36957,11 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } return { @@ -37305,9 +37358,7 @@ var ts; host.log(message); } } - function getCanonicalFileName(fileName) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { fileName = ts.normalizeSlashes(fileName); var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); @@ -41901,12 +41952,18 @@ var ts; var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; } LanguageServiceShimHostAdapter.prototype.log = function (s) { - this.shimHost.log(s); + if (this.loggingEnabled) { + this.shimHost.log(s); + } }; LanguageServiceShimHostAdapter.prototype.trace = function (s) { - this.shimHost.trace(s); + if (this.tracingEnabled) { + this.shimHost.trace(s); + } }; LanguageServiceShimHostAdapter.prototype.error = function (s) { this.shimHost.error(s); @@ -41918,6 +41975,9 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { var settingsJson = this.shimHost.getCompilationSettings(); if (settingsJson == null || settingsJson == "") { @@ -41985,13 +42045,13 @@ var ts; return CoreServicesShimHostAdapter; })(); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; - function simpleForwardCall(logger, actionDescription, action, noPerfLogging) { - if (!noPerfLogging) { + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + if (logPerformance) { logger.log(actionDescription); var start = Date.now(); } var result = action(); - if (!noPerfLogging) { + if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof (result) === "string") { @@ -42004,9 +42064,9 @@ var ts; } return result; } - function forwardJSONCall(logger, actionDescription, action, noPerfLogging) { + function forwardJSONCall(logger, actionDescription, action, logPerformance) { try { - var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging); + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); return JSON.stringify({ result: result }); } catch (err) { @@ -42048,10 +42108,11 @@ var ts; _super.call(this, factory); this.host = host; this.languageService = languageService; + this.logPerformance = false; this.logger = this.host; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; /// DISPOSE /** @@ -42358,12 +42419,12 @@ var ts; function ClassifierShimObject(factory, logger) { _super.call(this, factory); this.logger = logger; + this.logPerformance = false; this.classifier = ts.createClassifier(); } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; - return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, - /*noPerfLogging:*/ true); + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { @@ -42385,9 +42446,10 @@ var ts; _super.call(this, factory); this.logger = logger; this.host = host; + this.logPerformance = false; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { @@ -42444,7 +42506,6 @@ var ts; var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); } /* * Returns script API version. @@ -42454,6 +42515,9 @@ var ts; }; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); return new LanguageServiceShimObject(this, host, languageService); From 138970f35fc3d410761d3fbe449c813b4acb1c3c Mon Sep 17 00:00:00 2001 From: jbondc Date: Tue, 16 Jun 2015 22:00:42 -0400 Subject: [PATCH 21/79] Fixes #2632 (invoking methods on numbers) --- .../diagnosticInformationMap.generated.ts | 1 + src/compiler/diagnosticMessages.json | 4 ++ src/compiler/parser.ts | 41 ++++++++++++++----- src/compiler/types.ts | 3 +- tests/baselines/reference/numLit.errors.txt | 27 ++++++++---- tests/baselines/reference/numLit.js | 28 +++++++++++-- tests/cases/compiler/numLit.ts | 15 ++++++- 7 files changed, 93 insertions(+), 26 deletions(-) diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 09b009711fe..46976813120 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -569,5 +569,6 @@ namespace ts { decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, + Numeric_literal_0_cannot_be_followed_by_an_expression: { code: 9004, category: DiagnosticCategory.Error, key: "Numeric literal {0} cannot be followed by an expression." }, }; } \ No newline at end of file diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index fee46a84c1e..4b705396fe5 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2268,5 +2268,9 @@ "'class' expressions are not currently supported.": { "category": "Error", "code": 9003 + }, + "Numeric literal {0} cannot be followed by an expression.": { + "category": "Error", + "code": 9004 } } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index fbb3dad5037..55fdcd91d34 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -100,6 +100,8 @@ namespace ts { visitNode(cbNode, (node).type) || visitNode(cbNode, (node).equalsGreaterThanToken) || visitNode(cbNode, (node).body); + case SyntaxKind.NumericLiteral: + return visitNode(cbNode, (node).invalidDotExpression); case SyntaxKind.TypeReference: return visitNode(cbNode, (node).typeName) || visitNodes(cbNodes, (node).typeArguments); @@ -1830,20 +1832,37 @@ namespace ts { } let tokenPos = scanner.getTokenPos(); + let nextCharCode: number; + nextToken(); finishNode(node); - // Octal literals are not allowed in strict mode or ES5 - // Note that theoretically the following condition would hold true literals like 009, - // which is not octal.But because of how the scanner separates the tokens, we would - // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. - // We also do not need to check for negatives because any prefix operator would be part of a - // parent unary expression. - if (node.kind === SyntaxKind.NumericLiteral - && sourceText.charCodeAt(tokenPos) === CharacterCodes._0 - && isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - - node.flags |= NodeFlags.OctalLiteral; + if (node.kind === SyntaxKind.NumericLiteral) { + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (sourceText.charCodeAt(tokenPos) === CharacterCodes._0 && isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { + node.flags |= NodeFlags.OctalLiteral; + } + else if (token === SyntaxKind.DotToken) { + // Issue #2632 Keep space for 3 .toString() + if (isWhiteSpace(sourceText.charCodeAt(node.end))) { + node.end++; + scanner.setTextPos(node.end + 1); + } + } + else if (token === SyntaxKind.Identifier && sourceText.charCodeAt(node.end-1) === CharacterCodes.dot) { + nextCharCode = sourceText.charCodeAt(node.end); + if (!isWhiteSpace(nextCharCode) && !isLineBreak(nextCharCode)) { + // Eat up an invalid expression following '1.' e.g. 1.something() + node.invalidDotExpression = parseLeftHandSideExpressionOrHigher(); + parseErrorAtPosition(node.end, node.invalidDotExpression.end - node.end, Diagnostics.Numeric_literal_0_cannot_be_followed_by_an_expression, "'" + sourceText.substring(tokenPos, node.end) + "'"); + node.end = node.invalidDotExpression.end; + } + } } return node; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f9a2fa3b7b4..187cead4842 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -737,6 +737,7 @@ namespace ts { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; + invalidDotExpression?: LeftHandSideExpression; // 1.toString() we attach the node but never emit it } export interface TemplateExpression extends PrimaryExpression { @@ -1881,7 +1882,7 @@ namespace ts { CarriageReturnLineFeed = 0, LineFeed = 1, } - + export interface LineAndCharacter { line: number; /* diff --git a/tests/baselines/reference/numLit.errors.txt b/tests/baselines/reference/numLit.errors.txt index 98b84791e35..66f11141c15 100644 --- a/tests/baselines/reference/numLit.errors.txt +++ b/tests/baselines/reference/numLit.errors.txt @@ -1,13 +1,24 @@ -tests/cases/compiler/numLit.ts(3,3): error TS1005: ';' expected. -tests/cases/compiler/numLit.ts(3,3): error TS2304: Cannot find name 'toString'. +tests/cases/compiler/numLit.ts(3,3): error TS9004: Numeric literal '1.' cannot be followed by an expression. +tests/cases/compiler/numLit.ts(9,15): error TS9004: Numeric literal '2.' cannot be followed by an expression. ==== tests/cases/compiler/numLit.ts (2 errors) ==== 1..toString(); 1.0.toString(); - 1.toString(); - ~~~~~~~~ -!!! error TS1005: ';' expected. - ~~~~~~~~ -!!! error TS2304: Cannot find name 'toString'. - 1.+2.0 + 3. ; \ No newline at end of file + 1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. + ~~~~~~~~~~ +!!! error TS9004: Numeric literal '1.' cannot be followed by an expression. + 1.+2.0 + 3. ; + + // Preserve whitespace where important for JS compatibility + var i: number = 1; + var test1 = i.toString(); + var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. + ~~~~~~~~~~ +!!! error TS9004: Numeric literal '2.' cannot be followed by an expression. + var test3 = 3 .toString(); // preserve whitepace + var test4 = 3.['toString'](); + var test5 = 3 + .toString(); // preserve whitepace + var test6 = new Number(4).toString(); + var test7 = 3. + 3. \ No newline at end of file diff --git a/tests/baselines/reference/numLit.js b/tests/baselines/reference/numLit.js index aaec91cde5d..a6e33a9a3c1 100644 --- a/tests/baselines/reference/numLit.js +++ b/tests/baselines/reference/numLit.js @@ -1,12 +1,32 @@ //// [numLit.ts] 1..toString(); 1.0.toString(); -1.toString(); -1.+2.0 + 3. ; +1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. +1.+2.0 + 3. ; + +// Preserve whitespace where important for JS compatibility +var i: number = 1; +var test1 = i.toString(); +var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. +var test3 = 3 .toString(); // preserve whitepace +var test4 = 3.['toString'](); +var test5 = 3 +.toString(); // preserve whitepace +var test6 = new Number(4).toString(); +var test7 = 3. + 3. //// [numLit.js] 1..toString(); 1.0.toString(); -1.; -toString(); +1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. 1. + 2.0 + 3.; +// Preserve whitespace where important for JS compatibility +var i = 1; +var test1 = i.toString(); +var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. +var test3 = 3 .toString(); // preserve whitepace +var test4 = 3.['toString'](); +var test5 = 3 + .toString(); // preserve whitepace +var test6 = new Number(4).toString(); +var test7 = 3. + 3.; diff --git a/tests/cases/compiler/numLit.ts b/tests/cases/compiler/numLit.ts index 01e19e7c8fb..d9d42f9018c 100644 --- a/tests/cases/compiler/numLit.ts +++ b/tests/cases/compiler/numLit.ts @@ -1,4 +1,15 @@ 1..toString(); 1.0.toString(); -1.toString(); -1.+2.0 + 3. ; \ No newline at end of file +1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. +1.+2.0 + 3. ; + +// Preserve whitespace where important for JS compatibility +var i: number = 1; +var test1 = i.toString(); +var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. +var test3 = 3 .toString(); // preserve whitepace +var test4 = 3.['toString'](); +var test5 = 3 +.toString(); // preserve whitepace +var test6 = new Number(4).toString(); +var test7 = 3. + 3. \ No newline at end of file From db316b94d81d7987edeecb570aef4202f17295ea Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 14:41:35 -0700 Subject: [PATCH 22/79] p -> parameter --- src/compiler/emitter.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 3fbe640254f..9d436870297 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -3135,33 +3135,33 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { function emitDefaultValueAssignments(node: FunctionLikeDeclaration) { if (languageVersion < ScriptTarget.ES6) { let tempIndex = 0; - forEach(node.parameters, p => { + forEach(node.parameters, parameter => { // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. - if (p.dotDotDotToken) { + if (parameter.dotDotDotToken) { return; } - if (isBindingPattern(p.name)) { + if (isBindingPattern(parameter.name)) { writeLine(); write("var "); - emitDestructuring(p, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); write(";"); tempIndex++; } - else if (p.initializer) { + else if (parameter.initializer) { writeLine(); - emitStart(p); + emitStart(parameter); write("if ("); - emitNodeWithoutSourceMap(p.name); + emitNodeWithoutSourceMap(parameter.name); write(" === void 0)"); - emitEnd(p); + emitEnd(parameter); write(" { "); - emitStart(p); - emitNodeWithoutSourceMap(p.name); + emitStart(parameter); + emitNodeWithoutSourceMap(parameter.name); write(" = "); - emitNodeWithoutSourceMap(p.initializer); - emitEnd(p); + emitNodeWithoutSourceMap(parameter.initializer); + emitEnd(parameter); write("; }"); } }); From c1d2f60d3afb7cfd98369111195fd93ca9a1f3c3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 15:07:49 -0700 Subject: [PATCH 23/79] Added tests. --- .../es6/destructuring/emptyArrayBindingPatternParameter01.ts | 5 +++++ .../es6/destructuring/emptyArrayBindingPatternParameter02.ts | 5 +++++ .../es6/destructuring/emptyArrayBindingPatternParameter03.ts | 5 +++++ .../destructuring/emptyObjectBindingPatternParameter01.ts | 5 +++++ .../destructuring/emptyObjectBindingPatternParameter02.ts | 5 +++++ .../destructuring/emptyObjectBindingPatternParameter03.ts | 5 +++++ 6 files changed, 30 insertions(+) create mode 100644 tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter01.ts create mode 100644 tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts create mode 100644 tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts create mode 100644 tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts create mode 100644 tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts create mode 100644 tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts diff --git a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter01.ts b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter01.ts new file mode 100644 index 00000000000..0dea1fe795c --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter01.ts @@ -0,0 +1,5 @@ + + +function f([]) { + var x, y, z; +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts new file mode 100644 index 00000000000..aa945ed3bca --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts @@ -0,0 +1,5 @@ + + +function f(a, []) { + var x, y, z; +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts new file mode 100644 index 00000000000..aa945ed3bca --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts @@ -0,0 +1,5 @@ + + +function f(a, []) { + var x, y, z; +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts new file mode 100644 index 00000000000..aa6e4f265be --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts @@ -0,0 +1,5 @@ + + +function f({}) { + var x, y, z; +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts new file mode 100644 index 00000000000..671d69beb2b --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts @@ -0,0 +1,5 @@ + + +function f(a, {}) { + var x, y, z; +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts new file mode 100644 index 00000000000..4639b0b2042 --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts @@ -0,0 +1,5 @@ + + +function f({}, a) { + var x, y, z; +} \ No newline at end of file From 82f7f7d8e20f455d7686ebbc9badf479cead39b6 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 15:22:12 -0700 Subject: [PATCH 24/79] Accepted baselines. --- .../reference/emptyArrayBindingPatternParameter01.js | 12 ++++++++++++ .../emptyArrayBindingPatternParameter01.symbols | 11 +++++++++++ .../emptyArrayBindingPatternParameter01.types | 11 +++++++++++ .../reference/emptyArrayBindingPatternParameter02.js | 12 ++++++++++++ .../emptyArrayBindingPatternParameter02.symbols | 12 ++++++++++++ .../emptyArrayBindingPatternParameter02.types | 12 ++++++++++++ .../reference/emptyArrayBindingPatternParameter03.js | 12 ++++++++++++ .../emptyArrayBindingPatternParameter03.symbols | 12 ++++++++++++ .../emptyArrayBindingPatternParameter03.types | 12 ++++++++++++ .../emptyObjectBindingPatternParameter01.js | 12 ++++++++++++ .../emptyObjectBindingPatternParameter01.symbols | 11 +++++++++++ .../emptyObjectBindingPatternParameter01.types | 11 +++++++++++ .../emptyObjectBindingPatternParameter02.js | 12 ++++++++++++ .../emptyObjectBindingPatternParameter02.symbols | 12 ++++++++++++ .../emptyObjectBindingPatternParameter02.types | 12 ++++++++++++ .../emptyObjectBindingPatternParameter03.js | 12 ++++++++++++ .../emptyObjectBindingPatternParameter03.symbols | 12 ++++++++++++ .../emptyObjectBindingPatternParameter03.types | 12 ++++++++++++ 18 files changed, 212 insertions(+) create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter01.js create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter01.symbols create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter01.types create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter02.js create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter02.types create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter03.js create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter03.types create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter01.js create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter01.types create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter02.js create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter02.types create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter03.js create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter03.types diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter01.js b/tests/baselines/reference/emptyArrayBindingPatternParameter01.js new file mode 100644 index 00000000000..b074024ed94 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter01.js @@ -0,0 +1,12 @@ +//// [emptyArrayBindingPatternParameter01.ts] + + +function f([]) { + var x, y, z; +} + +//// [emptyArrayBindingPatternParameter01.js] +function f(_a) { + var ; + var x, y, z; +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter01.symbols b/tests/baselines/reference/emptyArrayBindingPatternParameter01.symbols new file mode 100644 index 00000000000..3207ca97dec --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter01.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter01.ts === + + +function f([]) { +>f : Symbol(f, Decl(emptyArrayBindingPatternParameter01.ts, 0, 0)) + + var x, y, z; +>x : Symbol(x, Decl(emptyArrayBindingPatternParameter01.ts, 3, 4)) +>y : Symbol(y, Decl(emptyArrayBindingPatternParameter01.ts, 3, 7)) +>z : Symbol(z, Decl(emptyArrayBindingPatternParameter01.ts, 3, 10)) +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter01.types b/tests/baselines/reference/emptyArrayBindingPatternParameter01.types new file mode 100644 index 00000000000..e93394b7371 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter01.types @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter01.ts === + + +function f([]) { +>f : ([]: any[]) => void + + var x, y, z; +>x : any +>y : any +>z : any +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.js b/tests/baselines/reference/emptyArrayBindingPatternParameter02.js new file mode 100644 index 00000000000..aed9e567ee7 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.js @@ -0,0 +1,12 @@ +//// [emptyArrayBindingPatternParameter02.ts] + + +function f(a, []) { + var x, y, z; +} + +//// [emptyArrayBindingPatternParameter02.js] +function f(a, _a) { + var ; + var x, y, z; +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols b/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols new file mode 100644 index 00000000000..e189bc41def --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts === + + +function f(a, []) { +>f : Symbol(f, Decl(emptyArrayBindingPatternParameter02.ts, 0, 0)) +>a : Symbol(a, Decl(emptyArrayBindingPatternParameter02.ts, 2, 11)) + + var x, y, z; +>x : Symbol(x, Decl(emptyArrayBindingPatternParameter02.ts, 3, 4)) +>y : Symbol(y, Decl(emptyArrayBindingPatternParameter02.ts, 3, 7)) +>z : Symbol(z, Decl(emptyArrayBindingPatternParameter02.ts, 3, 10)) +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.types b/tests/baselines/reference/emptyArrayBindingPatternParameter02.types new file mode 100644 index 00000000000..12657203f90 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.types @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts === + + +function f(a, []) { +>f : (a: any, []: any[]) => void +>a : any + + var x, y, z; +>x : any +>y : any +>z : any +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.js b/tests/baselines/reference/emptyArrayBindingPatternParameter03.js new file mode 100644 index 00000000000..9fb9cc6202e --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.js @@ -0,0 +1,12 @@ +//// [emptyArrayBindingPatternParameter03.ts] + + +function f(a, []) { + var x, y, z; +} + +//// [emptyArrayBindingPatternParameter03.js] +function f(a, _a) { + var ; + var x, y, z; +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols b/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols new file mode 100644 index 00000000000..a236a642807 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts === + + +function f(a, []) { +>f : Symbol(f, Decl(emptyArrayBindingPatternParameter03.ts, 0, 0)) +>a : Symbol(a, Decl(emptyArrayBindingPatternParameter03.ts, 2, 11)) + + var x, y, z; +>x : Symbol(x, Decl(emptyArrayBindingPatternParameter03.ts, 3, 4)) +>y : Symbol(y, Decl(emptyArrayBindingPatternParameter03.ts, 3, 7)) +>z : Symbol(z, Decl(emptyArrayBindingPatternParameter03.ts, 3, 10)) +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.types b/tests/baselines/reference/emptyArrayBindingPatternParameter03.types new file mode 100644 index 00000000000..d1cc85c462a --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.types @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts === + + +function f(a, []) { +>f : (a: any, []: any[]) => void +>a : any + + var x, y, z; +>x : any +>y : any +>z : any +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.js b/tests/baselines/reference/emptyObjectBindingPatternParameter01.js new file mode 100644 index 00000000000..9dd0e018561 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.js @@ -0,0 +1,12 @@ +//// [emptyObjectBindingPatternParameter01.ts] + + +function f({}) { + var x, y, z; +} + +//// [emptyObjectBindingPatternParameter01.js] +function f(_a) { + var ; + var x, y, z; +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols new file mode 100644 index 00000000000..701482c1355 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts === + + +function f({}) { +>f : Symbol(f, Decl(emptyObjectBindingPatternParameter01.ts, 0, 0)) + + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter01.ts, 3, 4)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter01.ts, 3, 7)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter01.ts, 3, 10)) +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.types b/tests/baselines/reference/emptyObjectBindingPatternParameter01.types new file mode 100644 index 00000000000..90b351e00dc --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.types @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts === + + +function f({}) { +>f : ({}: {}) => void + + var x, y, z; +>x : any +>y : any +>z : any +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.js b/tests/baselines/reference/emptyObjectBindingPatternParameter02.js new file mode 100644 index 00000000000..d1ad19ffb30 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.js @@ -0,0 +1,12 @@ +//// [emptyObjectBindingPatternParameter02.ts] + + +function f(a, {}) { + var x, y, z; +} + +//// [emptyObjectBindingPatternParameter02.js] +function f(a, _a) { + var ; + var x, y, z; +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols new file mode 100644 index 00000000000..7e58c6bae2e --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts === + + +function f(a, {}) { +>f : Symbol(f, Decl(emptyObjectBindingPatternParameter02.ts, 0, 0)) +>a : Symbol(a, Decl(emptyObjectBindingPatternParameter02.ts, 2, 11)) + + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter02.ts, 3, 4)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter02.ts, 3, 7)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter02.ts, 3, 10)) +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.types b/tests/baselines/reference/emptyObjectBindingPatternParameter02.types new file mode 100644 index 00000000000..67969e069be --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.types @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts === + + +function f(a, {}) { +>f : (a: any, {}: {}) => void +>a : any + + var x, y, z; +>x : any +>y : any +>z : any +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.js b/tests/baselines/reference/emptyObjectBindingPatternParameter03.js new file mode 100644 index 00000000000..efbdd5b04ea --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.js @@ -0,0 +1,12 @@ +//// [emptyObjectBindingPatternParameter03.ts] + + +function f({}, a) { + var x, y, z; +} + +//// [emptyObjectBindingPatternParameter03.js] +function f(_a, a) { + var ; + var x, y, z; +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols new file mode 100644 index 00000000000..c5ad54768b0 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts === + + +function f({}, a) { +>f : Symbol(f, Decl(emptyObjectBindingPatternParameter03.ts, 0, 0)) +>a : Symbol(a, Decl(emptyObjectBindingPatternParameter03.ts, 2, 14)) + + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter03.ts, 3, 4)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter03.ts, 3, 7)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter03.ts, 3, 10)) +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.types b/tests/baselines/reference/emptyObjectBindingPatternParameter03.types new file mode 100644 index 00000000000..60557d65f8c --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.types @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts === + + +function f({}, a) { +>f : ({}: {}, a: any) => void +>a : any + + var x, y, z; +>x : any +>y : any +>z : any +} From 0f871b9812f27a84e24fa45d56d8a94ce0287440 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 16:44:00 -0700 Subject: [PATCH 25/79] Check for number of binding elements in parameter patterns. --- src/compiler/emitter.ts | 17 +++++++++++------ src/compiler/utilities.ts | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 9d436870297..5da2abe3699 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -3142,12 +3142,17 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return; } - if (isBindingPattern(parameter.name)) { - writeLine(); - write("var "); - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); - write(";"); - tempIndex++; + let paramName = parameter.name; + if (isBindingPattern(paramName)) { + // In cases where a binding patternm is simply '[]' or '{}', + // we don't want to emit anything. + if (paramName.elements.length > 0) { + writeLine(); + write("var "); + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + write(";"); + tempIndex++; + } } else if (parameter.initializer) { writeLine(); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index ee75454ad93..72478a2fa26 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1067,7 +1067,7 @@ namespace ts { return SyntaxKind.FirstTemplateToken <= kind && kind <= SyntaxKind.LastTemplateToken; } - export function isBindingPattern(node: Node) { + export function isBindingPattern(node: Node): node is BindingPattern { return !!node && (node.kind === SyntaxKind.ArrayBindingPattern || node.kind === SyntaxKind.ObjectBindingPattern); } From b986514f4bec42a86ddae76bab436d0c2a2e604b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 16:45:12 -0700 Subject: [PATCH 26/79] Accepted baselines. --- .../reference/declarationEmitDestructuring4.js | 16 ++++------------ .../emptyArrayBindingPatternParameter01.js | 1 - .../emptyArrayBindingPatternParameter02.js | 1 - .../emptyArrayBindingPatternParameter03.js | 1 - .../emptyObjectBindingPatternParameter01.js | 1 - .../emptyObjectBindingPatternParameter02.js | 1 - .../emptyObjectBindingPatternParameter03.js | 1 - 7 files changed, 4 insertions(+), 18 deletions(-) diff --git a/tests/baselines/reference/declarationEmitDestructuring4.js b/tests/baselines/reference/declarationEmitDestructuring4.js index f5d9df09175..1f43c255170 100644 --- a/tests/baselines/reference/declarationEmitDestructuring4.js +++ b/tests/baselines/reference/declarationEmitDestructuring4.js @@ -15,21 +15,13 @@ function baz4({} = { x: 10 }) { } // For an array binding pattern with empty elements, // we will not make any modification and will emit // the similar binding pattern users' have written -function baz(_a) { - var ; -} -function baz1(_a) { - var _b = _a === void 0 ? [1, 2, 3] : _a; -} +function baz(_a) { } +function baz1(_a) { } function baz2(_a) { var _b = (_a === void 0 ? [[1, 2, 3]] : _a)[0]; } -function baz3(_a) { - var ; -} -function baz4(_a) { - var _b = _a === void 0 ? { x: 10 } : _a; -} +function baz3(_a) { } +function baz4(_a) { } //// [declarationEmitDestructuring4.d.ts] diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter01.js b/tests/baselines/reference/emptyArrayBindingPatternParameter01.js index b074024ed94..05b59b7d5f2 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter01.js +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter01.js @@ -7,6 +7,5 @@ function f([]) { //// [emptyArrayBindingPatternParameter01.js] function f(_a) { - var ; var x, y, z; } diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.js b/tests/baselines/reference/emptyArrayBindingPatternParameter02.js index aed9e567ee7..bc4053a0fe0 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter02.js +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.js @@ -7,6 +7,5 @@ function f(a, []) { //// [emptyArrayBindingPatternParameter02.js] function f(a, _a) { - var ; var x, y, z; } diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.js b/tests/baselines/reference/emptyArrayBindingPatternParameter03.js index 9fb9cc6202e..5431994234f 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter03.js +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.js @@ -7,6 +7,5 @@ function f(a, []) { //// [emptyArrayBindingPatternParameter03.js] function f(a, _a) { - var ; var x, y, z; } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.js b/tests/baselines/reference/emptyObjectBindingPatternParameter01.js index 9dd0e018561..a954627d2cb 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter01.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.js @@ -7,6 +7,5 @@ function f({}) { //// [emptyObjectBindingPatternParameter01.js] function f(_a) { - var ; var x, y, z; } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.js b/tests/baselines/reference/emptyObjectBindingPatternParameter02.js index d1ad19ffb30..119a84e95aa 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter02.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.js @@ -7,6 +7,5 @@ function f(a, {}) { //// [emptyObjectBindingPatternParameter02.js] function f(a, _a) { - var ; var x, y, z; } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.js b/tests/baselines/reference/emptyObjectBindingPatternParameter03.js index efbdd5b04ea..3fb84c0eae8 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter03.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.js @@ -7,6 +7,5 @@ function f({}, a) { //// [emptyObjectBindingPatternParameter03.js] function f(_a, a) { - var ; var x, y, z; } From 51246fe8939fbb55c3d04133ddc9820ffd237f0c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 17:31:52 -0700 Subject: [PATCH 27/79] Tabs -> Spaces --- .../es6/destructuring/emptyArrayBindingPatternParameter02.ts | 2 +- .../es6/destructuring/emptyArrayBindingPatternParameter03.ts | 2 +- .../es6/destructuring/emptyObjectBindingPatternParameter01.ts | 2 +- .../es6/destructuring/emptyObjectBindingPatternParameter02.ts | 2 +- .../es6/destructuring/emptyObjectBindingPatternParameter03.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts index aa945ed3bca..39663a4bed7 100644 --- a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts +++ b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter02.ts @@ -1,5 +1,5 @@ function f(a, []) { - var x, y, z; + var x, y, z; } \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts index aa945ed3bca..39663a4bed7 100644 --- a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts +++ b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter03.ts @@ -1,5 +1,5 @@ function f(a, []) { - var x, y, z; + var x, y, z; } \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts index aa6e4f265be..01aa5b54230 100644 --- a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter01.ts @@ -1,5 +1,5 @@ function f({}) { - var x, y, z; + var x, y, z; } \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts index 671d69beb2b..f34503c1152 100644 --- a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter02.ts @@ -1,5 +1,5 @@ function f(a, {}) { - var x, y, z; + var x, y, z; } \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts index 4639b0b2042..a940c659703 100644 --- a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter03.ts @@ -1,5 +1,5 @@ function f({}, a) { - var x, y, z; + var x, y, z; } \ No newline at end of file From 1dd5a9955770e68fa00909674a8f4931f39cc2b9 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 17:33:29 -0700 Subject: [PATCH 28/79] Accepted baselines. --- .../reference/emptyArrayBindingPatternParameter02.js | 2 +- .../reference/emptyArrayBindingPatternParameter02.symbols | 8 ++++---- .../reference/emptyArrayBindingPatternParameter02.types | 2 +- .../reference/emptyArrayBindingPatternParameter03.js | 2 +- .../reference/emptyArrayBindingPatternParameter03.symbols | 8 ++++---- .../reference/emptyArrayBindingPatternParameter03.types | 2 +- .../reference/emptyObjectBindingPatternParameter01.js | 2 +- .../emptyObjectBindingPatternParameter01.symbols | 8 ++++---- .../reference/emptyObjectBindingPatternParameter01.types | 2 +- .../reference/emptyObjectBindingPatternParameter02.js | 2 +- .../emptyObjectBindingPatternParameter02.symbols | 8 ++++---- .../reference/emptyObjectBindingPatternParameter02.types | 2 +- .../reference/emptyObjectBindingPatternParameter03.js | 2 +- .../emptyObjectBindingPatternParameter03.symbols | 8 ++++---- .../reference/emptyObjectBindingPatternParameter03.types | 2 +- 15 files changed, 30 insertions(+), 30 deletions(-) diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.js b/tests/baselines/reference/emptyArrayBindingPatternParameter02.js index bc4053a0fe0..dbd86e843a8 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter02.js +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.js @@ -2,7 +2,7 @@ function f(a, []) { - var x, y, z; + var x, y, z; } //// [emptyArrayBindingPatternParameter02.js] diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols b/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols index e189bc41def..48cdcfaf93d 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.symbols @@ -5,8 +5,8 @@ function f(a, []) { >f : Symbol(f, Decl(emptyArrayBindingPatternParameter02.ts, 0, 0)) >a : Symbol(a, Decl(emptyArrayBindingPatternParameter02.ts, 2, 11)) - var x, y, z; ->x : Symbol(x, Decl(emptyArrayBindingPatternParameter02.ts, 3, 4)) ->y : Symbol(y, Decl(emptyArrayBindingPatternParameter02.ts, 3, 7)) ->z : Symbol(z, Decl(emptyArrayBindingPatternParameter02.ts, 3, 10)) + var x, y, z; +>x : Symbol(x, Decl(emptyArrayBindingPatternParameter02.ts, 3, 7)) +>y : Symbol(y, Decl(emptyArrayBindingPatternParameter02.ts, 3, 10)) +>z : Symbol(z, Decl(emptyArrayBindingPatternParameter02.ts, 3, 13)) } diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter02.types b/tests/baselines/reference/emptyArrayBindingPatternParameter02.types index 12657203f90..a58fe6b91d3 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter02.types +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter02.types @@ -5,7 +5,7 @@ function f(a, []) { >f : (a: any, []: any[]) => void >a : any - var x, y, z; + var x, y, z; >x : any >y : any >z : any diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.js b/tests/baselines/reference/emptyArrayBindingPatternParameter03.js index 5431994234f..e2c3f7196e6 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter03.js +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.js @@ -2,7 +2,7 @@ function f(a, []) { - var x, y, z; + var x, y, z; } //// [emptyArrayBindingPatternParameter03.js] diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols b/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols index a236a642807..d3ec078df78 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.symbols @@ -5,8 +5,8 @@ function f(a, []) { >f : Symbol(f, Decl(emptyArrayBindingPatternParameter03.ts, 0, 0)) >a : Symbol(a, Decl(emptyArrayBindingPatternParameter03.ts, 2, 11)) - var x, y, z; ->x : Symbol(x, Decl(emptyArrayBindingPatternParameter03.ts, 3, 4)) ->y : Symbol(y, Decl(emptyArrayBindingPatternParameter03.ts, 3, 7)) ->z : Symbol(z, Decl(emptyArrayBindingPatternParameter03.ts, 3, 10)) + var x, y, z; +>x : Symbol(x, Decl(emptyArrayBindingPatternParameter03.ts, 3, 7)) +>y : Symbol(y, Decl(emptyArrayBindingPatternParameter03.ts, 3, 10)) +>z : Symbol(z, Decl(emptyArrayBindingPatternParameter03.ts, 3, 13)) } diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter03.types b/tests/baselines/reference/emptyArrayBindingPatternParameter03.types index d1cc85c462a..43f0af63ace 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter03.types +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter03.types @@ -5,7 +5,7 @@ function f(a, []) { >f : (a: any, []: any[]) => void >a : any - var x, y, z; + var x, y, z; >x : any >y : any >z : any diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.js b/tests/baselines/reference/emptyObjectBindingPatternParameter01.js index a954627d2cb..28cc30d2a0b 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter01.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.js @@ -2,7 +2,7 @@ function f({}) { - var x, y, z; + var x, y, z; } //// [emptyObjectBindingPatternParameter01.js] diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols index 701482c1355..98829df994f 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.symbols @@ -4,8 +4,8 @@ function f({}) { >f : Symbol(f, Decl(emptyObjectBindingPatternParameter01.ts, 0, 0)) - var x, y, z; ->x : Symbol(x, Decl(emptyObjectBindingPatternParameter01.ts, 3, 4)) ->y : Symbol(y, Decl(emptyObjectBindingPatternParameter01.ts, 3, 7)) ->z : Symbol(z, Decl(emptyObjectBindingPatternParameter01.ts, 3, 10)) + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter01.ts, 3, 7)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter01.ts, 3, 10)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter01.ts, 3, 13)) } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter01.types b/tests/baselines/reference/emptyObjectBindingPatternParameter01.types index 90b351e00dc..c46569ea770 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter01.types +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter01.types @@ -4,7 +4,7 @@ function f({}) { >f : ({}: {}) => void - var x, y, z; + var x, y, z; >x : any >y : any >z : any diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.js b/tests/baselines/reference/emptyObjectBindingPatternParameter02.js index 119a84e95aa..8488428ea51 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter02.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.js @@ -2,7 +2,7 @@ function f(a, {}) { - var x, y, z; + var x, y, z; } //// [emptyObjectBindingPatternParameter02.js] diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols index 7e58c6bae2e..fb0fa946b6f 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.symbols @@ -5,8 +5,8 @@ function f(a, {}) { >f : Symbol(f, Decl(emptyObjectBindingPatternParameter02.ts, 0, 0)) >a : Symbol(a, Decl(emptyObjectBindingPatternParameter02.ts, 2, 11)) - var x, y, z; ->x : Symbol(x, Decl(emptyObjectBindingPatternParameter02.ts, 3, 4)) ->y : Symbol(y, Decl(emptyObjectBindingPatternParameter02.ts, 3, 7)) ->z : Symbol(z, Decl(emptyObjectBindingPatternParameter02.ts, 3, 10)) + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter02.ts, 3, 7)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter02.ts, 3, 10)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter02.ts, 3, 13)) } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter02.types b/tests/baselines/reference/emptyObjectBindingPatternParameter02.types index 67969e069be..0a77fac8588 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter02.types +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter02.types @@ -5,7 +5,7 @@ function f(a, {}) { >f : (a: any, {}: {}) => void >a : any - var x, y, z; + var x, y, z; >x : any >y : any >z : any diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.js b/tests/baselines/reference/emptyObjectBindingPatternParameter03.js index 3fb84c0eae8..0279744e386 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter03.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.js @@ -2,7 +2,7 @@ function f({}, a) { - var x, y, z; + var x, y, z; } //// [emptyObjectBindingPatternParameter03.js] diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols index c5ad54768b0..4e658e21ccf 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.symbols @@ -5,8 +5,8 @@ function f({}, a) { >f : Symbol(f, Decl(emptyObjectBindingPatternParameter03.ts, 0, 0)) >a : Symbol(a, Decl(emptyObjectBindingPatternParameter03.ts, 2, 14)) - var x, y, z; ->x : Symbol(x, Decl(emptyObjectBindingPatternParameter03.ts, 3, 4)) ->y : Symbol(y, Decl(emptyObjectBindingPatternParameter03.ts, 3, 7)) ->z : Symbol(z, Decl(emptyObjectBindingPatternParameter03.ts, 3, 10)) + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter03.ts, 3, 7)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter03.ts, 3, 10)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter03.ts, 3, 13)) } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter03.types b/tests/baselines/reference/emptyObjectBindingPatternParameter03.types index 60557d65f8c..873c748dd9b 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter03.types +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter03.types @@ -5,7 +5,7 @@ function f({}, a) { >f : ({}: {}, a: any) => void >a : any - var x, y, z; + var x, y, z; >x : any >y : any >z : any From ebf486f7111df0e4c34b5f4f34ec85f656ec56da Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 17:40:13 -0700 Subject: [PATCH 29/79] Added tests where parameters have initializers. --- .../es6/destructuring/emptyArrayBindingPatternParameter04.ts | 5 +++++ .../destructuring/emptyObjectBindingPatternParameter04.ts | 5 +++++ 2 files changed, 10 insertions(+) create mode 100644 tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter04.ts create mode 100644 tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter04.ts diff --git a/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter04.ts b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter04.ts new file mode 100644 index 00000000000..313d4fe6708 --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter04.ts @@ -0,0 +1,5 @@ + + +function f([] = [1,2,3,4]) { + var x, y, z; +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter04.ts b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter04.ts new file mode 100644 index 00000000000..da05e5cb428 --- /dev/null +++ b/tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter04.ts @@ -0,0 +1,5 @@ + + +function f({} = {a: 1, b: "2", c: true}) { + var x, y, z; +} \ No newline at end of file From b159944f0a5eb662988f6f6cabcfc787b72ff294 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 22 Jun 2015 17:50:15 -0700 Subject: [PATCH 30/79] Accepted baselines. --- .../emptyArrayBindingPatternParameter04.js | 11 +++++++++++ ...emptyArrayBindingPatternParameter04.symbols | 11 +++++++++++ .../emptyArrayBindingPatternParameter04.types | 16 ++++++++++++++++ .../emptyObjectBindingPatternParameter04.js | 11 +++++++++++ ...mptyObjectBindingPatternParameter04.symbols | 14 ++++++++++++++ .../emptyObjectBindingPatternParameter04.types | 18 ++++++++++++++++++ 6 files changed, 81 insertions(+) create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter04.js create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter04.symbols create mode 100644 tests/baselines/reference/emptyArrayBindingPatternParameter04.types create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter04.js create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter04.symbols create mode 100644 tests/baselines/reference/emptyObjectBindingPatternParameter04.types diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter04.js b/tests/baselines/reference/emptyArrayBindingPatternParameter04.js new file mode 100644 index 00000000000..3f52b95ab62 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter04.js @@ -0,0 +1,11 @@ +//// [emptyArrayBindingPatternParameter04.ts] + + +function f([] = [1,2,3,4]) { + var x, y, z; +} + +//// [emptyArrayBindingPatternParameter04.js] +function f(_a) { + var x, y, z; +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter04.symbols b/tests/baselines/reference/emptyArrayBindingPatternParameter04.symbols new file mode 100644 index 00000000000..bb76a2c5925 --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter04.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter04.ts === + + +function f([] = [1,2,3,4]) { +>f : Symbol(f, Decl(emptyArrayBindingPatternParameter04.ts, 0, 0)) + + var x, y, z; +>x : Symbol(x, Decl(emptyArrayBindingPatternParameter04.ts, 3, 7)) +>y : Symbol(y, Decl(emptyArrayBindingPatternParameter04.ts, 3, 10)) +>z : Symbol(z, Decl(emptyArrayBindingPatternParameter04.ts, 3, 13)) +} diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter04.types b/tests/baselines/reference/emptyArrayBindingPatternParameter04.types new file mode 100644 index 00000000000..6f00a994f7b --- /dev/null +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter04.types @@ -0,0 +1,16 @@ +=== tests/cases/conformance/es6/destructuring/emptyArrayBindingPatternParameter04.ts === + + +function f([] = [1,2,3,4]) { +>f : ([]?: number[]) => void +>[1,2,3,4] : number[] +>1 : number +>2 : number +>3 : number +>4 : number + + var x, y, z; +>x : any +>y : any +>z : any +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter04.js b/tests/baselines/reference/emptyObjectBindingPatternParameter04.js new file mode 100644 index 00000000000..6545ea9ad34 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter04.js @@ -0,0 +1,11 @@ +//// [emptyObjectBindingPatternParameter04.ts] + + +function f({} = {a: 1, b: "2", c: true}) { + var x, y, z; +} + +//// [emptyObjectBindingPatternParameter04.js] +function f(_a) { + var x, y, z; +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter04.symbols b/tests/baselines/reference/emptyObjectBindingPatternParameter04.symbols new file mode 100644 index 00000000000..9922d4cd074 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter04.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter04.ts === + + +function f({} = {a: 1, b: "2", c: true}) { +>f : Symbol(f, Decl(emptyObjectBindingPatternParameter04.ts, 0, 0)) +>a : Symbol(a, Decl(emptyObjectBindingPatternParameter04.ts, 2, 17)) +>b : Symbol(b, Decl(emptyObjectBindingPatternParameter04.ts, 2, 22)) +>c : Symbol(c, Decl(emptyObjectBindingPatternParameter04.ts, 2, 30)) + + var x, y, z; +>x : Symbol(x, Decl(emptyObjectBindingPatternParameter04.ts, 3, 7)) +>y : Symbol(y, Decl(emptyObjectBindingPatternParameter04.ts, 3, 10)) +>z : Symbol(z, Decl(emptyObjectBindingPatternParameter04.ts, 3, 13)) +} diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter04.types b/tests/baselines/reference/emptyObjectBindingPatternParameter04.types new file mode 100644 index 00000000000..5ee32d422a9 --- /dev/null +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter04.types @@ -0,0 +1,18 @@ +=== tests/cases/conformance/es6/destructuring/emptyObjectBindingPatternParameter04.ts === + + +function f({} = {a: 1, b: "2", c: true}) { +>f : ({}?: { a: number; b: string; c: boolean; }) => void +>{a: 1, b: "2", c: true} : { a: number; b: string; c: boolean; } +>a : number +>1 : number +>b : string +>"2" : string +>c : boolean +>true : boolean + + var x, y, z; +>x : any +>y : any +>z : any +} From 8e2b204ace1901aaced26cde1bb2084d8db11b6d Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Tue, 23 Jun 2015 11:25:33 -0700 Subject: [PATCH 31/79] do not try to classify missing nodes --- src/services/services.ts | 4 ++++ .../fourslash/syntacticClassificationWithErrors.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 tests/cases/fourslash/syntacticClassificationWithErrors.ts diff --git a/src/services/services.ts b/src/services/services.ts index 70022cfe0bf..18510b9a178 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -6300,6 +6300,10 @@ namespace ts { } function classifyToken(token: Node): void { + if (nodeIsMissing(token)) { + return; + } + let tokenStart = classifyLeadingTriviaAndGetTokenStart(token); let tokenWidth = token.end - tokenStart; diff --git a/tests/cases/fourslash/syntacticClassificationWithErrors.ts b/tests/cases/fourslash/syntacticClassificationWithErrors.ts new file mode 100644 index 00000000000..b4572d3e620 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationWithErrors.ts @@ -0,0 +1,14 @@ +/// + +////class A { +//// a: +////} +////c = + +let c = classification +verify.syntacticClassificationsAre( + c.keyword("class"), c.className("A"), c.punctuation("{"), + c.text("a"), c.punctuation(":"), + c.punctuation("}"), + c.text("c"), c.operator("=") + ); \ No newline at end of file From 30657d4d55666eb5275d550893740dbfa306f606 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 23 Jun 2015 12:39:15 -0700 Subject: [PATCH 32/79] Update LKG --- bin/tsserver.js | 3 +++ bin/typescript.js | 3 +++ bin/typescriptServices.js | 3 +++ 3 files changed, 9 insertions(+) diff --git a/bin/tsserver.js b/bin/tsserver.js index 6f4c99b36a6..2d937e57fad 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -36217,6 +36217,9 @@ var ts; } } function classifyToken(token) { + if (ts.nodeIsMissing(token)) { + return; + } var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); var tokenWidth = token.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); diff --git a/bin/typescript.js b/bin/typescript.js index 2e3a784b298..6989f225452 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -42395,6 +42395,9 @@ var ts; } } function classifyToken(token) { + if (ts.nodeIsMissing(token)) { + return; + } var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); var tokenWidth = token.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 2e3a784b298..6989f225452 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -42395,6 +42395,9 @@ var ts; } } function classifyToken(token) { + if (ts.nodeIsMissing(token)) { + return; + } var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); var tokenWidth = token.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); From ef697f6307d514cb378b161128f6d74ffb0079c6 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 23 Jun 2015 14:00:05 -0700 Subject: [PATCH 33/79] PR feedback --- src/compiler/checker.ts | 46 +++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2c4e18699d7..3db99a12686 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6769,9 +6769,20 @@ module ts { let argCount = getEffectiveArgumentCount(node, args, signature); for (let i = 0; i < argCount; i++) { let arg = getEffectiveArgument(node, args, i); - if (!arg || arg.kind !== SyntaxKind.OmittedExpression) { + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { let paramType = getTypeAtPosition(signature, i); - let argType = getEffectiveArgumentType(node, i, arg, paramType, excludeArgument, inferenceMapper, /*reportErrors*/ false); + let argType = getEffectiveArgumentType(node, i, arg); + + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context, argType, paramType); } } @@ -6830,10 +6841,19 @@ module ts { let argCount = getEffectiveArgumentCount(node, args, signature); for (let i = 0; i < argCount; i++) { let arg = getEffectiveArgument(node, args, i); - if (!arg || arg.kind !== SyntaxKind.OmittedExpression) { + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) let paramType = getTypeAtPosition(signature, i); - let argType = getEffectiveArgumentType(node, i, arg, paramType, excludeArgument, /*inferenceMapper*/ undefined, reportErrors); + let argType = getEffectiveArgumentType(node, i, arg); + + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors + ? getStringLiteralType(arg) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + } // Use argument expression as error location when reporting errors let errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -7126,7 +7146,7 @@ module ts { /** * Gets the effective argument type for an argument in a call expression. */ - function getEffectiveArgumentType(node: CallLikeExpression, argIndex: number, arg: Expression, paramType: Type, excludeArgument: boolean[], inferenceMapper: TypeMapper, reportErrors: boolean): Type { + function getEffectiveArgumentType(node: CallLikeExpression, argIndex: number, arg: Expression): Type { // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors @@ -7136,20 +7156,10 @@ module ts { else if (argIndex === 0 && node.kind === SyntaxKind.TaggedTemplateExpression) { return globalTemplateStringsArrayType; } - else if (!inferenceMapper && !reportErrors && arg.kind === SyntaxKind.StringLiteral) { - return getStringLiteralType(arg); - } - else { - let mapper: TypeMapper; - if (inferenceMapper) { - mapper = excludeArgument && excludeArgument[argIndex] !== undefined ? identityMapper : inferenceMapper; - } - else { - mapper = excludeArgument && excludeArgument[argIndex] ? identityMapper : undefined; - } - return checkExpressionWithContextualType(arg, paramType, mapper); - } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. + return undefined; } /** From 60ed259a90d1b8b7a8a90da077fe12b8cb92f950 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 23 Jun 2015 15:05:33 -0700 Subject: [PATCH 34/79] Preserve initializer. --- src/compiler/emitter.ts | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 5da2abe3699..4e19bb79e5f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -3142,30 +3142,41 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return; } - let paramName = parameter.name; + let { name: paramName, initializer } = parameter; if (isBindingPattern(paramName)) { - // In cases where a binding patternm is simply '[]' or '{}', - // we don't want to emit anything. - if (paramName.elements.length > 0) { + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + let hasBindingElements = paramName.elements.length > 0; + if (hasBindingElements || initializer) { writeLine(); write("var "); - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + + if (hasBindingElements) { + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + } + else { + emit(tempParameters[tempIndex]); + write(" = "); + emit(initializer); + } + write(";"); tempIndex++; } } - else if (parameter.initializer) { + else if (initializer) { writeLine(); emitStart(parameter); write("if ("); - emitNodeWithoutSourceMap(parameter.name); + emitNodeWithoutSourceMap(paramName); write(" === void 0)"); emitEnd(parameter); write(" { "); emitStart(parameter); - emitNodeWithoutSourceMap(parameter.name); + emitNodeWithoutSourceMap(paramName); write(" = "); - emitNodeWithoutSourceMap(parameter.initializer); + emitNodeWithoutSourceMap(initializer); emitEnd(parameter); write("; }"); } From 740fd9c908380147212ecd9a2d77b238e13c7172 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 23 Jun 2015 15:05:56 -0700 Subject: [PATCH 35/79] Updated baselines. --- .../baselines/reference/declarationEmitDestructuring4.js | 8 ++++++-- .../reference/emptyArrayBindingPatternParameter04.js | 1 + .../reference/emptyObjectBindingPatternParameter04.js | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/baselines/reference/declarationEmitDestructuring4.js b/tests/baselines/reference/declarationEmitDestructuring4.js index 1f43c255170..16e6b49a4cf 100644 --- a/tests/baselines/reference/declarationEmitDestructuring4.js +++ b/tests/baselines/reference/declarationEmitDestructuring4.js @@ -16,12 +16,16 @@ function baz4({} = { x: 10 }) { } // we will not make any modification and will emit // the similar binding pattern users' have written function baz(_a) { } -function baz1(_a) { } +function baz1(_a) { + var _a = [1, 2, 3]; +} function baz2(_a) { var _b = (_a === void 0 ? [[1, 2, 3]] : _a)[0]; } function baz3(_a) { } -function baz4(_a) { } +function baz4(_a) { + var _a = { x: 10 }; +} //// [declarationEmitDestructuring4.d.ts] diff --git a/tests/baselines/reference/emptyArrayBindingPatternParameter04.js b/tests/baselines/reference/emptyArrayBindingPatternParameter04.js index 3f52b95ab62..e0715499ffe 100644 --- a/tests/baselines/reference/emptyArrayBindingPatternParameter04.js +++ b/tests/baselines/reference/emptyArrayBindingPatternParameter04.js @@ -7,5 +7,6 @@ function f([] = [1,2,3,4]) { //// [emptyArrayBindingPatternParameter04.js] function f(_a) { + var _a = [1, 2, 3, 4]; var x, y, z; } diff --git a/tests/baselines/reference/emptyObjectBindingPatternParameter04.js b/tests/baselines/reference/emptyObjectBindingPatternParameter04.js index 6545ea9ad34..fc3e41d0709 100644 --- a/tests/baselines/reference/emptyObjectBindingPatternParameter04.js +++ b/tests/baselines/reference/emptyObjectBindingPatternParameter04.js @@ -7,5 +7,6 @@ function f({} = {a: 1, b: "2", c: true}) { //// [emptyObjectBindingPatternParameter04.js] function f(_a) { + var _a = { a: 1, b: "2", c: true }; var x, y, z; } From d2fe1c0a61b7518f8b1b2f32ba46703a1c1db9e3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 23 Jun 2015 15:13:11 -0700 Subject: [PATCH 36/79] Added tests. --- .../completionsInObjectBindingPattern01.ts | 13 +++++++++++++ .../completionsInObjectBindingPattern02.ts | 13 +++++++++++++ .../completionsInObjectBindingPattern03.ts | 13 +++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern01.ts create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern02.ts create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern03.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern01.ts b/tests/cases/fourslash/completionsInObjectBindingPattern01.ts new file mode 100644 index 00000000000..128e95b8ed3 --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern01.ts @@ -0,0 +1,13 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var foo: I; +////var { /**/ } = foo; + +goTo.marker(); +verify.completionListContains("property1"); +verify.completionListContains("property2"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern02.ts b/tests/cases/fourslash/completionsInObjectBindingPattern02.ts new file mode 100644 index 00000000000..776fcc955c2 --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern02.ts @@ -0,0 +1,13 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var foo: I; +////var { property1, /**/ } = foo; + +goTo.marker(); +verify.not.completionListContains("property1"); +verify.completionListContains("property2"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern03.ts b/tests/cases/fourslash/completionsInObjectBindingPattern03.ts new file mode 100644 index 00000000000..72da68168bd --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern03.ts @@ -0,0 +1,13 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var foo: I; +////var { property1: /**/ } = foo; + +goTo.marker(); +verify.completionListAllowsNewIdentifier(); +verify.completionListIsEmpty(); \ No newline at end of file From 0b78d037467f26629f260d9eeb87baaa982bcdc9 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 23 Jun 2015 15:32:02 -0700 Subject: [PATCH 37/79] Clean up 'getContainingObjectLiteralApplicableForCompletion'. --- src/services/services.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 18510b9a178..5af32f9972c 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -3187,15 +3187,14 @@ namespace ts { return false; } - function getContainingObjectLiteralApplicableForCompletion(previousToken: Node): ObjectLiteralExpression { - // The locations in an object literal expression that are applicable for completion are property name definition locations. - - if (previousToken) { - let parent = previousToken.parent; - - switch (previousToken.kind) { + function getContainingObjectLiteralApplicableForCompletion(contextToken: Node): ObjectLiteralExpression { + // The locations in an object literal expression that + // are applicable for completion are property name definition locations. + if (contextToken) { + switch (contextToken.kind) { case SyntaxKind.OpenBraceToken: // let x = { | case SyntaxKind.CommaToken: // let x = { a: 0, | + let parent = contextToken.parent; if (parent && parent.kind === SyntaxKind.ObjectLiteralExpression) { return parent; } From 30ec5f92767b2f996c38b15c906598860f36d420 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 23 Jun 2015 16:08:19 -0700 Subject: [PATCH 38/79] Add test case for when in the middle/at the end of the word. --- .../completionsInObjectBindingPattern04.ts | 13 +++++++++++++ .../completionsInObjectBindingPattern05.ts | 12 ++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern04.ts create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern05.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern04.ts b/tests/cases/fourslash/completionsInObjectBindingPattern04.ts new file mode 100644 index 00000000000..92b202a1b37 --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern04.ts @@ -0,0 +1,13 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var foo: I; +////var { prope/**/ } = foo; + +goTo.marker(); +verify.completionListContains("property1"); +verify.completionListContains("property2"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern05.ts b/tests/cases/fourslash/completionsInObjectBindingPattern05.ts new file mode 100644 index 00000000000..d17e11810df --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern05.ts @@ -0,0 +1,12 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var foo: I; +////var { property1/**/ } = foo; + +goTo.marker(); +verify.completionListContains("property1"); \ No newline at end of file From 6accbdf0299e01e723fd07676f98bb8f71694e88 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 23 Jun 2015 16:37:22 -0700 Subject: [PATCH 39/79] Generalize logic for upcoming work on object binding completion. --- src/services/services.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 5af32f9972c..1aeac286748 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -2985,8 +2985,8 @@ namespace ts { } function tryGetGlobalSymbols(): boolean { - let containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(contextToken); - if (containingObjectLiteral) { + let containingObjectLiteral = getContainingObjectLiteralOrBindingPatternIfApplicableForCompletion(contextToken); + if (containingObjectLiteral && containingObjectLiteral.kind === SyntaxKind.ObjectLiteralExpression) { // Object literal expression, look up possible property names from contextual type isMemberCompletion = true; isNewIdentifierLocation = true; @@ -3187,7 +3187,7 @@ namespace ts { return false; } - function getContainingObjectLiteralApplicableForCompletion(contextToken: Node): ObjectLiteralExpression { + function getContainingObjectLiteralOrBindingPatternIfApplicableForCompletion(contextToken: Node): ObjectLiteralExpression | BindingPattern { // The locations in an object literal expression that // are applicable for completion are property name definition locations. if (contextToken) { @@ -3195,8 +3195,8 @@ namespace ts { case SyntaxKind.OpenBraceToken: // let x = { | case SyntaxKind.CommaToken: // let x = { a: 0, | let parent = contextToken.parent; - if (parent && parent.kind === SyntaxKind.ObjectLiteralExpression) { - return parent; + if (parent && (parent.kind === SyntaxKind.ObjectLiteralExpression || parent.kind === SyntaxKind.ObjectBindingPattern)) { + return parent; } break; } From 6928bfae12c80a263d4f040751378807d88a7741 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 23 Jun 2015 17:00:11 -0700 Subject: [PATCH 40/79] Adding extra test per CR --- .../reference/classExpressionES63.js | 31 +++++++++++++++++ .../reference/classExpressionES63.symbols | 26 +++++++++++++++ .../reference/classExpressionES63.types | 33 +++++++++++++++++++ .../classExpressions/classExpressionES63.ts | 6 ++++ 4 files changed, 96 insertions(+) create mode 100644 tests/baselines/reference/classExpressionES63.js create mode 100644 tests/baselines/reference/classExpressionES63.symbols create mode 100644 tests/baselines/reference/classExpressionES63.types create mode 100644 tests/cases/conformance/es6/classExpressions/classExpressionES63.ts diff --git a/tests/baselines/reference/classExpressionES63.js b/tests/baselines/reference/classExpressionES63.js new file mode 100644 index 00000000000..6d357af7c5a --- /dev/null +++ b/tests/baselines/reference/classExpressionES63.js @@ -0,0 +1,31 @@ +//// [classExpressionES63.ts] +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +let c = new C(); +c.a; +c.b; +c.c; + + +//// [classExpressionES63.js] +let C = class class_1 extends class class_2 extends class class_3 { + constructor() { + this.a = 1; + } +} + { + constructor(...args) { + super(...args); + this.b = 2; + } +} + { + constructor(...args) { + super(...args); + this.c = 3; + } +} +; +let c = new C(); +c.a; +c.b; +c.c; diff --git a/tests/baselines/reference/classExpressionES63.symbols b/tests/baselines/reference/classExpressionES63.symbols new file mode 100644 index 00000000000..4e52d5ee9dd --- /dev/null +++ b/tests/baselines/reference/classExpressionES63.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES63.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : Symbol(C, Decl(classExpressionES63.ts, 0, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpressionES63.ts, 0, 43)) +>b : Symbol((Anonymous class).b, Decl(classExpressionES63.ts, 0, 53)) +>c : Symbol((Anonymous class).c, Decl(classExpressionES63.ts, 0, 63)) + +let c = new C(); +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>C : Symbol(C, Decl(classExpressionES63.ts, 0, 3)) + +c.a; +>c.a : Symbol((Anonymous class).a, Decl(classExpressionES63.ts, 0, 43)) +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>a : Symbol((Anonymous class).a, Decl(classExpressionES63.ts, 0, 43)) + +c.b; +>c.b : Symbol((Anonymous class).b, Decl(classExpressionES63.ts, 0, 53)) +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>b : Symbol((Anonymous class).b, Decl(classExpressionES63.ts, 0, 53)) + +c.c; +>c.c : Symbol((Anonymous class).c, Decl(classExpressionES63.ts, 0, 63)) +>c : Symbol(c, Decl(classExpressionES63.ts, 1, 3)) +>c : Symbol((Anonymous class).c, Decl(classExpressionES63.ts, 0, 63)) + diff --git a/tests/baselines/reference/classExpressionES63.types b/tests/baselines/reference/classExpressionES63.types new file mode 100644 index 00000000000..5b07bf79692 --- /dev/null +++ b/tests/baselines/reference/classExpressionES63.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/es6/classExpressions/classExpressionES63.ts === +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +>C : typeof (Anonymous class) +>class extends class extends class { a = 1 } { b = 2 } { c = 3 } : typeof (Anonymous class) +>class extends class { a = 1 } { b = 2 } : (Anonymous class) +>class { a = 1 } : (Anonymous class) +>a : number +>1 : number +>b : number +>2 : number +>c : number +>3 : number + +let c = new C(); +>c : (Anonymous class) +>new C() : (Anonymous class) +>C : typeof (Anonymous class) + +c.a; +>c.a : number +>c : (Anonymous class) +>a : number + +c.b; +>c.b : number +>c : (Anonymous class) +>b : number + +c.c; +>c.c : number +>c : (Anonymous class) +>c : number + diff --git a/tests/cases/conformance/es6/classExpressions/classExpressionES63.ts b/tests/cases/conformance/es6/classExpressions/classExpressionES63.ts new file mode 100644 index 00000000000..cbbe0927c30 --- /dev/null +++ b/tests/cases/conformance/es6/classExpressions/classExpressionES63.ts @@ -0,0 +1,6 @@ +// @target: es6 +let C = class extends class extends class { a = 1 } { b = 2 } { c = 3 }; +let c = new C(); +c.a; +c.b; +c.c; From 55f195d445ede31aea7b83da435480bcf0d7c7e8 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 23 Jun 2015 17:06:47 -0700 Subject: [PATCH 41/79] Another change suggested in CR --- src/compiler/checker.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4891bff8630..9d3dc53da78 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5949,9 +5949,8 @@ namespace ts { captureLexicalThis(node, container); } - let classNode = isClassLike(container.parent) ? container.parent : undefined; - if (classNode) { - let symbol = getSymbolOfNode(classNode); + if (isClassLike(container.parent)) { + let symbol = getSymbolOfNode(container.parent); return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); } return anyType; From 2aceeea064e8c39bcce7bd1949e6924953fd03a4 Mon Sep 17 00:00:00 2001 From: Tingan Ho Date: Wed, 24 Jun 2015 10:37:23 +0800 Subject: [PATCH 42/79] Fixes goto definitions for type predicates --- src/compiler/checker.ts | 4 ++++ .../fourslash/goToDefinitionTypePredicate.ts | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 tests/cases/fourslash/goToDefinitionTypePredicate.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 71aa2ce1a07..29ff56172f5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11925,6 +11925,10 @@ namespace ts { return resolveEntityName(entityName, meaning); } + if (entityName.parent.kind === SyntaxKind.TypePredicate) { + return resolveEntityName(entityName, /* meanings */ SymbolFlags.Variable); + } + // Do we want to return undefined here? return undefined; } diff --git a/tests/cases/fourslash/goToDefinitionTypePredicate.ts b/tests/cases/fourslash/goToDefinitionTypePredicate.ts new file mode 100644 index 00000000000..40f1d1eb94c --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionTypePredicate.ts @@ -0,0 +1,16 @@ +/// + +//// /*classDeclaration*/class A {} +//// function f(/*parameterDeclaration*/parameter: any): /*parameterName*/parameter is /*typeReference*/A { +//// return typeof parameter === "string"; +//// } + +goTo.marker('parameterName'); + +goTo.definition(); +verify.caretAtMarker('parameterDeclaration'); + +goTo.marker('typeReference'); + +goTo.definition(); +verify.caretAtMarker('classDeclaration'); \ No newline at end of file From 485e31905731bfdf7101ddd0761338bc1e763103 Mon Sep 17 00:00:00 2001 From: Tingan Ho Date: Wed, 24 Jun 2015 10:48:22 +0800 Subject: [PATCH 43/79] Accept baselines --- tests/baselines/reference/typeGuardFunction.symbols | 11 +++++++++++ .../reference/typeGuardFunctionGenerics.symbols | 7 +++++++ .../baselines/reference/typeGuardOfFormIsType.symbols | 3 +++ .../typeGuardOfFormIsTypeOnInterfaces.symbols | 3 +++ 4 files changed, 24 insertions(+) diff --git a/tests/baselines/reference/typeGuardFunction.symbols b/tests/baselines/reference/typeGuardFunction.symbols index c315e721085..13ad30de5c5 100644 --- a/tests/baselines/reference/typeGuardFunction.symbols +++ b/tests/baselines/reference/typeGuardFunction.symbols @@ -25,16 +25,19 @@ class C extends A { declare function isA(p1: any): p1 is A; >isA : Symbol(isA, Decl(typeGuardFunction.ts, 11, 1)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 13, 21)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 13, 21)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) declare function isB(p1: any): p1 is B; >isB : Symbol(isB, Decl(typeGuardFunction.ts, 13, 39)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 14, 21)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 14, 21)) >B : Symbol(B, Decl(typeGuardFunction.ts, 3, 1)) declare function isC(p1: any): p1 is C; >isC : Symbol(isC, Decl(typeGuardFunction.ts, 14, 39)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 15, 21)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 15, 21)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) declare function retC(): C; @@ -98,6 +101,7 @@ interface I1 { (p1: A): p1 is C; >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 41, 5)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 41, 5)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) } @@ -107,6 +111,7 @@ declare function isC_multipleParams(p1, p2): p1 is C; >isC_multipleParams : Symbol(isC_multipleParams, Decl(typeGuardFunction.ts, 42, 1)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 46, 36)) >p2 : Symbol(p2, Decl(typeGuardFunction.ts, 46, 39)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 46, 36)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) if (isC_multipleParams(a, 0)) { @@ -127,6 +132,7 @@ var obj: { >func1 : Symbol(func1, Decl(typeGuardFunction.ts, 52, 10)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 53, 10)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 53, 10)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) } class D { @@ -136,6 +142,7 @@ class D { >method1 : Symbol(method1, Decl(typeGuardFunction.ts, 55, 9)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 56, 12)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 56, 12)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) return true; @@ -147,6 +154,7 @@ let f1 = (p1: A): p1 is C => false; >f1 : Symbol(f1, Decl(typeGuardFunction.ts, 62, 3)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 62, 10)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 62, 10)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) // Function type @@ -155,6 +163,7 @@ declare function f2(p1: (p1: A) => p1 is C); >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 65, 20)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 65, 25)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 65, 25)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) // Function expressions @@ -162,6 +171,7 @@ f2(function(p1: A): p1 is C { >f2 : Symbol(f2, Decl(typeGuardFunction.ts, 62, 35)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 68, 12)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) +>p1 : Symbol(p1, Decl(typeGuardFunction.ts, 68, 12)) >C : Symbol(C, Decl(typeGuardFunction.ts, 7, 1)) return true; @@ -182,6 +192,7 @@ declare function acceptingTypeGuardFunction(p1: (item) => item is A); >acceptingTypeGuardFunction : Symbol(acceptingTypeGuardFunction, Decl(typeGuardFunction.ts, 74, 25)) >p1 : Symbol(p1, Decl(typeGuardFunction.ts, 77, 44)) >item : Symbol(item, Decl(typeGuardFunction.ts, 77, 49)) +>item : Symbol(item, Decl(typeGuardFunction.ts, 77, 49)) >A : Symbol(A, Decl(typeGuardFunction.ts, 0, 0)) acceptingTypeGuardFunction(isA); diff --git a/tests/baselines/reference/typeGuardFunctionGenerics.symbols b/tests/baselines/reference/typeGuardFunctionGenerics.symbols index 0ad8fab2fdb..100d610070d 100644 --- a/tests/baselines/reference/typeGuardFunctionGenerics.symbols +++ b/tests/baselines/reference/typeGuardFunctionGenerics.symbols @@ -25,11 +25,13 @@ class C extends A { declare function isB(p1): p1 is B; >isB : Symbol(isB, Decl(typeGuardFunctionGenerics.ts, 11, 1)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 13, 21)) +>p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 13, 21)) >B : Symbol(B, Decl(typeGuardFunctionGenerics.ts, 3, 1)) declare function isC(p1): p1 is C; >isC : Symbol(isC, Decl(typeGuardFunctionGenerics.ts, 13, 34)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 14, 21)) +>p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 14, 21)) >C : Symbol(C, Decl(typeGuardFunctionGenerics.ts, 7, 1)) declare function retC(x): C; @@ -52,6 +54,7 @@ declare function funB(p1: (p1) => T, p2: any): p2 is T; >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 18, 30)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 18, 22)) >p2 : Symbol(p2, Decl(typeGuardFunctionGenerics.ts, 18, 39)) +>p2 : Symbol(p2, Decl(typeGuardFunctionGenerics.ts, 18, 39)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 18, 22)) declare function funC(p1: (p1) => p1 is T): T; @@ -59,6 +62,7 @@ declare function funC(p1: (p1) => p1 is T): T; >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 19, 22)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 19, 25)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 19, 30)) +>p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 19, 30)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 19, 22)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 19, 22)) @@ -67,8 +71,10 @@ declare function funD(p1: (p1) => p1 is T, p2: any): p2 is T; >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 20, 22)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 20, 25)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 20, 30)) +>p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 20, 30)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 20, 22)) >p2 : Symbol(p2, Decl(typeGuardFunctionGenerics.ts, 20, 45)) +>p2 : Symbol(p2, Decl(typeGuardFunctionGenerics.ts, 20, 45)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 20, 22)) declare function funE(p1: (p1) => p1 is T, p2: U): T; @@ -77,6 +83,7 @@ declare function funE(p1: (p1) => p1 is T, p2: U): T; >U : Symbol(U, Decl(typeGuardFunctionGenerics.ts, 21, 24)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 21, 28)) >p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 21, 33)) +>p1 : Symbol(p1, Decl(typeGuardFunctionGenerics.ts, 21, 33)) >T : Symbol(T, Decl(typeGuardFunctionGenerics.ts, 21, 22)) >p2 : Symbol(p2, Decl(typeGuardFunctionGenerics.ts, 21, 48)) >U : Symbol(U, Decl(typeGuardFunctionGenerics.ts, 21, 24)) diff --git a/tests/baselines/reference/typeGuardOfFormIsType.symbols b/tests/baselines/reference/typeGuardOfFormIsType.symbols index a7bd0f4c165..e7e8965673d 100644 --- a/tests/baselines/reference/typeGuardOfFormIsType.symbols +++ b/tests/baselines/reference/typeGuardOfFormIsType.symbols @@ -31,6 +31,7 @@ var strOrNum: string | number; function isC1(x: any): x is C1 { >isC1 : Symbol(isC1, Decl(typeGuardOfFormIsType.ts, 12, 30)) >x : Symbol(x, Decl(typeGuardOfFormIsType.ts, 14, 14)) +>x : Symbol(x, Decl(typeGuardOfFormIsType.ts, 14, 14)) >C1 : Symbol(C1, Decl(typeGuardOfFormIsType.ts, 0, 0)) return true; @@ -39,6 +40,7 @@ function isC1(x: any): x is C1 { function isC2(x: any): x is C2 { >isC2 : Symbol(isC2, Decl(typeGuardOfFormIsType.ts, 16, 1)) >x : Symbol(x, Decl(typeGuardOfFormIsType.ts, 18, 14)) +>x : Symbol(x, Decl(typeGuardOfFormIsType.ts, 18, 14)) >C2 : Symbol(C2, Decl(typeGuardOfFormIsType.ts, 3, 1)) return true; @@ -47,6 +49,7 @@ function isC2(x: any): x is C2 { function isD1(x: any): x is D1 { >isD1 : Symbol(isD1, Decl(typeGuardOfFormIsType.ts, 20, 1)) >x : Symbol(x, Decl(typeGuardOfFormIsType.ts, 22, 14)) +>x : Symbol(x, Decl(typeGuardOfFormIsType.ts, 22, 14)) >D1 : Symbol(D1, Decl(typeGuardOfFormIsType.ts, 6, 1)) return true; diff --git a/tests/baselines/reference/typeGuardOfFormIsTypeOnInterfaces.symbols b/tests/baselines/reference/typeGuardOfFormIsTypeOnInterfaces.symbols index 37249ef7659..641d20d95cd 100644 --- a/tests/baselines/reference/typeGuardOfFormIsTypeOnInterfaces.symbols +++ b/tests/baselines/reference/typeGuardOfFormIsTypeOnInterfaces.symbols @@ -50,6 +50,7 @@ var strOrNum: string | number; function isC1(x: any): x is C1 { >isC1 : Symbol(isC1, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 17, 30)) >x : Symbol(x, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 20, 14)) +>x : Symbol(x, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 20, 14)) >C1 : Symbol(C1, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 0, 0)) return true; @@ -58,6 +59,7 @@ function isC1(x: any): x is C1 { function isC2(x: any): x is C2 { >isC2 : Symbol(isC2, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 22, 1)) >x : Symbol(x, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 24, 14)) +>x : Symbol(x, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 24, 14)) >C2 : Symbol(C2, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 5, 1)) return true; @@ -66,6 +68,7 @@ function isC2(x: any): x is C2 { function isD1(x: any): x is D1 { >isD1 : Symbol(isD1, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 26, 1)) >x : Symbol(x, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 28, 14)) +>x : Symbol(x, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 28, 14)) >D1 : Symbol(D1, Decl(typeGuardOfFormIsTypeOnInterfaces.ts, 10, 1)) return true; From 1d0454534201239138df4eb721f268b4ccd617fe Mon Sep 17 00:00:00 2001 From: Tingan Ho Date: Wed, 24 Jun 2015 11:00:48 +0800 Subject: [PATCH 44/79] Changed symbolflag --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 29ff56172f5..a97a8428a0b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11926,7 +11926,7 @@ namespace ts { } if (entityName.parent.kind === SyntaxKind.TypePredicate) { - return resolveEntityName(entityName, /* meanings */ SymbolFlags.Variable); + return resolveEntityName(entityName, /* meanings */ SymbolFlags.FunctionScopedVariable); } // Do we want to return undefined here? From cb9f80f1aa378164b40d2c332abb3107b98fbf97 Mon Sep 17 00:00:00 2001 From: Tingan Ho Date: Wed, 24 Jun 2015 11:32:30 +0800 Subject: [PATCH 45/79] Remove space and s --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a97a8428a0b..db04831f832 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11926,7 +11926,7 @@ namespace ts { } if (entityName.parent.kind === SyntaxKind.TypePredicate) { - return resolveEntityName(entityName, /* meanings */ SymbolFlags.FunctionScopedVariable); + return resolveEntityName(entityName, /*meaning*/ SymbolFlags.FunctionScopedVariable); } // Do we want to return undefined here? From da1bc6bac8d637dda683aee727b3154cb95023eb Mon Sep 17 00:00:00 2001 From: jbondc Date: Wed, 24 Jun 2015 10:56:23 -0400 Subject: [PATCH 46/79] Don't report an error for 1.toString(), just emit a space for JS compat. --- .../diagnosticInformationMap.generated.ts | 1 - src/compiler/diagnosticMessages.json | 4 ---- src/compiler/emitter.ts | 6 +++++- src/compiler/parser.ts | 17 ++++------------- src/compiler/types.ts | 1 - tests/cases/compiler/numLit.ts | 18 ++++++++++-------- 6 files changed, 19 insertions(+), 28 deletions(-) diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 46976813120..09b009711fe 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -569,6 +569,5 @@ namespace ts { decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, - Numeric_literal_0_cannot_be_followed_by_an_expression: { code: 9004, category: DiagnosticCategory.Error, key: "Numeric literal {0} cannot be followed by an expression." }, }; } \ No newline at end of file diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4b705396fe5..fee46a84c1e 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2268,9 +2268,5 @@ "'class' expressions are not currently supported.": { "category": "Error", "code": 9003 - }, - "Numeric literal {0} cannot be followed by an expression.": { - "category": "Error", - "code": 9004 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 3fbe640254f..363acf7b651 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1778,7 +1778,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emit(node.expression); let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); - write("."); + if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) { + write(" ."); // JS compat with numeric literal + } else { + write("."); + } let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 55fdcd91d34..14c7d6da455 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -100,8 +100,6 @@ namespace ts { visitNode(cbNode, (node).type) || visitNode(cbNode, (node).equalsGreaterThanToken) || visitNode(cbNode, (node).body); - case SyntaxKind.NumericLiteral: - return visitNode(cbNode, (node).invalidDotExpression); case SyntaxKind.TypeReference: return visitNode(cbNode, (node).typeName) || visitNodes(cbNodes, (node).typeArguments); @@ -1847,20 +1845,13 @@ namespace ts { if (sourceText.charCodeAt(tokenPos) === CharacterCodes._0 && isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { node.flags |= NodeFlags.OctalLiteral; } - else if (token === SyntaxKind.DotToken) { - // Issue #2632 Keep space for 3 .toString() - if (isWhiteSpace(sourceText.charCodeAt(node.end))) { - node.end++; - scanner.setTextPos(node.end + 1); - } - } else if (token === SyntaxKind.Identifier && sourceText.charCodeAt(node.end-1) === CharacterCodes.dot) { nextCharCode = sourceText.charCodeAt(node.end); if (!isWhiteSpace(nextCharCode) && !isLineBreak(nextCharCode)) { - // Eat up an invalid expression following '1.' e.g. 1.something() - node.invalidDotExpression = parseLeftHandSideExpressionOrHigher(); - parseErrorAtPosition(node.end, node.invalidDotExpression.end - node.end, Diagnostics.Numeric_literal_0_cannot_be_followed_by_an_expression, "'" + sourceText.substring(tokenPos, node.end) + "'"); - node.end = node.invalidDotExpression.end; + // If we see 23.Identifier, go back 1 char to scan .Identifier + node.end = node.end - 1; + scanner.setTextPos(node.end); + nextToken() } } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 187cead4842..40135fe22e4 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -737,7 +737,6 @@ namespace ts { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; - invalidDotExpression?: LeftHandSideExpression; // 1.toString() we attach the node but never emit it } export interface TemplateExpression extends PrimaryExpression { diff --git a/tests/cases/compiler/numLit.ts b/tests/cases/compiler/numLit.ts index d9d42f9018c..abe3505703d 100644 --- a/tests/cases/compiler/numLit.ts +++ b/tests/cases/compiler/numLit.ts @@ -1,15 +1,17 @@ 1..toString(); 1.0.toString(); -1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. +1.toString(); 1.+2.0 + 3. ; // Preserve whitespace where important for JS compatibility var i: number = 1; var test1 = i.toString(); -var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. -var test3 = 3 .toString(); // preserve whitepace -var test4 = 3.['toString'](); -var test5 = 3 -.toString(); // preserve whitepace -var test6 = new Number(4).toString(); -var test7 = 3. + 3. \ No newline at end of file +var test2 = 2.toString(); // emitted as 2 .toString() +var test3 = 3 .toString(); +var test4 = 3 .toString(); +var test5 = 3 .toString(); +var test6 = 3.['toString'](); +var test7 = 3 +.toString(); +var test8 = new Number(4).toString(); +var test9 = 3. + 3. From 71dc7a5947c201c60f11e4f4e950e258354d3f2b Mon Sep 17 00:00:00 2001 From: jbondc Date: Wed, 24 Jun 2015 11:08:54 -0400 Subject: [PATCH 47/79] Accept baselines --- tests/baselines/reference/numLit.errors.txt | 24 ----------- tests/baselines/reference/numLit.js | 41 +++++++++++-------- .../reference/toStringOnPrimitives.js | 2 +- 3 files changed, 24 insertions(+), 43 deletions(-) delete mode 100644 tests/baselines/reference/numLit.errors.txt diff --git a/tests/baselines/reference/numLit.errors.txt b/tests/baselines/reference/numLit.errors.txt deleted file mode 100644 index 66f11141c15..00000000000 --- a/tests/baselines/reference/numLit.errors.txt +++ /dev/null @@ -1,24 +0,0 @@ -tests/cases/compiler/numLit.ts(3,3): error TS9004: Numeric literal '1.' cannot be followed by an expression. -tests/cases/compiler/numLit.ts(9,15): error TS9004: Numeric literal '2.' cannot be followed by an expression. - - -==== tests/cases/compiler/numLit.ts (2 errors) ==== - 1..toString(); - 1.0.toString(); - 1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. - ~~~~~~~~~~ -!!! error TS9004: Numeric literal '1.' cannot be followed by an expression. - 1.+2.0 + 3. ; - - // Preserve whitespace where important for JS compatibility - var i: number = 1; - var test1 = i.toString(); - var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. - ~~~~~~~~~~ -!!! error TS9004: Numeric literal '2.' cannot be followed by an expression. - var test3 = 3 .toString(); // preserve whitepace - var test4 = 3.['toString'](); - var test5 = 3 - .toString(); // preserve whitepace - var test6 = new Number(4).toString(); - var test7 = 3. + 3. \ No newline at end of file diff --git a/tests/baselines/reference/numLit.js b/tests/baselines/reference/numLit.js index a6e33a9a3c1..5620a9edcad 100644 --- a/tests/baselines/reference/numLit.js +++ b/tests/baselines/reference/numLit.js @@ -1,32 +1,37 @@ //// [numLit.ts] 1..toString(); 1.0.toString(); -1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. +1.toString(); 1.+2.0 + 3. ; // Preserve whitespace where important for JS compatibility var i: number = 1; var test1 = i.toString(); -var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. -var test3 = 3 .toString(); // preserve whitepace -var test4 = 3.['toString'](); -var test5 = 3 -.toString(); // preserve whitepace -var test6 = new Number(4).toString(); -var test7 = 3. + 3. +var test2 = 2.toString(); // emitted as 2 .toString() +var test3 = 3 .toString(); +var test4 = 3 .toString(); +var test5 = 3 .toString(); +var test6 = 3.['toString'](); +var test7 = 3 +.toString(); +var test8 = new Number(4).toString(); +var test9 = 3. + 3. + //// [numLit.js] -1..toString(); -1.0.toString(); -1.toString(); // error: Numeric literal '1.' cannot be followed by an expression. +1. .toString(); +1.0 .toString(); +1 .toString(); 1. + 2.0 + 3.; // Preserve whitespace where important for JS compatibility var i = 1; var test1 = i.toString(); -var test2 = 2.toString(); // error: Numeric literal '2.' cannot be followed by an expression. -var test3 = 3 .toString(); // preserve whitepace -var test4 = 3.['toString'](); -var test5 = 3 - .toString(); // preserve whitepace -var test6 = new Number(4).toString(); -var test7 = 3. + 3.; +var test2 = 2 .toString(); // emitted as 2 .toString() +var test3 = 3 .toString(); +var test4 = 3 .toString(); +var test5 = 3 .toString(); +var test6 = 3.['toString'](); +var test7 = 3 + .toString(); +var test8 = new Number(4).toString(); +var test9 = 3. + 3.; diff --git a/tests/baselines/reference/toStringOnPrimitives.js b/tests/baselines/reference/toStringOnPrimitives.js index bce8a997ba7..007bb5429b0 100644 --- a/tests/baselines/reference/toStringOnPrimitives.js +++ b/tests/baselines/reference/toStringOnPrimitives.js @@ -8,4 +8,4 @@ aBool.toString(); true.toString(); var aBool = false; aBool.toString(); -1..toString(); +1. .toString(); From 8ae53a43102ec9b1301ffd8cf8cae0ec18ae203d Mon Sep 17 00:00:00 2001 From: jbondc Date: Wed, 24 Jun 2015 11:21:48 -0400 Subject: [PATCH 48/79] Accept baselines (missing files). --- tests/baselines/reference/numLit.symbols | 65 ++++++++++++++++ tests/baselines/reference/numLit.types | 97 ++++++++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 tests/baselines/reference/numLit.symbols create mode 100644 tests/baselines/reference/numLit.types diff --git a/tests/baselines/reference/numLit.symbols b/tests/baselines/reference/numLit.symbols new file mode 100644 index 00000000000..1f4067d233f --- /dev/null +++ b/tests/baselines/reference/numLit.symbols @@ -0,0 +1,65 @@ +=== tests/cases/compiler/numLit.ts === +1..toString(); +>1..toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +1.0.toString(); +>1.0.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +1.toString(); +>1.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +1.+2.0 + 3. ; + +// Preserve whitespace where important for JS compatibility +var i: number = 1; +>i : Symbol(i, Decl(numLit.ts, 6, 3)) + +var test1 = i.toString(); +>test1 : Symbol(test1, Decl(numLit.ts, 7, 3)) +>i.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>i : Symbol(i, Decl(numLit.ts, 6, 3)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test2 = 2.toString(); // emitted as 2 .toString() +>test2 : Symbol(test2, Decl(numLit.ts, 8, 3)) +>2.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test3 = 3 .toString(); +>test3 : Symbol(test3, Decl(numLit.ts, 9, 3)) +>3 .toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test4 = 3 .toString(); +>test4 : Symbol(test4, Decl(numLit.ts, 10, 3)) +>3 .toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test5 = 3 .toString(); +>test5 : Symbol(test5, Decl(numLit.ts, 11, 3)) +>3 .toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test6 = 3.['toString'](); +>test6 : Symbol(test6, Decl(numLit.ts, 12, 3)) +>'toString' : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test7 = 3 +>test7 : Symbol(test7, Decl(numLit.ts, 13, 3)) +>3.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +.toString(); +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test8 = new Number(4).toString(); +>test8 : Symbol(test8, Decl(numLit.ts, 15, 3)) +>new Number(4).toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) +>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) + +var test9 = 3. + 3. +>test9 : Symbol(test9, Decl(numLit.ts, 16, 3)) + diff --git a/tests/baselines/reference/numLit.types b/tests/baselines/reference/numLit.types new file mode 100644 index 00000000000..ba72abb2825 --- /dev/null +++ b/tests/baselines/reference/numLit.types @@ -0,0 +1,97 @@ +=== tests/cases/compiler/numLit.ts === +1..toString(); +>1..toString() : string +>1..toString : (radix?: number) => string +>1. : number +>toString : (radix?: number) => string + +1.0.toString(); +>1.0.toString() : string +>1.0.toString : (radix?: number) => string +>1.0 : number +>toString : (radix?: number) => string + +1.toString(); +>1.toString() : string +>1.toString : (radix?: number) => string +>1 : number +>toString : (radix?: number) => string + +1.+2.0 + 3. ; +>1.+2.0 + 3. : number +>1.+2.0 : number +>1. : number +>2.0 : number +>3. : number + +// Preserve whitespace where important for JS compatibility +var i: number = 1; +>i : number +>1 : number + +var test1 = i.toString(); +>test1 : string +>i.toString() : string +>i.toString : (radix?: number) => string +>i : number +>toString : (radix?: number) => string + +var test2 = 2.toString(); // emitted as 2 .toString() +>test2 : string +>2.toString() : string +>2.toString : (radix?: number) => string +>2 : number +>toString : (radix?: number) => string + +var test3 = 3 .toString(); +>test3 : string +>3 .toString() : string +>3 .toString : (radix?: number) => string +>3 : number +>toString : (radix?: number) => string + +var test4 = 3 .toString(); +>test4 : string +>3 .toString() : string +>3 .toString : (radix?: number) => string +>3 : number +>toString : (radix?: number) => string + +var test5 = 3 .toString(); +>test5 : string +>3 .toString() : string +>3 .toString : (radix?: number) => string +>3 : number +>toString : (radix?: number) => string + +var test6 = 3.['toString'](); +>test6 : string +>3.['toString']() : string +>3.['toString'] : (radix?: number) => string +>3. : number +>'toString' : string + +var test7 = 3 +>test7 : string +>3.toString() : string +>3.toString : (radix?: number) => string +>3 : number + +.toString(); +>toString : (radix?: number) => string + +var test8 = new Number(4).toString(); +>test8 : string +>new Number(4).toString() : string +>new Number(4).toString : (radix?: number) => string +>new Number(4) : Number +>Number : NumberConstructor +>4 : number +>toString : (radix?: number) => string + +var test9 = 3. + 3. +>test9 : number +>3. + 3. : number +>3. : number +>3. : number + From c6498d79e57fa8ca018b3b7060b7d81c3c487a5e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 11:28:56 -0400 Subject: [PATCH 49/79] Changed ordering of verifications. --- tests/cases/fourslash/completionsInObjectBindingPattern02.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern02.ts b/tests/cases/fourslash/completionsInObjectBindingPattern02.ts index 776fcc955c2..6d2b7a6b516 100644 --- a/tests/cases/fourslash/completionsInObjectBindingPattern02.ts +++ b/tests/cases/fourslash/completionsInObjectBindingPattern02.ts @@ -9,5 +9,5 @@ ////var { property1, /**/ } = foo; goTo.marker(); -verify.not.completionListContains("property1"); -verify.completionListContains("property2"); \ No newline at end of file +verify.completionListContains("property2"); +verify.not.completionListContains("property1"); \ No newline at end of file From 513d73ad4b48601511e5b6515db663a973d22dc4 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 11:30:10 -0400 Subject: [PATCH 50/79] Don't print in the middle of tests. --- src/harness/fourslash.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 5915698462c..ff5baddbb70 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -660,8 +660,7 @@ module FourSlash { } errorMsg += "]\n"; - Harness.IO.log(errorMsg); - this.raiseError("Member list is not empty at Caret"); + this.raiseError("Member list is not empty at Caret: " + errorMsg); } } From c114de1a836524f3a60e9569d5369b7631d6f5fc Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 11:31:36 -0400 Subject: [PATCH 51/79] Basic completion in object destructuring working. --- src/compiler/checker.ts | 6 +++++- src/services/services.ts | 31 ++++++++++++++++++++----------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a18f2921a9a..00426d2aaf3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11993,7 +11993,7 @@ namespace ts { return resolveExternalModuleName(node, node); } - // Intentional fall-through + // fall through case SyntaxKind.NumericLiteral: // index access if (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { @@ -12060,6 +12060,10 @@ namespace ts { return symbol && getTypeOfSymbol(symbol); } + if (isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent); + } + if (isInRightSideOfImportOrExportAssignment(node)) { let symbol = getSymbolInfo(node); let declaredType = symbol && getDeclaredTypeOfSymbol(symbol); diff --git a/src/services/services.ts b/src/services/services.ts index 1aeac286748..78ce084b3ff 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -2985,21 +2985,32 @@ namespace ts { } function tryGetGlobalSymbols(): boolean { - let containingObjectLiteral = getContainingObjectLiteralOrBindingPatternIfApplicableForCompletion(contextToken); - if (containingObjectLiteral && containingObjectLiteral.kind === SyntaxKind.ObjectLiteralExpression) { + let objectLikeContainer = getContainingObjectLiteralOrBindingPatternIfApplicableForCompletion(contextToken); + if (objectLikeContainer) { // Object literal expression, look up possible property names from contextual type isMemberCompletion = true; isNewIdentifierLocation = true; - let contextualType = typeChecker.getContextualType(containingObjectLiteral); - if (!contextualType) { + let typeForObject: Type; + let existingMembers: Declaration[]; + + if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { + typeForObject = typeChecker.getContextualType(objectLikeContainer); + existingMembers = (objectLikeContainer).properties; + } + else { + typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + existingMembers = (objectLikeContainer).elements; + } + + if (!typeForObject) { return false; } - let contextualTypeMembers = typeChecker.getPropertiesOfType(contextualType); - if (contextualTypeMembers && contextualTypeMembers.length > 0) { + let typeMembers = typeChecker.getPropertiesOfType(typeForObject); + if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list - symbols = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); + symbols = filterContextualMembersList(typeMembers, existingMembers); } } else if (getAncestor(contextToken, SyntaxKind.ImportClause)) { @@ -3235,8 +3246,7 @@ namespace ts { containingNodeKind === SyntaxKind.ClassDeclaration || // class A Date: Wed, 24 Jun 2015 11:41:59 -0400 Subject: [PATCH 52/79] Got filtering working in object binding patterns. --- src/services/services.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 78ce084b3ff..2283d02ccb9 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -3010,7 +3010,7 @@ namespace ts { let typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list - symbols = filterContextualMembersList(typeMembers, existingMembers); + symbols = filterObjectMembersList(typeMembers, existingMembers); } } else if (getAncestor(contextToken, SyntaxKind.ImportClause)) { @@ -3356,26 +3356,28 @@ namespace ts { return filter(exports, e => !lookUp(exisingImports, e.name)); } - function filterContextualMembersList(contextualMemberSymbols: Symbol[], existingMembers: Declaration[]): Symbol[] { + function filterObjectMembersList(contextualMemberSymbols: Symbol[], existingMembers: Declaration[]): Symbol[] { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } let existingMemberNames: Map = {}; - forEach(existingMembers, m => { - if (m.kind !== SyntaxKind.PropertyAssignment && m.kind !== SyntaxKind.ShorthandPropertyAssignment) { - // Ignore omitted expressions for missing members in the object literal - return; + for (let m of existingMembers) { + if (m.kind !== SyntaxKind.PropertyAssignment && + m.kind !== SyntaxKind.ShorthandPropertyAssignment && + m.kind !== SyntaxKind.BindingElement) { + // Ignore omitted expressions for missing members + continue; } if (m.getStart() <= position && position <= m.getEnd()) { // If this is the current item we are editing right now, do not filter it out - return; + continue; } // TODO(jfreeman): Account for computed property name existingMemberNames[(m.name).text] = true; - }); + } let filteredMembers: Symbol[] = []; forEach(contextualMemberSymbols, s => { From f9ed47a1bb2f31aa7359e1a553620740e0f1cb53 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 12:28:54 -0400 Subject: [PATCH 53/79] Add the services sources as dependencies to tsserver. --- Jakefile.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jakefile.js b/Jakefile.js index 07a2ade06a6..a0ec0d880fe 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -103,7 +103,7 @@ var serverSources = [ "server.ts" ].map(function (f) { return path.join(serverDirectory, f); -}); +}).concat(servicesSources); var languageServiceLibrarySources = [ "editorServices.ts", From d3c59f4cc2c062f377896f01c001757ea5c2a940 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 12:33:49 -0400 Subject: [PATCH 54/79] Added more tests. --- .../completionsInObjectBindingPattern06.ts | 12 ++++++++++++ .../completionsInObjectBindingPattern07.ts | 18 ++++++++++++++++++ .../completionsInObjectBindingPattern08.ts | 18 ++++++++++++++++++ .../completionsInObjectBindingPattern09.ts | 19 +++++++++++++++++++ 4 files changed, 67 insertions(+) create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern06.ts create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern07.ts create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern08.ts create mode 100644 tests/cases/fourslash/completionsInObjectBindingPattern09.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern06.ts b/tests/cases/fourslash/completionsInObjectBindingPattern06.ts new file mode 100644 index 00000000000..8060c2bde78 --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern06.ts @@ -0,0 +1,12 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var foo: I; +////var { property1, property2, /**/ } = foo; + +goTo.marker(); +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern07.ts b/tests/cases/fourslash/completionsInObjectBindingPattern07.ts new file mode 100644 index 00000000000..a3015346aa3 --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern07.ts @@ -0,0 +1,18 @@ +/// + +////interface I { +//// propertyOfI_1: number; +//// propertyOfI_2: string; +////} +////interface J { +//// property1: I; +//// property2: string; +////} +//// +////var foo: J; +////var { property1: { /**/ } } = foo; + +goTo.marker(); +verify.completionListContains("propertyOfI_1"); +verify.completionListContains("propertyOfI_2"); +verify.not.completionListContains("property2"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern08.ts b/tests/cases/fourslash/completionsInObjectBindingPattern08.ts new file mode 100644 index 00000000000..6d6be330b83 --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern08.ts @@ -0,0 +1,18 @@ +/// + +////interface I { +//// propertyOfI_1: number; +//// propertyOfI_2: string; +////} +////interface J { +//// property1: I; +//// property2: string; +////} +//// +////var foo: J; +////var { property1: { propertyOfI_1, /**/ } } = foo; + +goTo.marker(); +verify.completionListContains("propertyOfI_2"); +verify.not.completionListContains("propertyOfI_1"); +verify.not.completionListContains("property2"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern09.ts b/tests/cases/fourslash/completionsInObjectBindingPattern09.ts new file mode 100644 index 00000000000..2698e78667b --- /dev/null +++ b/tests/cases/fourslash/completionsInObjectBindingPattern09.ts @@ -0,0 +1,19 @@ +/// + +////interface I { +//// propertyOfI_1: number; +//// propertyOfI_2: string; +////} +////interface J { +//// property1: I; +//// property2: string; +////} +//// +////var foo: J; +////var { property1: { propertyOfI_1, }, /**/ } = foo; + +goTo.marker(); +verify.completionListContains("property2"); +verify.not.completionListContains("property1"); +verify.not.completionListContains("propertyOfI_2"); +verify.not.completionListContains("propertyOfI_1"); \ No newline at end of file From d892a55aa9cd14b86bd6578ed102540fbcf7c8eb Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 12:35:11 -0400 Subject: [PATCH 55/79] Use 'propertyName' when available in a BindingPattern. --- src/services/services.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 2283d02ccb9..25949082e8d 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -3363,20 +3363,31 @@ namespace ts { let existingMemberNames: Map = {}; for (let m of existingMembers) { + // Ignore omitted expressions for missing members if (m.kind !== SyntaxKind.PropertyAssignment && m.kind !== SyntaxKind.ShorthandPropertyAssignment && m.kind !== SyntaxKind.BindingElement) { - // Ignore omitted expressions for missing members continue; } + // If this is the current item we are editing right now, do not filter it out if (m.getStart() <= position && position <= m.getEnd()) { - // If this is the current item we are editing right now, do not filter it out continue; } - // TODO(jfreeman): Account for computed property name - existingMemberNames[(m.name).text] = true; + let existingName: string; + + if (m.kind === SyntaxKind.BindingElement && (m).propertyName) { + existingName = (m).propertyName.text; + } + else { + // TODO(jfreeman): Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + existingName = (m.name).text; + } + + existingMemberNames[existingName] = true; } let filteredMembers: Symbol[] = []; From 713a70d794356a2fd5c6ba9d5a84cbde0d392803 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 12:39:10 -0400 Subject: [PATCH 56/79] Renamed tests. --- ...dingPattern01.ts => completionListInObjectBindingPattern01.ts} | 0 ...dingPattern02.ts => completionListInObjectBindingPattern02.ts} | 0 ...dingPattern03.ts => completionListInObjectBindingPattern03.ts} | 0 ...dingPattern04.ts => completionListInObjectBindingPattern04.ts} | 0 ...dingPattern05.ts => completionListInObjectBindingPattern05.ts} | 0 ...dingPattern06.ts => completionListInObjectBindingPattern06.ts} | 0 ...dingPattern07.ts => completionListInObjectBindingPattern07.ts} | 0 ...dingPattern08.ts => completionListInObjectBindingPattern08.ts} | 0 ...dingPattern09.ts => completionListInObjectBindingPattern09.ts} | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename tests/cases/fourslash/{completionsInObjectBindingPattern01.ts => completionListInObjectBindingPattern01.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern02.ts => completionListInObjectBindingPattern02.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern03.ts => completionListInObjectBindingPattern03.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern04.ts => completionListInObjectBindingPattern04.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern05.ts => completionListInObjectBindingPattern05.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern06.ts => completionListInObjectBindingPattern06.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern07.ts => completionListInObjectBindingPattern07.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern08.ts => completionListInObjectBindingPattern08.ts} (100%) rename tests/cases/fourslash/{completionsInObjectBindingPattern09.ts => completionListInObjectBindingPattern09.ts} (100%) diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern01.ts b/tests/cases/fourslash/completionListInObjectBindingPattern01.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern01.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern01.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern02.ts b/tests/cases/fourslash/completionListInObjectBindingPattern02.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern02.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern02.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern03.ts b/tests/cases/fourslash/completionListInObjectBindingPattern03.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern03.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern03.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern04.ts b/tests/cases/fourslash/completionListInObjectBindingPattern04.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern04.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern04.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern05.ts b/tests/cases/fourslash/completionListInObjectBindingPattern05.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern05.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern05.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern06.ts b/tests/cases/fourslash/completionListInObjectBindingPattern06.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern06.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern06.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern07.ts b/tests/cases/fourslash/completionListInObjectBindingPattern07.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern07.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern07.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern08.ts b/tests/cases/fourslash/completionListInObjectBindingPattern08.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern08.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern08.ts diff --git a/tests/cases/fourslash/completionsInObjectBindingPattern09.ts b/tests/cases/fourslash/completionListInObjectBindingPattern09.ts similarity index 100% rename from tests/cases/fourslash/completionsInObjectBindingPattern09.ts rename to tests/cases/fourslash/completionListInObjectBindingPattern09.ts From 36a30c42b5d53aa1ee1911515e29aa6645e6b003 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 24 Jun 2015 11:53:53 -0700 Subject: [PATCH 57/79] Rename functions and variables, also a small refactoring. --- src/services/formatting/smartIndenter.ts | 44 ++++++++++++++++-------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index b9636a8ddb8..db748f7f494 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -298,35 +298,49 @@ namespace ts.formatting { function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorOptions): number { // actual indentation should not be used when: // - node is close parenthesis - this is the end of the expression - // - node is property access expression - if (node.kind !== SyntaxKind.CloseParenToken && - node.kind !== SyntaxKind.PropertyAccessExpression && - node.parent && ( + if (node.kind === SyntaxKind.CloseParenToken) { + return Value.Unknown; + } + + if (node.parent && ( node.parent.kind === SyntaxKind.CallExpression || - node.parent.kind === SyntaxKind.NewExpression)) { + node.parent.kind === SyntaxKind.NewExpression) && + (node.parent).expression !== node) { - let parentExpression = (node.parent).expression; - let startingExpression = getStartingExpression(parentExpression); + let fullCallOrNewExpression = (node.parent).expression; + let startingExpression = getStartingExpression(fullCallOrNewExpression); - if (parentExpression === startingExpression) { + if (fullCallOrNewExpression === startingExpression) { return Value.Unknown; } - let parentExpressionEnd = sourceFile.getLineAndCharacterOfPosition(parentExpression.end); + let fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); - if (parentExpressionEnd.line === startingExpressionEnd.line) { + if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { return Value.Unknown; } - return findColumnForFirstNonWhitespaceCharacterInLine(parentExpressionEnd, sourceFile, options); + return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); } + return Value.Unknown; - function getStartingExpression(expression: PropertyAccessExpression | CallExpression | ElementAccessExpression) { - while (expression.expression) - expression = expression.expression; - return expression; + function getStartingExpression(node: PropertyAccessExpression | CallExpression | ElementAccessExpression) { + while (true) { + switch (node.kind) { + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ElementAccessExpression: + + node = node.expression; + break; + default: + return node; + } + } + return node; } } From cc4511d9a15fb61af5ec26ee495e6047ee2af4f0 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 24 Jun 2015 12:48:35 -0700 Subject: [PATCH 58/79] Update LKG --- bin/lib.core.es6.d.ts | 4 + bin/lib.es6.d.ts | 4 + bin/tsc.js | 538 ++++++++++++++++++-------- bin/tsserver.js | 582 ++++++++++++++++++++-------- bin/typescript.d.ts | 2 +- bin/typescript.js | 734 +++++++++++++++++++++++++++--------- bin/typescriptServices.d.ts | 2 +- bin/typescriptServices.js | 734 +++++++++++++++++++++++++++--------- 8 files changed, 1940 insertions(+), 660 deletions(-) diff --git a/bin/lib.core.es6.d.ts b/bin/lib.core.es6.d.ts index 1ee111caa9b..50c7fcc9017 100644 --- a/bin/lib.core.es6.d.ts +++ b/bin/lib.core.es6.d.ts @@ -1880,6 +1880,7 @@ interface Map { } interface MapConstructor { + new (): Map; new (): Map; new (iterable: Iterable<[K, V]>): Map; prototype: Map; @@ -1896,6 +1897,7 @@ interface WeakMap { } interface WeakMapConstructor { + new (): WeakMap; new (): WeakMap; new (iterable: Iterable<[K, V]>): WeakMap; prototype: WeakMap; @@ -1917,6 +1919,7 @@ interface Set { } interface SetConstructor { + new (): Set; new (): Set; new (iterable: Iterable): Set; prototype: Set; @@ -1932,6 +1935,7 @@ interface WeakSet { } interface WeakSetConstructor { + new (): WeakSet; new (): WeakSet; new (iterable: Iterable): WeakSet; prototype: WeakSet; diff --git a/bin/lib.es6.d.ts b/bin/lib.es6.d.ts index e17cb3f35cf..931d60ec47a 100644 --- a/bin/lib.es6.d.ts +++ b/bin/lib.es6.d.ts @@ -1880,6 +1880,7 @@ interface Map { } interface MapConstructor { + new (): Map; new (): Map; new (iterable: Iterable<[K, V]>): Map; prototype: Map; @@ -1896,6 +1897,7 @@ interface WeakMap { } interface WeakMapConstructor { + new (): WeakMap; new (): WeakMap; new (iterable: Iterable<[K, V]>): WeakMap; prototype: WeakMap; @@ -1917,6 +1919,7 @@ interface Set { } interface SetConstructor { + new (): Set; new (): Set; new (iterable: Iterable): Set; prototype: Set; @@ -1932,6 +1935,7 @@ interface WeakSet { } interface WeakSetConstructor { + new (): WeakSet; new (): WeakSet; new (iterable: Iterable): WeakSet; prototype: WeakSet; diff --git a/bin/tsc.js b/bin/tsc.js index e5f449c4101..9e1d681e218 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -1166,6 +1166,12 @@ var ts; An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An export declaration can only be used in a module." }, An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." }, A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." }, + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." }, + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." }, + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." }, + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." }, + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." }, + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -1541,9 +1547,7 @@ var ts; property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, - decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } + decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." } }; })(ts || (ts = {})); /// @@ -3214,7 +3218,7 @@ var ts; } } function getStrictModeIdentifierMessage(node) { - if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -3252,7 +3256,7 @@ var ts; } } function getStrictModeEvalOrArgumentsMessage(node) { - if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -3504,7 +3508,7 @@ var ts; } if (node.flags & 112 && node.parent.kind === 137 && - (node.parent.parent.kind === 204 || node.parent.parent.kind === 177)) { + ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } @@ -3928,6 +3932,7 @@ var ts; case 208: case 206: case 204: + case 177: return; default: if (isFunctionLike(node)) { @@ -3962,20 +3967,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - if (node) { - switch (node.kind) { - case 138: - case 139: - return true; - } - } - return false; + return node && (node.kind === 138 || node.kind === 139); } ts.isAccessor = isAccessor; function isClassLike(node) { - if (node) { - return node.kind === 204 || node.kind === 177; - } + return node && (node.kind === 204 || node.kind === 177); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -4017,6 +4013,15 @@ var ts; } } ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { while (true) { node = node.parent; @@ -4025,7 +4030,7 @@ var ts; } switch (node.kind) { case 129: - if (node.parent.parent.kind === 204) { + if (isClassLike(node.parent.parent)) { return node; } node = node.parent; @@ -4066,7 +4071,7 @@ var ts; return node; switch (node.kind) { case 129: - if (node.parent.parent.kind === 204) { + if (isClassLike(node.parent.parent)) { return node; } node = node.parent; @@ -4406,6 +4411,7 @@ var ts; case 166: case 155: case 204: + case 177: case 137: case 207: case 229: @@ -5107,7 +5113,7 @@ var ts; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return node.kind === 179 && node.parent.token === 79 && - node.parent.parent.kind === 204; + isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isSupportedExpressionWithTypeArguments(node) { @@ -9709,10 +9715,7 @@ var ts; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; - var getGlobalClassDecoratorType; - var getGlobalParameterDecoratorType; - var getGlobalPropertyDecoratorType; - var getGlobalMethodDecoratorType; + var getGlobalTypedPropertyDescriptorType; var tupleTypes = {}; var unionTypes = {}; var stringLiteralTypes = {}; @@ -9969,7 +9972,7 @@ var ts; break; case 134: case 133: - if (location.parent.kind === 204 && !(location.flags & 128)) { + if (ts.isClassLike(location.parent) && !(location.flags & 128)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -9979,6 +9982,7 @@ var ts; } break; case 204: + case 177: case 205: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 128) { @@ -9987,10 +9991,17 @@ var ts; } break loop; } + if (location.kind === 177 && meaning & 32) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } + } break; case 129: grandparent = location.parent.parent; - if (grandparent.kind === 204 || grandparent.kind === 205) { + if (ts.isClassLike(grandparent) || grandparent.kind === 205) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; @@ -10022,15 +10033,6 @@ var ts; } } break; - case 177: - if (meaning & 32) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; case 132: if (location.parent && location.parent.kind === 131) { location = location.parent; @@ -10731,15 +10733,24 @@ var ts; } var _displayBuilder; function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - if (symbol.declarations && symbol.declarations.length > 0) { + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; if (declaration.name) { - writer.writeSymbol(ts.declarationNameToString(declaration.name), symbol); - return; + return ts.declarationNameToString(declaration.name); + } + switch (declaration.kind) { + case 177: + return "(Anonymous class)"; + case 165: + case 166: + return "(Anonymous function)"; } } - writer.writeSymbol(symbol.name, symbol); + return symbol.name; + } + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); } function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { var parentSymbol; @@ -11655,9 +11666,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 204 || node.kind === 203 || - node.kind === 165 || node.kind === 136 || - node.kind === 166) { + if (node.kind === 204 || node.kind === 177 || + node.kind === 203 || node.kind === 165 || + node.kind === 136 || node.kind === 166) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -11666,14 +11677,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var kind = symbol.flags & 32 ? 204 : 205; - return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 205); + return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 205 || node.kind === 204 || node.kind === 206) { + if (node.kind === 205 || node.kind === 204 || + node.kind === 177 || node.kind === 206) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -12686,6 +12698,12 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + function createTypedPropertyDescriptorType(propertyType) { + var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyObjectType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } function createTypeFromGenericGlobalType(genericGlobalType, elementType) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; } @@ -13101,8 +13119,8 @@ var ts; function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } - function checkTypeAssignableTo(source, target, errorNode, headMessage) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target) { var sourceType = getOrCreateTypeFromSignature(source); @@ -14487,9 +14505,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; getNodeLinks(node).flags |= 2; if (container.kind === 134 || container.kind === 137) { + var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } else { @@ -14528,9 +14546,8 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; - if (classNode) { - var symbol = getSymbolOfNode(classNode); + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); return container.flags & 128 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); } return anyType; @@ -14545,7 +14562,7 @@ var ts; } function checkSuperExpression(node) { var isCallExpression = node.parent.kind === 160 && node.parent.expression === node; - var classDeclaration = ts.getAncestor(node, 204); + var classDeclaration = ts.getContainingClass(node); var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { @@ -14567,7 +14584,7 @@ var ts; container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } - if (container && container.parent && container.parent.kind === 204) { + if (container && ts.isClassLike(container.parent)) { if (container.flags & 128) { canUseSuperExpression = container.kind === 136 || @@ -15050,7 +15067,7 @@ var ts; if (!(flags & (32 | 64))) { return; } - var enclosingClassDeclaration = ts.getAncestor(node, 204); + var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (flags & 32) { @@ -15228,7 +15245,7 @@ var ts; if (node.kind === 162) { checkExpression(node.template); } - else { + else if (node.kind !== 132) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -15278,7 +15295,8 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 176) { + var arg = args[i]; + if (arg && arg.kind === 176) { return i; } } @@ -15288,6 +15306,8 @@ var ts; var adjustedArgCount; var typeArguments; var callIsIncomplete; + var isDecorator; + var spreadArgIndex = -1; if (node.kind === 162) { var tagExpression = node; adjustedArgCount = args.length; @@ -15304,6 +15324,11 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } + else if (node.kind === 132) { + isDecorator = true; + typeArguments = undefined; + adjustedArgCount = getEffectiveArgumentCount(node, undefined, signature); + } else { var callExpression = node; if (!callExpression.arguments) { @@ -15313,13 +15338,13 @@ var ts; adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; callIsIncomplete = callExpression.arguments.end === callExpression.end; typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); } var hasRightNumberOfTypeArgs = !typeArguments || (signature.typeParameters && typeArguments.length === signature.typeParameters.length); if (!hasRightNumberOfTypeArgs) { return false; } - var spreadArgIndex = getSpreadArgumentIndex(args); if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } @@ -15346,7 +15371,7 @@ var ts; }); return getSignatureInstantiation(signature, getInferredTypes(context)); } - function inferTypeArguments(signature, args, excludeArgument, context) { + function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; var inferenceMapper = createInferenceMapper(context); for (var i = 0; i < typeParameters.length; i++) { @@ -15357,15 +15382,13 @@ var ts; if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { context.failedTypeParameterIndex = undefined; } - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); - var argType = void 0; - if (i === 0 && args[i].parent.kind === 162) { - argType = globalTemplateStringsArrayType; - } - else { + var argType = getEffectiveArgumentType(node, i, arg); + if (argType === undefined) { var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } @@ -15373,7 +15396,7 @@ var ts; } } if (excludeArgument) { - for (var i = 0; i < args.length; i++) { + for (var i = 0; i < argCount; i++) { if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); @@ -15383,7 +15406,7 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors) { + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; for (var i = 0; i < typeParameters.length; i++) { @@ -15393,23 +15416,33 @@ var ts; if (typeArgumentsAreAssignable) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); } } } return typeArgumentsAreAssignable; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); - var argType = i === 0 && node.kind === 162 - ? globalTemplateStringsArrayType - : arg.kind === 8 && !reportErrors + var argType = getEffectiveArgumentType(node, i, arg); + if (argType === undefined) { + argType = arg.kind === 8 && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - if (!checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1)) { + } + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } } @@ -15420,22 +15453,165 @@ var ts; var args; if (node.kind === 162) { var template = node.template; - args = [template]; + args = [undefined]; if (template.kind === 174) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } + else if (node.kind === 132) { + return undefined; + } else { args = node.arguments || emptyArray; } return args; } - function resolveCall(node, signatures, candidatesOutArray) { + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 132) { + switch (node.parent.kind) { + case 204: + case 177: + return 1; + case 134: + return 2; + case 136: + case 138: + case 139: + return signature.parameters.length >= 3 ? 3 : 2; + case 131: + return 3; + } + } + else { + return args.length; + } + } + function getEffectiveDecoratorFirstArgumentType(node) { + switch (node.kind) { + case 204: + case 177: + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + case 131: + node = node.parent; + if (node.kind === 137) { + var classSymbol_1 = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol_1); + } + case 134: + case 136: + case 138: + case 139: + return getParentTypeOfClassElement(node); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + function getEffectiveDecoratorSecondArgumentType(node) { + switch (node.kind) { + case 204: + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + case 131: + node = node.parent; + if (node.kind === 137) { + return anyType; + } + case 134: + case 136: + case 138: + case 139: + var element = node; + switch (element.name.kind) { + case 65: + case 7: + case 8: + return getStringLiteralType(element.name); + case 129: + var nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, 2097152)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + function getEffectiveDecoratorThirdArgumentType(node) { + switch (node.kind) { + case 204: + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + case 131: + return numberType; + case 134: + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + case 136: + case 138: + case 139: + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + function getEffectiveArgumentType(node, argIndex, arg) { + if (node.kind === 132) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 162) { + return globalTemplateStringsArrayType; + } + return undefined; + } + function getEffectiveArgument(node, args, argIndex) { + if (node.kind === 132 || + (argIndex === 0 && node.kind === 162)) { + return undefined; + } + return args[argIndex]; + } + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 132) { + return node.expression; + } + else if (argIndex === 0 && node.kind === 162) { + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, headMessage) { var isTaggedTemplate = node.kind === 162; + var isDecorator = node.kind === 132; var typeArguments; - if (!isTaggedTemplate) { + if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; if (node.expression.kind !== 91) { ts.forEach(typeArguments, checkSourceElement); @@ -15444,17 +15620,19 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); var excludeArgument; - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); + if (!isDecorator) { + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; } - excludeArgument[i] = true; } } var candidateForArgumentError; @@ -15477,19 +15655,22 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); + if (!isTaggedTemplate && !isDecorator && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + if (headMessage) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + } reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead); } } else { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } if (!produceDiagnostics) { for (var _i = 0; _i < candidates.length; _i++) { @@ -15500,6 +15681,14 @@ var ts; } } return resolveErrorCall(node); + function reportError(message, arg0, arg1, arg2) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + if (headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + } function chooseOverload(candidates, relation) { for (var _i = 0; _i < candidates.length; _i++) { var originalCandidate = candidates[_i]; @@ -15520,7 +15709,7 @@ var ts; typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { - inferTypeArguments(candidate, args, excludeArgument, inferenceContext); + inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; typeArgumentTypes = inferenceContext.inferredTypes; } @@ -15562,7 +15751,7 @@ var ts; if (node.expression.kind === 91) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getAncestor(node, 204)); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } @@ -15641,6 +15830,41 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 204: + case 177: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 131: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 134: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 136: + case 138: + case 139: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { @@ -15654,6 +15878,9 @@ var ts; else if (node.kind === 162) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } + else if (node.kind === 132) { + links.resolvedSignature = resolveDecorator(node, candidatesOutArray); + } else { ts.Debug.fail("Branch in 'getResolvedSignature' should be unreachable."); } @@ -15869,7 +16096,7 @@ var ts; if (node.type) { checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined); } - checkFunctionExpressionBodies(node.body); + checkFunctionAndClassExpressionBodies(node.body); } } } @@ -16269,7 +16496,7 @@ var ts; if (ts.isFunctionLike(parent) && current === parent.body) { return false; } - else if (current.kind === 204 || current.kind === 177) { + else if (ts.isClassLike(current)) { return true; } current = parent; @@ -17045,29 +17272,37 @@ var ts; } } function checkDecorator(node) { - var expression = node.expression; - var exprType = checkExpression(expression); + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; switch (node.parent.kind) { case 204: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); - var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); - checkTypeAssignableTo(exprType, classDecoratorType, node); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 131: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 134: - checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 136: case 138: case 139: var methodType = getTypeOfNode(node.parent); - var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); - checkTypeAssignableTo(exprType, methodDecoratorType, node); - break; - case 131: - checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); break; } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function checkTypeNodeAsExpression(node) { if (node && node.kind === 144) { @@ -17186,7 +17421,7 @@ var ts; } ts.forEach(node.statements, checkSourceElement); if (ts.isFunctionBlock(node) || node.kind === 209) { - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { @@ -17245,7 +17480,7 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } - var enclosingClass = ts.getAncestor(node, 204); + var enclosingClass = ts.getContainingClass(node); if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; } @@ -17779,7 +18014,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && type.symbol.valueDeclaration.kind === 204) { + if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -17855,14 +18090,17 @@ var ts; } } function checkClassExpression(node) { - grammarErrorOnNode(node, ts.Diagnostics.class_expressions_are_not_currently_supported); - ts.forEach(node.members, checkSourceElement); - return unknownType; + checkClassLikeDeclaration(node); + return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 256)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + } + function checkClassLikeDeclaration(node) { checkGrammarClassDeclarationHeritageClauses(node); checkDecorators(node); if (node.name) { @@ -17923,7 +18161,6 @@ var ts; } }); } - ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -18665,17 +18902,20 @@ var ts; return checkMissingDeclaration(node); } } - function checkFunctionExpressionBodies(node) { + function checkFunctionAndClassExpressionBodies(node) { switch (node.kind) { case 165: case 166: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case 177: + ts.forEach(node.members, checkSourceElement); + break; case 136: case 135: - ts.forEach(node.decorators, checkFunctionExpressionBodies); - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } @@ -18684,10 +18924,10 @@ var ts; case 138: case 139: case 203: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); break; case 195: - checkFunctionExpressionBodies(node.expression); + checkFunctionAndClassExpressionBodies(node.expression); break; case 132: case 131: @@ -18744,7 +18984,7 @@ var ts; case 229: case 217: case 230: - ts.forEachChild(node, checkFunctionExpressionBodies); + ts.forEachChild(node, checkFunctionAndClassExpressionBodies); break; } } @@ -18765,7 +19005,7 @@ var ts; emitParam = false; potentialThisCollisions.length = 0; ts.forEach(node.statements, checkSourceElement); - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); if (ts.isExternalModule(node)) { checkExternalModuleExports(node); } @@ -18838,6 +19078,10 @@ var ts; case 207: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; + case 177: + if (location.name) { + copySymbol(location.symbol, meaning); + } case 204: case 205: if (!(memberFlags & 128)) { @@ -18872,40 +19116,6 @@ var ts; } } } - if (isInsideWithStatementBody(location)) { - return []; - } - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 230: - if (!ts.isExternalModule(location)) - break; - case 208: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); - break; - case 207: - copySymbols(getSymbolOfNode(location).exports, meaning & 8); - break; - case 204: - case 205: - if (!(memberFlags & 128)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056); - } - break; - case 165: - if (location.name) { - copySymbol(location.symbol, meaning); - } - break; - } - memberFlags = location.flags; - location = location.parent; - } - copySymbols(globals, meaning); - return symbolsToArray(symbols); } function isTypeDeclarationName(name) { return name.kind === 65 && @@ -18999,6 +19209,9 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } + if (entityName.parent.kind === 143) { + return resolveEntityName(entityName, 1); + } return undefined; } function getSymbolInfo(node) { @@ -19098,6 +19311,12 @@ var ts; } return checkExpression(expr); } + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return node.flags & 128 + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = createSymbolTable(getPropertiesOfType(type)); @@ -19500,10 +19719,7 @@ var ts; globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - getGlobalClassDecoratorType = ts.memoize(function () { return getGlobalType("ClassDecorator"); }); - getGlobalPropertyDecoratorType = ts.memoize(function () { return getGlobalType("PropertyDecorator"); }); - getGlobalMethodDecoratorType = ts.memoize(function () { return getGlobalType("MethodDecorator"); }); - getGlobalParameterDecoratorType = ts.memoize(function () { return getGlobalType("ParameterDecorator"); }); + getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); if (languageVersion >= 2) { globalTemplateStringsArrayType = getGlobalType("TemplateStringsArray"); globalESSymbolType = getGlobalType("Symbol"); @@ -20045,7 +20261,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 204) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -20276,7 +20492,7 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 204) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { return true; @@ -21826,6 +22042,9 @@ var ts; function generateNameForExportDefault() { return makeUniqueName("default"); } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } function generateNameForNode(node) { switch (node.kind) { case 65: @@ -21838,9 +22057,10 @@ var ts; return generateNameForImportOrExportDeclaration(node); case 203: case 204: - case 177: case 217: return generateNameForExportDefault(); + case 177: + return generateNameForClassExpression(); } } function getGeneratedNameForNode(node) { diff --git a/bin/tsserver.js b/bin/tsserver.js index 2d937e57fad..b9b8ecc2ad1 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -1166,6 +1166,12 @@ var ts; An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An export declaration can only be used in a module." }, An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." }, A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." }, + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." }, + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." }, + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." }, + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." }, + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." }, + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -1541,9 +1547,7 @@ var ts; property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, - decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } + decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." } }; })(ts || (ts = {})); /// @@ -3620,6 +3624,7 @@ var ts; case 208: case 206: case 204: + case 177: return; default: if (isFunctionLike(node)) { @@ -3654,20 +3659,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - if (node) { - switch (node.kind) { - case 138: - case 139: - return true; - } - } - return false; + return node && (node.kind === 138 || node.kind === 139); } ts.isAccessor = isAccessor; function isClassLike(node) { - if (node) { - return node.kind === 204 || node.kind === 177; - } + return node && (node.kind === 204 || node.kind === 177); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -3709,6 +3705,15 @@ var ts; } } ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { while (true) { node = node.parent; @@ -3717,7 +3722,7 @@ var ts; } switch (node.kind) { case 129: - if (node.parent.parent.kind === 204) { + if (isClassLike(node.parent.parent)) { return node; } node = node.parent; @@ -3758,7 +3763,7 @@ var ts; return node; switch (node.kind) { case 129: - if (node.parent.parent.kind === 204) { + if (isClassLike(node.parent.parent)) { return node; } node = node.parent; @@ -4098,6 +4103,7 @@ var ts; case 166: case 155: case 204: + case 177: case 137: case 207: case 229: @@ -4799,7 +4805,7 @@ var ts; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return node.kind === 179 && node.parent.token === 79 && - node.parent.parent.kind === 204; + isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isSupportedExpressionWithTypeArguments(node) { @@ -9701,7 +9707,7 @@ var ts; } } function getStrictModeIdentifierMessage(node) { - if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -9739,7 +9745,7 @@ var ts; } } function getStrictModeEvalOrArgumentsMessage(node) { - if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -9991,7 +9997,7 @@ var ts; } if (node.flags & 112 && node.parent.kind === 137 && - (node.parent.parent.kind === 204 || node.parent.parent.kind === 177)) { + ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } @@ -10105,10 +10111,7 @@ var ts; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; - var getGlobalClassDecoratorType; - var getGlobalParameterDecoratorType; - var getGlobalPropertyDecoratorType; - var getGlobalMethodDecoratorType; + var getGlobalTypedPropertyDescriptorType; var tupleTypes = {}; var unionTypes = {}; var stringLiteralTypes = {}; @@ -10365,7 +10368,7 @@ var ts; break; case 134: case 133: - if (location.parent.kind === 204 && !(location.flags & 128)) { + if (ts.isClassLike(location.parent) && !(location.flags & 128)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -10375,6 +10378,7 @@ var ts; } break; case 204: + case 177: case 205: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 128) { @@ -10383,10 +10387,17 @@ var ts; } break loop; } + if (location.kind === 177 && meaning & 32) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } + } break; case 129: grandparent = location.parent.parent; - if (grandparent.kind === 204 || grandparent.kind === 205) { + if (ts.isClassLike(grandparent) || grandparent.kind === 205) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; @@ -10418,15 +10429,6 @@ var ts; } } break; - case 177: - if (meaning & 32) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; case 132: if (location.parent && location.parent.kind === 131) { location = location.parent; @@ -11127,15 +11129,24 @@ var ts; } var _displayBuilder; function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - if (symbol.declarations && symbol.declarations.length > 0) { + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; if (declaration.name) { - writer.writeSymbol(ts.declarationNameToString(declaration.name), symbol); - return; + return ts.declarationNameToString(declaration.name); + } + switch (declaration.kind) { + case 177: + return "(Anonymous class)"; + case 165: + case 166: + return "(Anonymous function)"; } } - writer.writeSymbol(symbol.name, symbol); + return symbol.name; + } + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); } function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { var parentSymbol; @@ -12051,9 +12062,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 204 || node.kind === 203 || - node.kind === 165 || node.kind === 136 || - node.kind === 166) { + if (node.kind === 204 || node.kind === 177 || + node.kind === 203 || node.kind === 165 || + node.kind === 136 || node.kind === 166) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -12062,14 +12073,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var kind = symbol.flags & 32 ? 204 : 205; - return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 205); + return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 205 || node.kind === 204 || node.kind === 206) { + if (node.kind === 205 || node.kind === 204 || + node.kind === 177 || node.kind === 206) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -13082,6 +13094,12 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + function createTypedPropertyDescriptorType(propertyType) { + var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyObjectType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } function createTypeFromGenericGlobalType(genericGlobalType, elementType) { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; } @@ -13497,8 +13515,8 @@ var ts; function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } - function checkTypeAssignableTo(source, target, errorNode, headMessage) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target) { var sourceType = getOrCreateTypeFromSignature(source); @@ -14883,9 +14901,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; getNodeLinks(node).flags |= 2; if (container.kind === 134 || container.kind === 137) { + var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } else { @@ -14924,9 +14942,8 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; - if (classNode) { - var symbol = getSymbolOfNode(classNode); + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); return container.flags & 128 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); } return anyType; @@ -14941,7 +14958,7 @@ var ts; } function checkSuperExpression(node) { var isCallExpression = node.parent.kind === 160 && node.parent.expression === node; - var classDeclaration = ts.getAncestor(node, 204); + var classDeclaration = ts.getContainingClass(node); var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { @@ -14963,7 +14980,7 @@ var ts; container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } - if (container && container.parent && container.parent.kind === 204) { + if (container && ts.isClassLike(container.parent)) { if (container.flags & 128) { canUseSuperExpression = container.kind === 136 || @@ -15446,7 +15463,7 @@ var ts; if (!(flags & (32 | 64))) { return; } - var enclosingClassDeclaration = ts.getAncestor(node, 204); + var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (flags & 32) { @@ -15624,7 +15641,7 @@ var ts; if (node.kind === 162) { checkExpression(node.template); } - else { + else if (node.kind !== 132) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -15674,7 +15691,8 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 176) { + var arg = args[i]; + if (arg && arg.kind === 176) { return i; } } @@ -15684,6 +15702,8 @@ var ts; var adjustedArgCount; var typeArguments; var callIsIncomplete; + var isDecorator; + var spreadArgIndex = -1; if (node.kind === 162) { var tagExpression = node; adjustedArgCount = args.length; @@ -15700,6 +15720,11 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } + else if (node.kind === 132) { + isDecorator = true; + typeArguments = undefined; + adjustedArgCount = getEffectiveArgumentCount(node, undefined, signature); + } else { var callExpression = node; if (!callExpression.arguments) { @@ -15709,13 +15734,13 @@ var ts; adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; callIsIncomplete = callExpression.arguments.end === callExpression.end; typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); } var hasRightNumberOfTypeArgs = !typeArguments || (signature.typeParameters && typeArguments.length === signature.typeParameters.length); if (!hasRightNumberOfTypeArgs) { return false; } - var spreadArgIndex = getSpreadArgumentIndex(args); if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } @@ -15742,7 +15767,7 @@ var ts; }); return getSignatureInstantiation(signature, getInferredTypes(context)); } - function inferTypeArguments(signature, args, excludeArgument, context) { + function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; var inferenceMapper = createInferenceMapper(context); for (var i = 0; i < typeParameters.length; i++) { @@ -15753,15 +15778,13 @@ var ts; if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { context.failedTypeParameterIndex = undefined; } - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); - var argType = void 0; - if (i === 0 && args[i].parent.kind === 162) { - argType = globalTemplateStringsArrayType; - } - else { + var argType = getEffectiveArgumentType(node, i, arg); + if (argType === undefined) { var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } @@ -15769,7 +15792,7 @@ var ts; } } if (excludeArgument) { - for (var i = 0; i < args.length; i++) { + for (var i = 0; i < argCount; i++) { if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); @@ -15779,7 +15802,7 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors) { + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; for (var i = 0; i < typeParameters.length; i++) { @@ -15789,23 +15812,33 @@ var ts; if (typeArgumentsAreAssignable) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); } } } return typeArgumentsAreAssignable; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); - var argType = i === 0 && node.kind === 162 - ? globalTemplateStringsArrayType - : arg.kind === 8 && !reportErrors + var argType = getEffectiveArgumentType(node, i, arg); + if (argType === undefined) { + argType = arg.kind === 8 && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - if (!checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1)) { + } + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } } @@ -15816,22 +15849,165 @@ var ts; var args; if (node.kind === 162) { var template = node.template; - args = [template]; + args = [undefined]; if (template.kind === 174) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } + else if (node.kind === 132) { + return undefined; + } else { args = node.arguments || emptyArray; } return args; } - function resolveCall(node, signatures, candidatesOutArray) { + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 132) { + switch (node.parent.kind) { + case 204: + case 177: + return 1; + case 134: + return 2; + case 136: + case 138: + case 139: + return signature.parameters.length >= 3 ? 3 : 2; + case 131: + return 3; + } + } + else { + return args.length; + } + } + function getEffectiveDecoratorFirstArgumentType(node) { + switch (node.kind) { + case 204: + case 177: + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + case 131: + node = node.parent; + if (node.kind === 137) { + var classSymbol_1 = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol_1); + } + case 134: + case 136: + case 138: + case 139: + return getParentTypeOfClassElement(node); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + function getEffectiveDecoratorSecondArgumentType(node) { + switch (node.kind) { + case 204: + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + case 131: + node = node.parent; + if (node.kind === 137) { + return anyType; + } + case 134: + case 136: + case 138: + case 139: + var element = node; + switch (element.name.kind) { + case 65: + case 7: + case 8: + return getStringLiteralType(element.name); + case 129: + var nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, 2097152)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + function getEffectiveDecoratorThirdArgumentType(node) { + switch (node.kind) { + case 204: + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + case 131: + return numberType; + case 134: + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + case 136: + case 138: + case 139: + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + function getEffectiveArgumentType(node, argIndex, arg) { + if (node.kind === 132) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 162) { + return globalTemplateStringsArrayType; + } + return undefined; + } + function getEffectiveArgument(node, args, argIndex) { + if (node.kind === 132 || + (argIndex === 0 && node.kind === 162)) { + return undefined; + } + return args[argIndex]; + } + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 132) { + return node.expression; + } + else if (argIndex === 0 && node.kind === 162) { + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, headMessage) { var isTaggedTemplate = node.kind === 162; + var isDecorator = node.kind === 132; var typeArguments; - if (!isTaggedTemplate) { + if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; if (node.expression.kind !== 91) { ts.forEach(typeArguments, checkSourceElement); @@ -15840,17 +16016,19 @@ var ts; var candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates); if (!candidates.length) { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); var excludeArgument; - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); + if (!isDecorator) { + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; } - excludeArgument[i] = true; } } var candidateForArgumentError; @@ -15873,19 +16051,22 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); + if (!isTaggedTemplate && !isDecorator && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + if (headMessage) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + } reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead); } } else { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } if (!produceDiagnostics) { for (var _i = 0; _i < candidates.length; _i++) { @@ -15896,6 +16077,14 @@ var ts; } } return resolveErrorCall(node); + function reportError(message, arg0, arg1, arg2) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + if (headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + } function chooseOverload(candidates, relation) { for (var _i = 0; _i < candidates.length; _i++) { var originalCandidate = candidates[_i]; @@ -15916,7 +16105,7 @@ var ts; typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { - inferTypeArguments(candidate, args, excludeArgument, inferenceContext); + inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; typeArgumentTypes = inferenceContext.inferredTypes; } @@ -15958,7 +16147,7 @@ var ts; if (node.expression.kind === 91) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getAncestor(node, 204)); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } @@ -16037,6 +16226,41 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 204: + case 177: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 131: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 134: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 136: + case 138: + case 139: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { @@ -16050,6 +16274,9 @@ var ts; else if (node.kind === 162) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } + else if (node.kind === 132) { + links.resolvedSignature = resolveDecorator(node, candidatesOutArray); + } else { ts.Debug.fail("Branch in 'getResolvedSignature' should be unreachable."); } @@ -16265,7 +16492,7 @@ var ts; if (node.type) { checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined); } - checkFunctionExpressionBodies(node.body); + checkFunctionAndClassExpressionBodies(node.body); } } } @@ -16665,7 +16892,7 @@ var ts; if (ts.isFunctionLike(parent) && current === parent.body) { return false; } - else if (current.kind === 204 || current.kind === 177) { + else if (ts.isClassLike(current)) { return true; } current = parent; @@ -17441,29 +17668,37 @@ var ts; } } function checkDecorator(node) { - var expression = node.expression; - var exprType = checkExpression(expression); + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; switch (node.parent.kind) { case 204: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); - var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); - checkTypeAssignableTo(exprType, classDecoratorType, node); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 131: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 134: - checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 136: case 138: case 139: var methodType = getTypeOfNode(node.parent); - var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); - checkTypeAssignableTo(exprType, methodDecoratorType, node); - break; - case 131: - checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); break; } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function checkTypeNodeAsExpression(node) { if (node && node.kind === 144) { @@ -17582,7 +17817,7 @@ var ts; } ts.forEach(node.statements, checkSourceElement); if (ts.isFunctionBlock(node) || node.kind === 209) { - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { @@ -17641,7 +17876,7 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } - var enclosingClass = ts.getAncestor(node, 204); + var enclosingClass = ts.getContainingClass(node); if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; } @@ -18175,7 +18410,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && type.symbol.valueDeclaration.kind === 204) { + if (type.flags & 1024 && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -18251,14 +18486,17 @@ var ts; } } function checkClassExpression(node) { - grammarErrorOnNode(node, ts.Diagnostics.class_expressions_are_not_currently_supported); - ts.forEach(node.members, checkSourceElement); - return unknownType; + checkClassLikeDeclaration(node); + return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 256)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + } + function checkClassLikeDeclaration(node) { checkGrammarClassDeclarationHeritageClauses(node); checkDecorators(node); if (node.name) { @@ -18319,7 +18557,6 @@ var ts; } }); } - ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -19061,17 +19298,20 @@ var ts; return checkMissingDeclaration(node); } } - function checkFunctionExpressionBodies(node) { + function checkFunctionAndClassExpressionBodies(node) { switch (node.kind) { case 165: case 166: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case 177: + ts.forEach(node.members, checkSourceElement); + break; case 136: case 135: - ts.forEach(node.decorators, checkFunctionExpressionBodies); - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } @@ -19080,10 +19320,10 @@ var ts; case 138: case 139: case 203: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); break; case 195: - checkFunctionExpressionBodies(node.expression); + checkFunctionAndClassExpressionBodies(node.expression); break; case 132: case 131: @@ -19140,7 +19380,7 @@ var ts; case 229: case 217: case 230: - ts.forEachChild(node, checkFunctionExpressionBodies); + ts.forEachChild(node, checkFunctionAndClassExpressionBodies); break; } } @@ -19161,7 +19401,7 @@ var ts; emitParam = false; potentialThisCollisions.length = 0; ts.forEach(node.statements, checkSourceElement); - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); if (ts.isExternalModule(node)) { checkExternalModuleExports(node); } @@ -19234,6 +19474,10 @@ var ts; case 207: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; + case 177: + if (location.name) { + copySymbol(location.symbol, meaning); + } case 204: case 205: if (!(memberFlags & 128)) { @@ -19268,40 +19512,6 @@ var ts; } } } - if (isInsideWithStatementBody(location)) { - return []; - } - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 230: - if (!ts.isExternalModule(location)) - break; - case 208: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); - break; - case 207: - copySymbols(getSymbolOfNode(location).exports, meaning & 8); - break; - case 204: - case 205: - if (!(memberFlags & 128)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056); - } - break; - case 165: - if (location.name) { - copySymbol(location.symbol, meaning); - } - break; - } - memberFlags = location.flags; - location = location.parent; - } - copySymbols(globals, meaning); - return symbolsToArray(symbols); } function isTypeDeclarationName(name) { return name.kind === 65 && @@ -19395,6 +19605,9 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } + if (entityName.parent.kind === 143) { + return resolveEntityName(entityName, 1); + } return undefined; } function getSymbolInfo(node) { @@ -19494,6 +19707,12 @@ var ts; } return checkExpression(expr); } + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return node.flags & 128 + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = createSymbolTable(getPropertiesOfType(type)); @@ -19896,10 +20115,7 @@ var ts; globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - getGlobalClassDecoratorType = ts.memoize(function () { return getGlobalType("ClassDecorator"); }); - getGlobalPropertyDecoratorType = ts.memoize(function () { return getGlobalType("PropertyDecorator"); }); - getGlobalMethodDecoratorType = ts.memoize(function () { return getGlobalType("MethodDecorator"); }); - getGlobalParameterDecoratorType = ts.memoize(function () { return getGlobalType("ParameterDecorator"); }); + getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); if (languageVersion >= 2) { globalTemplateStringsArrayType = getGlobalType("TemplateStringsArray"); globalESSymbolType = getGlobalType("Symbol"); @@ -20441,7 +20657,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 204) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -20672,7 +20888,7 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 204) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { return true; @@ -22222,6 +22438,9 @@ var ts; function generateNameForExportDefault() { return makeUniqueName("default"); } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } function generateNameForNode(node) { switch (node.kind) { case 65: @@ -22234,9 +22453,10 @@ var ts; return generateNameForImportOrExportDeclaration(node); case 203: case 204: - case 177: case 217: return generateNameForExportDefault(); + case 177: + return generateNameForClassExpression(); } } function getGeneratedNameForNode(node) { @@ -31651,6 +31871,10 @@ var ts; if (actualIndentation !== -1) { return actualIndentation; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1) { + return actualIndentation + options.IndentSize; + } previous = current; current = current.parent; } @@ -31688,6 +31912,10 @@ var ts; if (actualIndentation !== -1) { return actualIndentation + indentationDelta; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1) { + return actualIndentation + indentationDelta; + } } if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; @@ -31804,6 +32032,42 @@ var ts; return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1; } } + function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { + if (node.kind === 17) { + return -1; + } + if (node.parent && (node.parent.kind === 160 || + node.parent.kind === 161) && + node.parent.expression !== node) { + var fullCallOrNewExpression = node.parent.expression; + var startingExpression = getStartingExpression(fullCallOrNewExpression); + if (fullCallOrNewExpression === startingExpression) { + return -1; + } + var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); + var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { + return -1; + } + return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); + } + return -1; + function getStartingExpression(node) { + while (true) { + switch (node.kind) { + case 160: + case 161: + case 158: + case 159: + node = node.expression; + break; + default: + return node; + } + } + return node; + } + } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index 2fd4bb2c2f3..e7637e0bc19 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -600,7 +600,7 @@ declare module "typescript" { tag: LeftHandSideExpression; template: LiteralExpression | TemplateExpression; } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression; + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface TypeAssertion extends UnaryExpression { type: TypeNode; expression: UnaryExpression; diff --git a/bin/typescript.js b/bin/typescript.js index 6989f225452..6373e3f9c58 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -1950,6 +1950,12 @@ var ts; An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An export declaration can only be used in a module." }, An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." }, A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." }, + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." }, + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." }, + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." }, + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." }, + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." }, + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -2325,9 +2331,7 @@ var ts; property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, - decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } + decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." } }; })(ts || (ts = {})); /// @@ -4284,7 +4288,7 @@ var ts; function getStrictModeIdentifierMessage(node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. - if (ts.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -4333,7 +4337,7 @@ var ts; function getStrictModeEvalOrArgumentsMessage(node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. - if (ts.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -4641,7 +4645,7 @@ var ts; // containing class. if (node.flags & 112 /* AccessibilityModifier */ && node.parent.kind === 137 /* Constructor */ && - (node.parent.parent.kind === 204 /* ClassDeclaration */ || node.parent.parent.kind === 177 /* ClassExpression */)) { + ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } @@ -5136,6 +5140,7 @@ var ts; case 208 /* ModuleDeclaration */: case 206 /* TypeAliasDeclaration */: case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -5177,20 +5182,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - if (node) { - switch (node.kind) { - case 138 /* GetAccessor */: - case 139 /* SetAccessor */: - return true; - } - } - return false; + return node && (node.kind === 138 /* GetAccessor */ || node.kind === 139 /* SetAccessor */); } ts.isAccessor = isAccessor; function isClassLike(node) { - if (node) { - return node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */; - } + return node && (node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -5232,6 +5228,15 @@ var ts; } } ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { while (true) { node = node.parent; @@ -5244,7 +5249,7 @@ var ts; // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. - if (node.parent.parent.kind === 204 /* ClassDeclaration */) { + if (isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -5300,7 +5305,7 @@ var ts; // then the computed property is not a 'super' container. // A computed property name in a class needs to be a super container // so that we can error on it. - if (node.parent.parent.kind === 204 /* ClassDeclaration */) { + if (isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -5345,7 +5350,7 @@ var ts; if (node.kind === 162 /* TaggedTemplateExpression */) { return node.tag; } - // Will either be a CallExpression or NewExpression. + // Will either be a CallExpression, NewExpression, or Decorator. return node.expression; } ts.getInvokedExpression = getInvokedExpression; @@ -5658,6 +5663,7 @@ var ts; case 166 /* ArrowFunction */: case 155 /* BindingElement */: case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: case 137 /* Constructor */: case 207 /* EnumDeclaration */: case 229 /* EnumMember */: @@ -6429,7 +6435,7 @@ var ts; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return node.kind === 179 /* ExpressionWithTypeArguments */ && node.parent.token === 79 /* ExtendsKeyword */ && - node.parent.parent.kind === 204 /* ClassDeclaration */; + isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; // Returns false if this heritage clause element's expression contains something unsupported @@ -12210,10 +12216,7 @@ var ts; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; - var getGlobalClassDecoratorType; - var getGlobalParameterDecoratorType; - var getGlobalPropertyDecoratorType; - var getGlobalMethodDecoratorType; + var getGlobalTypedPropertyDescriptorType; var tupleTypes = {}; var unionTypes = {}; var stringLiteralTypes = {}; @@ -12499,7 +12502,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (location.parent.kind === 204 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 128 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -12510,6 +12513,7 @@ var ts; } break; case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: case 205 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 128 /* Static */) { @@ -12521,6 +12525,13 @@ var ts; } break loop; } + if (location.kind === 177 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } + } break; // It is not legal to reference a class's own type parameters from a computed property name that // belongs to the class. For example: @@ -12532,7 +12543,7 @@ var ts; // case 129 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (grandparent.kind === 204 /* ClassDeclaration */ || grandparent.kind === 205 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 205 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -12565,15 +12576,6 @@ var ts; } } break; - case 177 /* ClassExpression */: - if (meaning & 32 /* Class */) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; case 132 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. @@ -13407,19 +13409,28 @@ var ts; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; function getSymbolDisplayBuilder() { + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + if (declaration.name) { + return ts.declarationNameToString(declaration.name); + } + switch (declaration.kind) { + case 177 /* ClassExpression */: + return "(Anonymous class)"; + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + return "(Anonymous function)"; + } + } + return symbol.name; + } /** * Writes only the name of the symbol out to the writer. Uses the original source text * for the name of the symbol if it is available to match how the user inputted the name. */ function appendSymbolNameOnly(symbol, writer) { - if (symbol.declarations && symbol.declarations.length > 0) { - var declaration = symbol.declarations[0]; - if (declaration.name) { - writer.writeSymbol(ts.declarationNameToString(declaration.name), symbol); - return; - } - } - writer.writeSymbol(symbol.name, symbol); + writer.writeSymbol(getNameOfSymbol(symbol), symbol); } /** * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope @@ -14488,9 +14499,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 204 /* ClassDeclaration */ || node.kind === 203 /* FunctionDeclaration */ || - node.kind === 165 /* FunctionExpression */ || node.kind === 136 /* MethodDeclaration */ || - node.kind === 166 /* ArrowFunction */) { + if (node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */ || + node.kind === 203 /* FunctionDeclaration */ || node.kind === 165 /* FunctionExpression */ || + node.kind === 136 /* MethodDeclaration */ || node.kind === 166 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -14500,8 +14511,8 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var kind = symbol.flags & 32 /* Class */ ? 204 /* ClassDeclaration */ : 205 /* InterfaceDeclaration */; - return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 205 /* InterfaceDeclaration */); + return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. @@ -14509,7 +14520,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 205 /* InterfaceDeclaration */ || node.kind === 204 /* ClassDeclaration */ || node.kind === 206 /* TypeAliasDeclaration */) { + if (node.kind === 205 /* InterfaceDeclaration */ || node.kind === 204 /* ClassDeclaration */ || + node.kind === 177 /* ClassExpression */ || node.kind === 206 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -15604,6 +15616,15 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + /** + * Creates a TypeReference for a generic `TypedPropertyDescriptor`. + */ + function createTypedPropertyDescriptorType(propertyType) { + var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyObjectType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -16042,8 +16063,8 @@ var ts; function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } - function checkTypeAssignableTo(source, target, errorNode, headMessage) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target) { var sourceType = getOrCreateTypeFromSignature(source); @@ -17582,9 +17603,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; getNodeLinks(node).flags |= 2 /* LexicalThis */; if (container.kind === 134 /* PropertyDeclaration */ || container.kind === 137 /* Constructor */) { + var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } else { @@ -17629,9 +17650,8 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; - if (classNode) { - var symbol = getSymbolOfNode(classNode); + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); } return anyType; @@ -17646,7 +17666,7 @@ var ts; } function checkSuperExpression(node) { var isCallExpression = node.parent.kind === 160 /* CallExpression */ && node.parent.expression === node; - var classDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); + var classDeclaration = ts.getContainingClass(node); var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { @@ -17676,7 +17696,7 @@ var ts; needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } // topmost container must be something that is directly nested in the class declaration - if (container && container.parent && container.parent.kind === 204 /* ClassDeclaration */) { + if (container && ts.isClassLike(container.parent)) { if (container.flags & 128 /* Static */) { canUseSuperExpression = container.kind === 136 /* MethodDeclaration */ || @@ -18276,7 +18296,7 @@ var ts; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - var enclosingClassDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); + var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); // Private property is accessible if declaring and enclosing class are the same @@ -18502,7 +18522,7 @@ var ts; if (node.kind === 162 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else { + else if (node.kind !== 132 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -18567,7 +18587,8 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 176 /* SpreadElementExpression */) { + var arg = args[i]; + if (arg && arg.kind === 176 /* SpreadElementExpression */) { return i; } } @@ -18577,6 +18598,8 @@ var ts; var adjustedArgCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var isDecorator; + var spreadArgIndex = -1; if (node.kind === 162 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, @@ -18600,6 +18623,11 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } + else if (node.kind === 132 /* Decorator */) { + isDecorator = true; + typeArguments = undefined; + adjustedArgCount = getEffectiveArgumentCount(node, undefined, signature); + } else { var callExpression = node; if (!callExpression.arguments) { @@ -18612,6 +18640,7 @@ var ts; // If we are missing the close paren, the call is incomplete. callIsIncomplete = callExpression.arguments.end === callExpression.end; typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); } // If the user supplied type arguments, but the number of type arguments does not match // the declared number of type parameters, the call has an incorrect arity. @@ -18622,7 +18651,6 @@ var ts; } // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. - var spreadArgIndex = getSpreadArgumentIndex(args); if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } @@ -18654,7 +18682,7 @@ var ts; }); return getSignatureInstantiation(signature, getInferredTypes(context)); } - function inferTypeArguments(signature, args, excludeArgument, context) { + function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; var inferenceMapper = createInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context @@ -18679,15 +18707,16 @@ var ts; } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178 /* OmittedExpression */) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 178 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = void 0; - if (i === 0 && args[i].parent.kind === 162 /* TaggedTemplateExpression */) { - argType = globalTemplateStringsArrayType; - } - else { + var argType = getEffectiveArgumentType(node, i, arg); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; @@ -18699,8 +18728,10 @@ var ts; // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { - for (var i = 0; i < args.length; i++) { + for (var i = 0; i < argCount; i++) { // No need to check for omitted args and template expressions, their exlusion value is always undefined if (excludeArgument[i] === false) { var arg = args[i]; @@ -18711,7 +18742,7 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors) { + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; for (var i = 0; i < typeParameters.length; i++) { @@ -18722,27 +18753,38 @@ var ts; if (typeArgumentsAreAssignable /* so far */) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); } } } return typeArgumentsAreAssignable; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178 /* OmittedExpression */) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 178 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); - // A tagged template expression provides a special first argument, and string literals get string literal types - // unless we're reporting errors - var argType = i === 0 && node.kind === 162 /* TaggedTemplateExpression */ - ? globalTemplateStringsArrayType - : arg.kind === 8 /* StringLiteral */ && !reportErrors + var argType = getEffectiveArgumentType(node, i, arg); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + argType = arg.kind === 8 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + } // Use argument expression as error location when reporting errors - if (!checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1)) { + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } } @@ -18754,28 +18796,276 @@ var ts; * * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is the template for error reporting purposes. + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { var args; if (node.kind === 162 /* TaggedTemplateExpression */) { var template = node.template; - args = [template]; + args = [undefined]; if (template.kind === 174 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } + else if (node.kind === 132 /* Decorator */) { + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. + return undefined; + } else { args = node.arguments || emptyArray; } return args; } - function resolveCall(node, signatures, candidatesOutArray) { + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 132 /* Decorator */) { + switch (node.parent.kind) { + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + return 1; + case 134 /* PropertyDeclaration */: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + return 2; + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. + return signature.parameters.length >= 3 ? 3 : 2; + case 131 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + return 3; + } + } + else { + return args.length; + } + } + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ + function getEffectiveDecoratorFirstArgumentType(node) { + // The first argument to a decorator is its `target`. + switch (node.kind) { + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + case 131 /* Parameter */: + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + node = node.parent; + if (node.kind === 137 /* Constructor */) { + var classSymbol_1 = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol_1); + } + // fall-through + case 134 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getParentTypeOfClassElement(node); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ + function getEffectiveDecoratorSecondArgumentType(node) { + // The second argument to a decorator is its `propertyKey` + switch (node.kind) { + case 204 /* ClassDeclaration */: + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + case 131 /* Parameter */: + node = node.parent; + if (node.kind === 137 /* Constructor */) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + // fall-through + case 134 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + var element = node; + switch (element.name.kind) { + case 65 /* Identifier */: + case 7 /* NumericLiteral */: + case 8 /* StringLiteral */: + return getStringLiteralType(element.name); + case 129 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, 2097152 /* ESSymbol */)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ + function getEffectiveDecoratorThirdArgumentType(node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a paramter decorator + switch (node.kind) { + case 204 /* ClassDeclaration */: + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + case 131 /* Parameter */: + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + case 134 /* PropertyDeclaration */: + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + /** + * Returns the effective argument type for the provided argument to a decorator. + */ + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + /** + * Gets the effective argument type for an argument in a call expression. + */ + function getEffectiveArgumentType(node, argIndex, arg) { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === 132 /* Decorator */) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 162 /* TaggedTemplateExpression */) { + return globalTemplateStringsArrayType; + } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. + return undefined; + } + /** + * Gets the effective argument expression for an argument in a call expression. + */ + function getEffectiveArgument(node, args, argIndex) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === 132 /* Decorator */ || + (argIndex === 0 && node.kind === 162 /* TaggedTemplateExpression */)) { + return undefined; + } + return args[argIndex]; + } + /** + * Gets the error node to use when reporting errors for an effective argument. + */ + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 132 /* Decorator */) { + // For a decorator, we use the expression of the decorator for error reporting. + return node.expression; + } + else if (argIndex === 0 && node.kind === 162 /* TaggedTemplateExpression */) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, headMessage) { var isTaggedTemplate = node.kind === 162 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 132 /* Decorator */; var typeArguments; - if (!isTaggedTemplate) { + if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (node.expression.kind !== 91 /* SuperKeyword */) { @@ -18786,7 +19076,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -18801,13 +19091,20 @@ var ts; // // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. var excludeArgument; - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); + if (!isDecorator) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; } - excludeArgument[i] = true; } } // The following variables are captured and modified by calls to chooseOverload. @@ -18871,19 +19168,22 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); + if (!isTaggedTemplate && !isDecorator && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + if (headMessage) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + } reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead); } } else { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information that anySignature. @@ -18899,6 +19199,14 @@ var ts; } } return resolveErrorCall(node); + function reportError(message, arg0, arg1, arg2) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + if (headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + } function chooseOverload(candidates, relation) { for (var _i = 0; _i < candidates.length; _i++) { var originalCandidate = candidates[_i]; @@ -18919,7 +19227,7 @@ var ts; typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { - inferTypeArguments(candidate, args, excludeArgument, inferenceContext); + inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; typeArgumentTypes = inferenceContext.inferredTypes; } @@ -18968,7 +19276,7 @@ var ts; if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getAncestor(node, 204 /* ClassDeclaration */)); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } @@ -19082,6 +19390,47 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 131 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 134 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } // candidatesOutArray is passed by signature help in the language service, and collectCandidates // must fill it up with the appropriate candidate signatures function getResolvedSignature(node, candidatesOutArray) { @@ -19101,6 +19450,9 @@ var ts; else if (node.kind === 162 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } + else if (node.kind === 132 /* Decorator */) { + links.resolvedSignature = resolveDecorator(node, candidatesOutArray); + } else { ts.Debug.fail("Branch in 'getResolvedSignature' should be unreachable."); } @@ -19343,7 +19695,7 @@ var ts; if (node.type) { checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined); } - checkFunctionExpressionBodies(node.body); + checkFunctionAndClassExpressionBodies(node.body); } } } @@ -19807,7 +20159,7 @@ var ts; if (ts.isFunctionLike(parent) && current === parent.body) { return false; } - else if (current.kind === 204 /* ClassDeclaration */ || current.kind === 177 /* ClassExpression */) { + else if (ts.isClassLike(current)) { return true; } current = parent; @@ -20707,29 +21059,37 @@ var ts; } /** Check a decorator */ function checkDecorator(node) { - var expression = node.expression; - var exprType = checkExpression(expression); + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; switch (node.parent.kind) { case 204 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); - var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); - checkTypeAssignableTo(exprType, classDecoratorType, node); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 131 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 134 /* PropertyDeclaration */: - checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 136 /* MethodDeclaration */: case 138 /* GetAccessor */: case 139 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); - var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); - checkTypeAssignableTo(exprType, methodDecoratorType, node); - break; - case 131 /* Parameter */: - checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); break; } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } /** Checks a type reference node as an expression. */ function checkTypeNodeAsExpression(node) { @@ -20880,7 +21240,7 @@ var ts; } ts.forEach(node.statements, checkSourceElement); if (ts.isFunctionBlock(node) || node.kind === 209 /* ModuleBlock */) { - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { @@ -20945,7 +21305,7 @@ var ts; return; } // bubble up and find containing type - var enclosingClass = ts.getAncestor(node, 204 /* ClassDeclaration */); + var enclosingClass = ts.getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; @@ -21650,7 +22010,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 204 /* ClassDeclaration */) { + if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -21739,15 +22099,17 @@ var ts; } } function checkClassExpression(node) { - grammarErrorOnNode(node, ts.Diagnostics.class_expressions_are_not_currently_supported); - ts.forEach(node.members, checkSourceElement); - return unknownType; + checkClassLikeDeclaration(node); + return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { - // Grammar checking if (!node.name && !(node.flags & 256 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + } + function checkClassLikeDeclaration(node) { checkGrammarClassDeclarationHeritageClauses(node); checkDecorators(node); if (node.name) { @@ -21812,7 +22174,6 @@ var ts; } }); } - ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -22608,8 +22969,8 @@ var ts; return checkMissingDeclaration(node); } } - // Function expression bodies are checked after all statements in the enclosing body. This is to ensure - // constructs like the following are permitted: + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: // let foo = function () { // let s = foo(); // return "hello"; @@ -22617,17 +22978,20 @@ var ts; // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionExpressionBodies(node) { + function checkFunctionAndClassExpressionBodies(node) { switch (node.kind) { case 165 /* FunctionExpression */: case 166 /* ArrowFunction */: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case 177 /* ClassExpression */: + ts.forEach(node.members, checkSourceElement); + break; case 136 /* MethodDeclaration */: case 135 /* MethodSignature */: - ts.forEach(node.decorators, checkFunctionExpressionBodies); - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } @@ -22636,10 +23000,10 @@ var ts; case 138 /* GetAccessor */: case 139 /* SetAccessor */: case 203 /* FunctionDeclaration */: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); break; case 195 /* WithStatement */: - checkFunctionExpressionBodies(node.expression); + checkFunctionAndClassExpressionBodies(node.expression); break; case 132 /* Decorator */: case 131 /* Parameter */: @@ -22696,7 +23060,7 @@ var ts; case 229 /* EnumMember */: case 217 /* ExportAssignment */: case 230 /* SourceFile */: - ts.forEachChild(node, checkFunctionExpressionBodies); + ts.forEachChild(node, checkFunctionAndClassExpressionBodies); break; } } @@ -22721,7 +23085,7 @@ var ts; emitParam = false; potentialThisCollisions.length = 0; ts.forEach(node.statements, checkSourceElement); - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); if (ts.isExternalModule(node)) { checkExternalModuleExports(node); } @@ -22796,6 +23160,11 @@ var ts; case 207 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; + case 177 /* ClassExpression */: + if (location.name) { + copySymbol(location.symbol, meaning); + } + // Fall through case 204 /* ClassDeclaration */: case 205 /* InterfaceDeclaration */: if (!(memberFlags & 128 /* Static */)) { @@ -22831,41 +23200,6 @@ var ts; } } } - if (isInsideWithStatementBody(location)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return []; - } - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 230 /* SourceFile */: - if (!ts.isExternalModule(location)) - break; - case 208 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); - break; - case 207 /* EnumDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); - break; - case 204 /* ClassDeclaration */: - case 205 /* InterfaceDeclaration */: - if (!(memberFlags & 128 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); - } - break; - case 165 /* FunctionExpression */: - if (location.name) { - copySymbol(location.symbol, meaning); - } - break; - } - memberFlags = location.flags; - location = location.parent; - } - copySymbols(globals, meaning); - return symbolsToArray(symbols); } function isTypeDeclarationName(name) { return name.kind === 65 /* Identifier */ && @@ -22967,6 +23301,9 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } + if (entityName.parent.kind === 143 /* TypePredicate */) { + return resolveEntityName(entityName, 1 /* FunctionScopedVariable */); + } // Do we want to return undefined here? return undefined; } @@ -23081,6 +23418,16 @@ var ts; } return checkExpression(expr); } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return node.flags & 128 /* Static */ + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -23566,10 +23913,7 @@ var ts; globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - getGlobalClassDecoratorType = ts.memoize(function () { return getGlobalType("ClassDecorator"); }); - getGlobalPropertyDecoratorType = ts.memoize(function () { return getGlobalType("PropertyDecorator"); }); - getGlobalMethodDecoratorType = ts.memoize(function () { return getGlobalType("MethodDecorator"); }); - getGlobalParameterDecoratorType = ts.memoize(function () { return getGlobalType("ParameterDecorator"); }); + getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); // If we're in ES6 mode, load the TemplateStringsArray. // Otherwise, default to 'unknown' for the purposes of type checking in LS scenarios. if (languageVersion >= 2 /* ES6 */) { @@ -24132,7 +24476,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 204 /* ClassDeclaration */) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -24390,7 +24734,7 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 204 /* ClassDeclaration */) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { return true; @@ -26121,6 +26465,9 @@ var ts; function generateNameForExportDefault() { return makeUniqueName("default"); } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } function generateNameForNode(node) { switch (node.kind) { case 65 /* Identifier */: @@ -26133,9 +26480,10 @@ var ts; return generateNameForImportOrExportDeclaration(node); case 203 /* FunctionDeclaration */: case 204 /* ClassDeclaration */: - case 177 /* ClassExpression */: case 217 /* ExportAssignment */: return generateNameForExportDefault(); + case 177 /* ClassExpression */: + return generateNameForClassExpression(); } } function getGeneratedNameForNode(node) { @@ -37159,6 +37507,10 @@ var ts; if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + options.IndentSize; + } previous = current; current = current.parent; } @@ -37201,6 +37553,10 @@ var ts; if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { @@ -37338,6 +37694,44 @@ var ts; return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; } } + function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { + // actual indentation should not be used when: + // - node is close parenthesis - this is the end of the expression + if (node.kind === 17 /* CloseParenToken */) { + return -1 /* Unknown */; + } + if (node.parent && (node.parent.kind === 160 /* CallExpression */ || + node.parent.kind === 161 /* NewExpression */) && + node.parent.expression !== node) { + var fullCallOrNewExpression = node.parent.expression; + var startingExpression = getStartingExpression(fullCallOrNewExpression); + if (fullCallOrNewExpression === startingExpression) { + return -1 /* Unknown */; + } + var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); + var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); + } + return -1 /* Unknown */; + function getStartingExpression(node) { + while (true) { + switch (node.kind) { + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + node = node.expression; + break; + default: + return node; + } + } + return node; + } + } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index da6d55bfd80..70e4f42e1ef 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -600,7 +600,7 @@ declare namespace ts { tag: LeftHandSideExpression; template: LiteralExpression | TemplateExpression; } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression; + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface TypeAssertion extends UnaryExpression { type: TypeNode; expression: UnaryExpression; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 6989f225452..6373e3f9c58 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -1950,6 +1950,12 @@ var ts; An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An export declaration can only be used in a module." }, An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." }, A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." }, + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." }, + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." }, + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." }, + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." }, + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." }, + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -2325,9 +2331,7 @@ var ts; property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, - decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } + decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." } }; })(ts || (ts = {})); /// @@ -4284,7 +4288,7 @@ var ts; function getStrictModeIdentifierMessage(node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. - if (ts.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -4333,7 +4337,7 @@ var ts; function getStrictModeEvalOrArgumentsMessage(node) { // Provide specialized messages to help the user understand why we think they're in // strict mode. - if (ts.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + if (ts.getContainingClass(node)) { return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; } if (file.externalModuleIndicator) { @@ -4641,7 +4645,7 @@ var ts; // containing class. if (node.flags & 112 /* AccessibilityModifier */ && node.parent.kind === 137 /* Constructor */ && - (node.parent.parent.kind === 204 /* ClassDeclaration */ || node.parent.parent.kind === 177 /* ClassExpression */)) { + ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } @@ -5136,6 +5140,7 @@ var ts; case 208 /* ModuleDeclaration */: case 206 /* TypeAliasDeclaration */: case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -5177,20 +5182,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - if (node) { - switch (node.kind) { - case 138 /* GetAccessor */: - case 139 /* SetAccessor */: - return true; - } - } - return false; + return node && (node.kind === 138 /* GetAccessor */ || node.kind === 139 /* SetAccessor */); } ts.isAccessor = isAccessor; function isClassLike(node) { - if (node) { - return node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */; - } + return node && (node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -5232,6 +5228,15 @@ var ts; } } ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { while (true) { node = node.parent; @@ -5244,7 +5249,7 @@ var ts; // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. - if (node.parent.parent.kind === 204 /* ClassDeclaration */) { + if (isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -5300,7 +5305,7 @@ var ts; // then the computed property is not a 'super' container. // A computed property name in a class needs to be a super container // so that we can error on it. - if (node.parent.parent.kind === 204 /* ClassDeclaration */) { + if (isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -5345,7 +5350,7 @@ var ts; if (node.kind === 162 /* TaggedTemplateExpression */) { return node.tag; } - // Will either be a CallExpression or NewExpression. + // Will either be a CallExpression, NewExpression, or Decorator. return node.expression; } ts.getInvokedExpression = getInvokedExpression; @@ -5658,6 +5663,7 @@ var ts; case 166 /* ArrowFunction */: case 155 /* BindingElement */: case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: case 137 /* Constructor */: case 207 /* EnumDeclaration */: case 229 /* EnumMember */: @@ -6429,7 +6435,7 @@ var ts; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { return node.kind === 179 /* ExpressionWithTypeArguments */ && node.parent.token === 79 /* ExtendsKeyword */ && - node.parent.parent.kind === 204 /* ClassDeclaration */; + isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; // Returns false if this heritage clause element's expression contains something unsupported @@ -12210,10 +12216,7 @@ var ts; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; - var getGlobalClassDecoratorType; - var getGlobalParameterDecoratorType; - var getGlobalPropertyDecoratorType; - var getGlobalMethodDecoratorType; + var getGlobalTypedPropertyDescriptorType; var tupleTypes = {}; var unionTypes = {}; var stringLiteralTypes = {}; @@ -12499,7 +12502,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (location.parent.kind === 204 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 128 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -12510,6 +12513,7 @@ var ts; } break; case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: case 205 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 128 /* Static */) { @@ -12521,6 +12525,13 @@ var ts; } break loop; } + if (location.kind === 177 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } + } break; // It is not legal to reference a class's own type parameters from a computed property name that // belongs to the class. For example: @@ -12532,7 +12543,7 @@ var ts; // case 129 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (grandparent.kind === 204 /* ClassDeclaration */ || grandparent.kind === 205 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 205 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -12565,15 +12576,6 @@ var ts; } } break; - case 177 /* ClassExpression */: - if (meaning & 32 /* Class */) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; case 132 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. @@ -13407,19 +13409,28 @@ var ts; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; function getSymbolDisplayBuilder() { + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + if (declaration.name) { + return ts.declarationNameToString(declaration.name); + } + switch (declaration.kind) { + case 177 /* ClassExpression */: + return "(Anonymous class)"; + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + return "(Anonymous function)"; + } + } + return symbol.name; + } /** * Writes only the name of the symbol out to the writer. Uses the original source text * for the name of the symbol if it is available to match how the user inputted the name. */ function appendSymbolNameOnly(symbol, writer) { - if (symbol.declarations && symbol.declarations.length > 0) { - var declaration = symbol.declarations[0]; - if (declaration.name) { - writer.writeSymbol(ts.declarationNameToString(declaration.name), symbol); - return; - } - } - writer.writeSymbol(symbol.name, symbol); + writer.writeSymbol(getNameOfSymbol(symbol), symbol); } /** * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope @@ -14488,9 +14499,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 204 /* ClassDeclaration */ || node.kind === 203 /* FunctionDeclaration */ || - node.kind === 165 /* FunctionExpression */ || node.kind === 136 /* MethodDeclaration */ || - node.kind === 166 /* ArrowFunction */) { + if (node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */ || + node.kind === 203 /* FunctionDeclaration */ || node.kind === 165 /* FunctionExpression */ || + node.kind === 136 /* MethodDeclaration */ || node.kind === 166 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -14500,8 +14511,8 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var kind = symbol.flags & 32 /* Class */ ? 204 /* ClassDeclaration */ : 205 /* InterfaceDeclaration */; - return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 205 /* InterfaceDeclaration */); + return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. @@ -14509,7 +14520,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 205 /* InterfaceDeclaration */ || node.kind === 204 /* ClassDeclaration */ || node.kind === 206 /* TypeAliasDeclaration */) { + if (node.kind === 205 /* InterfaceDeclaration */ || node.kind === 204 /* ClassDeclaration */ || + node.kind === 177 /* ClassExpression */ || node.kind === 206 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -15604,6 +15616,15 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + /** + * Creates a TypeReference for a generic `TypedPropertyDescriptor`. + */ + function createTypedPropertyDescriptorType(propertyType) { + var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyObjectType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -16042,8 +16063,8 @@ var ts; function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } - function checkTypeAssignableTo(source, target, errorNode, headMessage) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target) { var sourceType = getOrCreateTypeFromSignature(source); @@ -17582,9 +17603,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; getNodeLinks(node).flags |= 2 /* LexicalThis */; if (container.kind === 134 /* PropertyDeclaration */ || container.kind === 137 /* Constructor */) { + var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } else { @@ -17629,9 +17650,8 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; - if (classNode) { - var symbol = getSymbolOfNode(classNode); + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); } return anyType; @@ -17646,7 +17666,7 @@ var ts; } function checkSuperExpression(node) { var isCallExpression = node.parent.kind === 160 /* CallExpression */ && node.parent.expression === node; - var classDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); + var classDeclaration = ts.getContainingClass(node); var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { @@ -17676,7 +17696,7 @@ var ts; needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } // topmost container must be something that is directly nested in the class declaration - if (container && container.parent && container.parent.kind === 204 /* ClassDeclaration */) { + if (container && ts.isClassLike(container.parent)) { if (container.flags & 128 /* Static */) { canUseSuperExpression = container.kind === 136 /* MethodDeclaration */ || @@ -18276,7 +18296,7 @@ var ts; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - var enclosingClassDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); + var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); // Private property is accessible if declaring and enclosing class are the same @@ -18502,7 +18522,7 @@ var ts; if (node.kind === 162 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else { + else if (node.kind !== 132 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -18567,7 +18587,8 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 176 /* SpreadElementExpression */) { + var arg = args[i]; + if (arg && arg.kind === 176 /* SpreadElementExpression */) { return i; } } @@ -18577,6 +18598,8 @@ var ts; var adjustedArgCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var isDecorator; + var spreadArgIndex = -1; if (node.kind === 162 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, @@ -18600,6 +18623,11 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } + else if (node.kind === 132 /* Decorator */) { + isDecorator = true; + typeArguments = undefined; + adjustedArgCount = getEffectiveArgumentCount(node, undefined, signature); + } else { var callExpression = node; if (!callExpression.arguments) { @@ -18612,6 +18640,7 @@ var ts; // If we are missing the close paren, the call is incomplete. callIsIncomplete = callExpression.arguments.end === callExpression.end; typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); } // If the user supplied type arguments, but the number of type arguments does not match // the declared number of type parameters, the call has an incorrect arity. @@ -18622,7 +18651,6 @@ var ts; } // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. - var spreadArgIndex = getSpreadArgumentIndex(args); if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } @@ -18654,7 +18682,7 @@ var ts; }); return getSignatureInstantiation(signature, getInferredTypes(context)); } - function inferTypeArguments(signature, args, excludeArgument, context) { + function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; var inferenceMapper = createInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context @@ -18679,15 +18707,16 @@ var ts; } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178 /* OmittedExpression */) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 178 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = void 0; - if (i === 0 && args[i].parent.kind === 162 /* TaggedTemplateExpression */) { - argType = globalTemplateStringsArrayType; - } - else { + var argType = getEffectiveArgumentType(node, i, arg); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; @@ -18699,8 +18728,10 @@ var ts; // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { - for (var i = 0; i < args.length; i++) { + for (var i = 0; i < argCount; i++) { // No need to check for omitted args and template expressions, their exlusion value is always undefined if (excludeArgument[i] === false) { var arg = args[i]; @@ -18711,7 +18742,7 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors) { + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; for (var i = 0; i < typeParameters.length; i++) { @@ -18722,27 +18753,38 @@ var ts; if (typeArgumentsAreAssignable /* so far */) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); } } } return typeArgumentsAreAssignable; } function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg.kind !== 178 /* OmittedExpression */) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 178 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); - // A tagged template expression provides a special first argument, and string literals get string literal types - // unless we're reporting errors - var argType = i === 0 && node.kind === 162 /* TaggedTemplateExpression */ - ? globalTemplateStringsArrayType - : arg.kind === 8 /* StringLiteral */ && !reportErrors + var argType = getEffectiveArgumentType(node, i, arg); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + argType = arg.kind === 8 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + } // Use argument expression as error location when reporting errors - if (!checkTypeRelatedTo(argType, paramType, relation, reportErrors ? arg : undefined, ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1)) { + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } } @@ -18754,28 +18796,276 @@ var ts; * * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is the template for error reporting purposes. + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { var args; if (node.kind === 162 /* TaggedTemplateExpression */) { var template = node.template; - args = [template]; + args = [undefined]; if (template.kind === 174 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } + else if (node.kind === 132 /* Decorator */) { + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. + return undefined; + } else { args = node.arguments || emptyArray; } return args; } - function resolveCall(node, signatures, candidatesOutArray) { + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 132 /* Decorator */) { + switch (node.parent.kind) { + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + return 1; + case 134 /* PropertyDeclaration */: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + return 2; + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. + return signature.parameters.length >= 3 ? 3 : 2; + case 131 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + return 3; + } + } + else { + return args.length; + } + } + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ + function getEffectiveDecoratorFirstArgumentType(node) { + // The first argument to a decorator is its `target`. + switch (node.kind) { + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + case 131 /* Parameter */: + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + node = node.parent; + if (node.kind === 137 /* Constructor */) { + var classSymbol_1 = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol_1); + } + // fall-through + case 134 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getParentTypeOfClassElement(node); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ + function getEffectiveDecoratorSecondArgumentType(node) { + // The second argument to a decorator is its `propertyKey` + switch (node.kind) { + case 204 /* ClassDeclaration */: + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + case 131 /* Parameter */: + node = node.parent; + if (node.kind === 137 /* Constructor */) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + // fall-through + case 134 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + var element = node; + switch (element.name.kind) { + case 65 /* Identifier */: + case 7 /* NumericLiteral */: + case 8 /* StringLiteral */: + return getStringLiteralType(element.name); + case 129 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, 2097152 /* ESSymbol */)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ + function getEffectiveDecoratorThirdArgumentType(node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a paramter decorator + switch (node.kind) { + case 204 /* ClassDeclaration */: + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + case 131 /* Parameter */: + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + case 134 /* PropertyDeclaration */: + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + default: + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + } + /** + * Returns the effective argument type for the provided argument to a decorator. + */ + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + /** + * Gets the effective argument type for an argument in a call expression. + */ + function getEffectiveArgumentType(node, argIndex, arg) { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === 132 /* Decorator */) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 162 /* TaggedTemplateExpression */) { + return globalTemplateStringsArrayType; + } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. + return undefined; + } + /** + * Gets the effective argument expression for an argument in a call expression. + */ + function getEffectiveArgument(node, args, argIndex) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === 132 /* Decorator */ || + (argIndex === 0 && node.kind === 162 /* TaggedTemplateExpression */)) { + return undefined; + } + return args[argIndex]; + } + /** + * Gets the error node to use when reporting errors for an effective argument. + */ + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 132 /* Decorator */) { + // For a decorator, we use the expression of the decorator for error reporting. + return node.expression; + } + else if (argIndex === 0 && node.kind === 162 /* TaggedTemplateExpression */) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, headMessage) { var isTaggedTemplate = node.kind === 162 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 132 /* Decorator */; var typeArguments; - if (!isTaggedTemplate) { + if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (node.expression.kind !== 91 /* SuperKeyword */) { @@ -18786,7 +19076,7 @@ var ts; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); @@ -18801,13 +19091,20 @@ var ts; // // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. var excludeArgument; - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); + if (!isDecorator) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; } - excludeArgument[i] = true; } } // The following variables are captured and modified by calls to chooseOverload. @@ -18871,19 +19168,22 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); + if (!isTaggedTemplate && !isDecorator && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + if (headMessage) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + } reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead); } } else { - error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information that anySignature. @@ -18899,6 +19199,14 @@ var ts; } } return resolveErrorCall(node); + function reportError(message, arg0, arg1, arg2) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + if (headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + } function chooseOverload(candidates, relation) { for (var _i = 0; _i < candidates.length; _i++) { var originalCandidate = candidates[_i]; @@ -18919,7 +19227,7 @@ var ts; typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { - inferTypeArguments(candidate, args, excludeArgument, inferenceContext); + inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; typeArgumentTypes = inferenceContext.inferredTypes; } @@ -18968,7 +19276,7 @@ var ts; if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getAncestor(node, 204 /* ClassDeclaration */)); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } @@ -19082,6 +19390,47 @@ var ts; } return resolveCall(node, callSignatures, candidatesOutArray); } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 131 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 134 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } // candidatesOutArray is passed by signature help in the language service, and collectCandidates // must fill it up with the appropriate candidate signatures function getResolvedSignature(node, candidatesOutArray) { @@ -19101,6 +19450,9 @@ var ts; else if (node.kind === 162 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } + else if (node.kind === 132 /* Decorator */) { + links.resolvedSignature = resolveDecorator(node, candidatesOutArray); + } else { ts.Debug.fail("Branch in 'getResolvedSignature' should be unreachable."); } @@ -19343,7 +19695,7 @@ var ts; if (node.type) { checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, undefined); } - checkFunctionExpressionBodies(node.body); + checkFunctionAndClassExpressionBodies(node.body); } } } @@ -19807,7 +20159,7 @@ var ts; if (ts.isFunctionLike(parent) && current === parent.body) { return false; } - else if (current.kind === 204 /* ClassDeclaration */ || current.kind === 177 /* ClassExpression */) { + else if (ts.isClassLike(current)) { return true; } current = parent; @@ -20707,29 +21059,37 @@ var ts; } /** Check a decorator */ function checkDecorator(node) { - var expression = node.expression; - var exprType = checkExpression(expression); + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; switch (node.parent.kind) { case 204 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); - var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); - checkTypeAssignableTo(exprType, classDecoratorType, node); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 131 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; case 134 /* PropertyDeclaration */: - checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 136 /* MethodDeclaration */: case 138 /* GetAccessor */: case 139 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); - var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); - checkTypeAssignableTo(exprType, methodDecoratorType, node); - break; - case 131 /* Parameter */: - checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); break; } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } /** Checks a type reference node as an expression. */ function checkTypeNodeAsExpression(node) { @@ -20880,7 +21240,7 @@ var ts; } ts.forEach(node.statements, checkSourceElement); if (ts.isFunctionBlock(node) || node.kind === 209 /* ModuleBlock */) { - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { @@ -20945,7 +21305,7 @@ var ts; return; } // bubble up and find containing type - var enclosingClass = ts.getAncestor(node, 204 /* ClassDeclaration */); + var enclosingClass = ts.getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; @@ -21650,7 +22010,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 204 /* ClassDeclaration */) { + if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -21739,15 +22099,17 @@ var ts; } } function checkClassExpression(node) { - grammarErrorOnNode(node, ts.Diagnostics.class_expressions_are_not_currently_supported); - ts.forEach(node.members, checkSourceElement); - return unknownType; + checkClassLikeDeclaration(node); + return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { - // Grammar checking if (!node.name && !(node.flags & 256 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + } + function checkClassLikeDeclaration(node) { checkGrammarClassDeclarationHeritageClauses(node); checkDecorators(node); if (node.name) { @@ -21812,7 +22174,6 @@ var ts; } }); } - ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -22608,8 +22969,8 @@ var ts; return checkMissingDeclaration(node); } } - // Function expression bodies are checked after all statements in the enclosing body. This is to ensure - // constructs like the following are permitted: + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: // let foo = function () { // let s = foo(); // return "hello"; @@ -22617,17 +22978,20 @@ var ts; // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionExpressionBodies(node) { + function checkFunctionAndClassExpressionBodies(node) { switch (node.kind) { case 165 /* FunctionExpression */: case 166 /* ArrowFunction */: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case 177 /* ClassExpression */: + ts.forEach(node.members, checkSourceElement); + break; case 136 /* MethodDeclaration */: case 135 /* MethodSignature */: - ts.forEach(node.decorators, checkFunctionExpressionBodies); - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } @@ -22636,10 +23000,10 @@ var ts; case 138 /* GetAccessor */: case 139 /* SetAccessor */: case 203 /* FunctionDeclaration */: - ts.forEach(node.parameters, checkFunctionExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); break; case 195 /* WithStatement */: - checkFunctionExpressionBodies(node.expression); + checkFunctionAndClassExpressionBodies(node.expression); break; case 132 /* Decorator */: case 131 /* Parameter */: @@ -22696,7 +23060,7 @@ var ts; case 229 /* EnumMember */: case 217 /* ExportAssignment */: case 230 /* SourceFile */: - ts.forEachChild(node, checkFunctionExpressionBodies); + ts.forEachChild(node, checkFunctionAndClassExpressionBodies); break; } } @@ -22721,7 +23085,7 @@ var ts; emitParam = false; potentialThisCollisions.length = 0; ts.forEach(node.statements, checkSourceElement); - checkFunctionExpressionBodies(node); + checkFunctionAndClassExpressionBodies(node); if (ts.isExternalModule(node)) { checkExternalModuleExports(node); } @@ -22796,6 +23160,11 @@ var ts; case 207 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; + case 177 /* ClassExpression */: + if (location.name) { + copySymbol(location.symbol, meaning); + } + // Fall through case 204 /* ClassDeclaration */: case 205 /* InterfaceDeclaration */: if (!(memberFlags & 128 /* Static */)) { @@ -22831,41 +23200,6 @@ var ts; } } } - if (isInsideWithStatementBody(location)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return []; - } - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 230 /* SourceFile */: - if (!ts.isExternalModule(location)) - break; - case 208 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); - break; - case 207 /* EnumDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); - break; - case 204 /* ClassDeclaration */: - case 205 /* InterfaceDeclaration */: - if (!(memberFlags & 128 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); - } - break; - case 165 /* FunctionExpression */: - if (location.name) { - copySymbol(location.symbol, meaning); - } - break; - } - memberFlags = location.flags; - location = location.parent; - } - copySymbols(globals, meaning); - return symbolsToArray(symbols); } function isTypeDeclarationName(name) { return name.kind === 65 /* Identifier */ && @@ -22967,6 +23301,9 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } + if (entityName.parent.kind === 143 /* TypePredicate */) { + return resolveEntityName(entityName, 1 /* FunctionScopedVariable */); + } // Do we want to return undefined here? return undefined; } @@ -23081,6 +23418,16 @@ var ts; } return checkExpression(expr); } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return node.flags & 128 /* Static */ + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { @@ -23566,10 +23913,7 @@ var ts; globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - getGlobalClassDecoratorType = ts.memoize(function () { return getGlobalType("ClassDecorator"); }); - getGlobalPropertyDecoratorType = ts.memoize(function () { return getGlobalType("PropertyDecorator"); }); - getGlobalMethodDecoratorType = ts.memoize(function () { return getGlobalType("MethodDecorator"); }); - getGlobalParameterDecoratorType = ts.memoize(function () { return getGlobalType("ParameterDecorator"); }); + getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", 1); }); // If we're in ES6 mode, load the TemplateStringsArray. // Otherwise, default to 'unknown' for the purposes of type checking in LS scenarios. if (languageVersion >= 2 /* ES6 */) { @@ -24132,7 +24476,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 204 /* ClassDeclaration */) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -24390,7 +24734,7 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 204 /* ClassDeclaration */) { + if (ts.isClassLike(node.parent)) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { return true; @@ -26121,6 +26465,9 @@ var ts; function generateNameForExportDefault() { return makeUniqueName("default"); } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } function generateNameForNode(node) { switch (node.kind) { case 65 /* Identifier */: @@ -26133,9 +26480,10 @@ var ts; return generateNameForImportOrExportDeclaration(node); case 203 /* FunctionDeclaration */: case 204 /* ClassDeclaration */: - case 177 /* ClassExpression */: case 217 /* ExportAssignment */: return generateNameForExportDefault(); + case 177 /* ClassExpression */: + return generateNameForClassExpression(); } } function getGeneratedNameForNode(node) { @@ -37159,6 +37507,10 @@ var ts; if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + options.IndentSize; + } previous = current; current = current.parent; } @@ -37201,6 +37553,10 @@ var ts; if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { @@ -37338,6 +37694,44 @@ var ts; return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; } } + function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { + // actual indentation should not be used when: + // - node is close parenthesis - this is the end of the expression + if (node.kind === 17 /* CloseParenToken */) { + return -1 /* Unknown */; + } + if (node.parent && (node.parent.kind === 160 /* CallExpression */ || + node.parent.kind === 161 /* NewExpression */) && + node.parent.expression !== node) { + var fullCallOrNewExpression = node.parent.expression; + var startingExpression = getStartingExpression(fullCallOrNewExpression); + if (fullCallOrNewExpression === startingExpression) { + return -1 /* Unknown */; + } + var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); + var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); + } + return -1 /* Unknown */; + function getStartingExpression(node) { + while (true) { + switch (node.kind) { + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + node = node.expression; + break; + default: + return node; + } + } + return node; + } + } function deriveActualIndentationFromList(list, index, sourceFile, options) { ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; From 02e01d7afcf03af039f2452e1b242b2aac2c39b3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 17:13:47 -0400 Subject: [PATCH 59/79] Added tests. --- .../completionListInObjectBindingPattern10.ts | 23 +++++++++++++++++++ .../completionListInObjectBindingPattern11.ts | 13 +++++++++++ .../completionListInObjectBindingPattern12.ts | 13 +++++++++++ 3 files changed, 49 insertions(+) create mode 100644 tests/cases/fourslash/completionListInObjectBindingPattern10.ts create mode 100644 tests/cases/fourslash/completionListInObjectBindingPattern11.ts create mode 100644 tests/cases/fourslash/completionListInObjectBindingPattern12.ts diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern10.ts b/tests/cases/fourslash/completionListInObjectBindingPattern10.ts new file mode 100644 index 00000000000..fcc09d1ead4 --- /dev/null +++ b/tests/cases/fourslash/completionListInObjectBindingPattern10.ts @@ -0,0 +1,23 @@ +/// + +////interface I { +//// propertyOfI_1: number; +//// propertyOfI_2: string; +////} +////interface J { +//// property1: I; +//// property2: string; +////} +//// +////var foo: J[]; +////var [{ property1: { propertyOfI_1, }, /*1*/ }, { /*2*/ }] = foo; + +goTo.marker("1"); +verify.completionListContains("property2"); +verify.not.completionListContains("property1"); +verify.not.completionListContains("propertyOfI_2"); +verify.not.completionListContains("propertyOfI_1"); + +goTo.marker("2"); +verify.completionListContains("property1"); +verify.completionListContains("property2"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern11.ts b/tests/cases/fourslash/completionListInObjectBindingPattern11.ts new file mode 100644 index 00000000000..25d6651a038 --- /dev/null +++ b/tests/cases/fourslash/completionListInObjectBindingPattern11.ts @@ -0,0 +1,13 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////var { property1: prop1, /**/ }: I; + +goTo.marker(""); +verify.completionListContains("property2"); +verify.not.completionListContains("property1"); +verify.not.completionListContains("prop1"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern12.ts b/tests/cases/fourslash/completionListInObjectBindingPattern12.ts new file mode 100644 index 00000000000..f31206a21b6 --- /dev/null +++ b/tests/cases/fourslash/completionListInObjectBindingPattern12.ts @@ -0,0 +1,13 @@ +/// + +////interface I { +//// property1: number; +//// property2: string; +////} +//// +////function f({ property1, /**/ }: I): void { +////} + +goTo.marker(""); +verify.completionListContains("property2"); +verify.not.completionListContains("property1"); \ No newline at end of file From 4853fd02677ca469e7f3b206e533e93ce4f7dbca Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 24 Jun 2015 23:04:52 +0200 Subject: [PATCH 60/79] Fixed formatting spaces on protected keyword --- src/services/formatting/rules.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index abb08f5bf22..9897453e575 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -318,7 +318,7 @@ namespace ts.formatting { this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space)); + this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space)); this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { From 822199f40a938896f8dcbbe5402234f5194ff3a5 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Wed, 24 Jun 2015 23:11:11 +0200 Subject: [PATCH 61/79] Added test for formatting on protected modifier --- tests/cases/fourslash/formattingOnClasses.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/cases/fourslash/formattingOnClasses.ts b/tests/cases/fourslash/formattingOnClasses.ts index 045ee91e427..0c259dae2ec 100644 --- a/tests/cases/fourslash/formattingOnClasses.ts +++ b/tests/cases/fourslash/formattingOnClasses.ts @@ -77,7 +77,9 @@ /////*60*/ private foo ( ns : any ) { /////*61*/ return ns.toString ( ) ; /////*62*/ } -/////*63*/} +/////*63*/ protected bar ( ) { } +/////*64*/ protected static bar2 ( ) { } +/////*65*/} format.document(); goTo.marker("1"); verify.currentLineContentIs("class a {"); @@ -204,4 +206,8 @@ verify.currentLineContentIs(" return ns.toString();"); goTo.marker("62"); verify.currentLineContentIs(" }"); goTo.marker("63"); +verify.currentLineContentIs(" protected bar() { }"); +goTo.marker("64"); +verify.currentLineContentIs(" protected static bar2() { }"); +goTo.marker("65"); verify.currentLineContentIs("}"); \ No newline at end of file From 14f7dd02d714e3ee9ea92a25222c93b85078c3e0 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 24 Jun 2015 15:02:20 -0700 Subject: [PATCH 62/79] Revert changes to the parser and augment check to the emitter to handel '1..toString' case --- src/compiler/emitter.ts | 14 ++- src/compiler/parser.ts | 32 +++--- tests/baselines/reference/numLit.errors.txt | 33 +++++++ tests/baselines/reference/numLit.js | 9 +- tests/baselines/reference/numLit.symbols | 65 ------------- tests/baselines/reference/numLit.types | 97 ------------------- .../reference/toStringOnPrimitives.js | 2 +- 7 files changed, 62 insertions(+), 190 deletions(-) create mode 100644 tests/baselines/reference/numLit.errors.txt delete mode 100644 tests/baselines/reference/numLit.symbols delete mode 100644 tests/baselines/reference/numLit.types diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index b7c71c7b09a..4296884fdeb 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1783,11 +1783,21 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emit(node.expression); let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + + // 1 .toString is a valid property access, emit a space after the literal + let shouldEmitSpace: boolean; if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) { - write(" ."); // JS compat with numeric literal - } else { + let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0; + } + + if (shouldEmitSpace) { + write(" ."); + } + else { write("."); } + let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 14c7d6da455..fbb3dad5037 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1830,30 +1830,20 @@ namespace ts { } let tokenPos = scanner.getTokenPos(); - let nextCharCode: number; - nextToken(); finishNode(node); - if (node.kind === SyntaxKind.NumericLiteral) { - // Octal literals are not allowed in strict mode or ES5 - // Note that theoretically the following condition would hold true literals like 009, - // which is not octal.But because of how the scanner separates the tokens, we would - // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. - // We also do not need to check for negatives because any prefix operator would be part of a - // parent unary expression. - if (sourceText.charCodeAt(tokenPos) === CharacterCodes._0 && isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= NodeFlags.OctalLiteral; - } - else if (token === SyntaxKind.Identifier && sourceText.charCodeAt(node.end-1) === CharacterCodes.dot) { - nextCharCode = sourceText.charCodeAt(node.end); - if (!isWhiteSpace(nextCharCode) && !isLineBreak(nextCharCode)) { - // If we see 23.Identifier, go back 1 char to scan .Identifier - node.end = node.end - 1; - scanner.setTextPos(node.end); - nextToken() - } - } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === SyntaxKind.NumericLiteral + && sourceText.charCodeAt(tokenPos) === CharacterCodes._0 + && isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { + + node.flags |= NodeFlags.OctalLiteral; } return node; diff --git a/tests/baselines/reference/numLit.errors.txt b/tests/baselines/reference/numLit.errors.txt new file mode 100644 index 00000000000..17392011fa6 --- /dev/null +++ b/tests/baselines/reference/numLit.errors.txt @@ -0,0 +1,33 @@ +tests/cases/compiler/numLit.ts(3,3): error TS1005: ';' expected. +tests/cases/compiler/numLit.ts(9,15): error TS1005: ',' expected. +tests/cases/compiler/numLit.ts(9,23): error TS1005: '=' expected. +tests/cases/compiler/numLit.ts(9,24): error TS1109: Expression expected. + + +==== tests/cases/compiler/numLit.ts (4 errors) ==== + 1..toString(); + 1.0.toString(); + 1.toString(); + ~~~~~~~~ +!!! error TS1005: ';' expected. + 1.+2.0 + 3. ; + + // Preserve whitespace where important for JS compatibility + var i: number = 1; + var test1 = i.toString(); + var test2 = 2.toString(); // emitted as 2 .toString() + ~~~~~~~~ +!!! error TS1005: ',' expected. + ~ +!!! error TS1005: '=' expected. + ~ +!!! error TS1109: Expression expected. + var test3 = 3 .toString(); + var test4 = 3 .toString(); + var test5 = 3 .toString(); + var test6 = 3.['toString'](); + var test7 = 3 + .toString(); + var test8 = new Number(4).toString(); + var test9 = 3. + 3. + \ No newline at end of file diff --git a/tests/baselines/reference/numLit.js b/tests/baselines/reference/numLit.js index 5620a9edcad..c68d6925faa 100644 --- a/tests/baselines/reference/numLit.js +++ b/tests/baselines/reference/numLit.js @@ -19,14 +19,15 @@ var test9 = 3. + 3. //// [numLit.js] -1. .toString(); -1.0 .toString(); -1 .toString(); +1..toString(); +1.0.toString(); +1.; +toString(); 1. + 2.0 + 3.; // Preserve whitespace where important for JS compatibility var i = 1; var test1 = i.toString(); -var test2 = 2 .toString(); // emitted as 2 .toString() +var test2 = 2., toString = (); // emitted as 2 .toString() var test3 = 3 .toString(); var test4 = 3 .toString(); var test5 = 3 .toString(); diff --git a/tests/baselines/reference/numLit.symbols b/tests/baselines/reference/numLit.symbols deleted file mode 100644 index 1f4067d233f..00000000000 --- a/tests/baselines/reference/numLit.symbols +++ /dev/null @@ -1,65 +0,0 @@ -=== tests/cases/compiler/numLit.ts === -1..toString(); ->1..toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -1.0.toString(); ->1.0.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -1.toString(); ->1.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -1.+2.0 + 3. ; - -// Preserve whitespace where important for JS compatibility -var i: number = 1; ->i : Symbol(i, Decl(numLit.ts, 6, 3)) - -var test1 = i.toString(); ->test1 : Symbol(test1, Decl(numLit.ts, 7, 3)) ->i.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->i : Symbol(i, Decl(numLit.ts, 6, 3)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test2 = 2.toString(); // emitted as 2 .toString() ->test2 : Symbol(test2, Decl(numLit.ts, 8, 3)) ->2.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test3 = 3 .toString(); ->test3 : Symbol(test3, Decl(numLit.ts, 9, 3)) ->3 .toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test4 = 3 .toString(); ->test4 : Symbol(test4, Decl(numLit.ts, 10, 3)) ->3 .toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test5 = 3 .toString(); ->test5 : Symbol(test5, Decl(numLit.ts, 11, 3)) ->3 .toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test6 = 3.['toString'](); ->test6 : Symbol(test6, Decl(numLit.ts, 12, 3)) ->'toString' : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test7 = 3 ->test7 : Symbol(test7, Decl(numLit.ts, 13, 3)) ->3.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -.toString(); ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test8 = new Number(4).toString(); ->test8 : Symbol(test8, Decl(numLit.ts, 15, 3)) ->new Number(4).toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) ->Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18)) - -var test9 = 3. + 3. ->test9 : Symbol(test9, Decl(numLit.ts, 16, 3)) - diff --git a/tests/baselines/reference/numLit.types b/tests/baselines/reference/numLit.types deleted file mode 100644 index ba72abb2825..00000000000 --- a/tests/baselines/reference/numLit.types +++ /dev/null @@ -1,97 +0,0 @@ -=== tests/cases/compiler/numLit.ts === -1..toString(); ->1..toString() : string ->1..toString : (radix?: number) => string ->1. : number ->toString : (radix?: number) => string - -1.0.toString(); ->1.0.toString() : string ->1.0.toString : (radix?: number) => string ->1.0 : number ->toString : (radix?: number) => string - -1.toString(); ->1.toString() : string ->1.toString : (radix?: number) => string ->1 : number ->toString : (radix?: number) => string - -1.+2.0 + 3. ; ->1.+2.0 + 3. : number ->1.+2.0 : number ->1. : number ->2.0 : number ->3. : number - -// Preserve whitespace where important for JS compatibility -var i: number = 1; ->i : number ->1 : number - -var test1 = i.toString(); ->test1 : string ->i.toString() : string ->i.toString : (radix?: number) => string ->i : number ->toString : (radix?: number) => string - -var test2 = 2.toString(); // emitted as 2 .toString() ->test2 : string ->2.toString() : string ->2.toString : (radix?: number) => string ->2 : number ->toString : (radix?: number) => string - -var test3 = 3 .toString(); ->test3 : string ->3 .toString() : string ->3 .toString : (radix?: number) => string ->3 : number ->toString : (radix?: number) => string - -var test4 = 3 .toString(); ->test4 : string ->3 .toString() : string ->3 .toString : (radix?: number) => string ->3 : number ->toString : (radix?: number) => string - -var test5 = 3 .toString(); ->test5 : string ->3 .toString() : string ->3 .toString : (radix?: number) => string ->3 : number ->toString : (radix?: number) => string - -var test6 = 3.['toString'](); ->test6 : string ->3.['toString']() : string ->3.['toString'] : (radix?: number) => string ->3. : number ->'toString' : string - -var test7 = 3 ->test7 : string ->3.toString() : string ->3.toString : (radix?: number) => string ->3 : number - -.toString(); ->toString : (radix?: number) => string - -var test8 = new Number(4).toString(); ->test8 : string ->new Number(4).toString() : string ->new Number(4).toString : (radix?: number) => string ->new Number(4) : Number ->Number : NumberConstructor ->4 : number ->toString : (radix?: number) => string - -var test9 = 3. + 3. ->test9 : number ->3. + 3. : number ->3. : number ->3. : number - diff --git a/tests/baselines/reference/toStringOnPrimitives.js b/tests/baselines/reference/toStringOnPrimitives.js index 007bb5429b0..bce8a997ba7 100644 --- a/tests/baselines/reference/toStringOnPrimitives.js +++ b/tests/baselines/reference/toStringOnPrimitives.js @@ -8,4 +8,4 @@ aBool.toString(); true.toString(); var aBool = false; aBool.toString(); -1. .toString(); +1..toString(); From e52a27b3de5f003de74f4d245bed7fabbc26d7f5 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 24 Jun 2015 18:07:49 -0400 Subject: [PATCH 63/79] Renamed function. --- src/services/services.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 25949082e8d..f4e37bf56ea 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -2985,7 +2985,7 @@ namespace ts { } function tryGetGlobalSymbols(): boolean { - let objectLikeContainer = getContainingObjectLiteralOrBindingPatternIfApplicableForCompletion(contextToken); + let objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken); if (objectLikeContainer) { // Object literal expression, look up possible property names from contextual type isMemberCompletion = true; @@ -3198,9 +3198,11 @@ namespace ts { return false; } - function getContainingObjectLiteralOrBindingPatternIfApplicableForCompletion(contextToken: Node): ObjectLiteralExpression | BindingPattern { - // The locations in an object literal expression that - // are applicable for completion are property name definition locations. + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken: Node): ObjectLiteralExpression | BindingPattern { if (contextToken) { switch (contextToken.kind) { case SyntaxKind.OpenBraceToken: // let x = { | From 2a483187a7a6f9073ac928ca4cde8609a0ee8040 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Thu, 25 Jun 2015 00:23:13 +0200 Subject: [PATCH 64/79] Remove unused variables --- src/compiler/checker.ts | 6 ++---- src/compiler/declarationEmitter.ts | 1 - src/compiler/parser.ts | 1 - src/compiler/program.ts | 1 - src/compiler/utilities.ts | 1 - src/services/services.ts | 2 -- 6 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 609a154ded1..49a61a2fd08 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3518,7 +3518,6 @@ namespace ts { let syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; let indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { - let len = indexSymbol.declarations.length; for (let decl of indexSymbol.declarations) { let node = decl; if (node.parameters.length === 1) { @@ -8374,12 +8373,12 @@ namespace ts { } function checkTypeOfExpression(node: TypeOfExpression): Type { - let operandType = checkExpression(node.expression); + checkExpression(node.expression); return stringType; } function checkVoidExpression(node: VoidExpression): Type { - let operandType = checkExpression(node.expression); + checkExpression(node.expression); return undefinedType; } @@ -12380,7 +12379,6 @@ namespace ts { case SyntaxKind.StringLiteral: // External module name in an import declaration - let moduleName: Expression; if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 2ba88f1ac29..54d0d6ff854 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -40,7 +40,6 @@ namespace ts { function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit { let newLine = host.getNewLine(); let compilerOptions = host.getCompilerOptions(); - let languageVersion = compilerOptions.target || ScriptTarget.ES3; let write: (s: string) => void; let writeLine: () => void; diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index fbb3dad5037..2c496b8c60d 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -5363,7 +5363,6 @@ namespace ts { let atToken = createNode(SyntaxKind.AtToken, pos - 1); atToken.end = pos; - let startPos = pos; let tagName = scanIdentifier(); if (!tagName) { return; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 2af9ad9987d..09bd6fbdd28 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -337,7 +337,6 @@ namespace ts { function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { let start: number; let length: number; - let extensions: string; let diagnosticArgument: string[]; if (refEnd !== undefined && refPos !== undefined) { start = refPos; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 8162625c25f..ce166aa2f36 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1957,7 +1957,6 @@ namespace ts { function getExpandedCharCodes(input: string): number[] { let output: number[] = []; let length = input.length; - let leadSurrogate: number = undefined; for (let i = 0; i < length; i++) { let charCode = input.charCodeAt(i); diff --git a/src/services/services.ts b/src/services/services.ts index 18510b9a178..077a46a7461 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -95,7 +95,6 @@ namespace ts { export module ScriptSnapshot { class StringScriptSnapshot implements IScriptSnapshot { - private _lineStartPositions: number[] = undefined; constructor(private text: string) { } @@ -2910,7 +2909,6 @@ namespace ts { } let location = getTouchingPropertyName(sourceFile, position); - var target = program.getCompilerOptions().target; let semanticStart = new Date().getTime(); let isMemberCompletion: boolean; From f734055ee7522db7d3d1bced6f2ed9e68d483b80 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 25 Jun 2015 12:06:13 -0400 Subject: [PATCH 65/79] externam -> external --- ...nExternamModuleName.ts => goToDefinitionExternalModuleName.ts} | 0 ...xternamModuleName2.ts => goToDefinitionExternalModuleName2.ts} | 0 ...xternamModuleName3.ts => goToDefinitionExternalModuleName3.ts} | 0 ...xternamModuleName4.ts => goToDefinitionExternalModuleName4.ts} | 0 ...xternamModuleName5.ts => goToDefinitionExternalModuleName5.ts} | 0 ...xternamModuleName6.ts => goToDefinitionExternalModuleName6.ts} | 0 ...xternamModuleName7.ts => goToDefinitionExternalModuleName7.ts} | 0 ...xternamModuleName8.ts => goToDefinitionExternalModuleName8.ts} | 0 ...xternamModuleName9.ts => goToDefinitionExternalModuleName9.ts} | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename tests/cases/fourslash/{goToDefinitionExternamModuleName.ts => goToDefinitionExternalModuleName.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName2.ts => goToDefinitionExternalModuleName2.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName3.ts => goToDefinitionExternalModuleName3.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName4.ts => goToDefinitionExternalModuleName4.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName5.ts => goToDefinitionExternalModuleName5.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName6.ts => goToDefinitionExternalModuleName6.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName7.ts => goToDefinitionExternalModuleName7.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName8.ts => goToDefinitionExternalModuleName8.ts} (100%) rename tests/cases/fourslash/{goToDefinitionExternamModuleName9.ts => goToDefinitionExternalModuleName9.ts} (100%) diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName2.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName2.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName2.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName2.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName3.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName3.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName3.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName3.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName4.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName4.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName4.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName4.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName5.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName5.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName5.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName5.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName6.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName6.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName6.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName6.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName7.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName7.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName7.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName7.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName8.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName8.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName8.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName8.ts diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName9.ts b/tests/cases/fourslash/goToDefinitionExternalModuleName9.ts similarity index 100% rename from tests/cases/fourslash/goToDefinitionExternamModuleName9.ts rename to tests/cases/fourslash/goToDefinitionExternalModuleName9.ts From 6732acaa325ee42322e5fa97e2bd260f358f580d Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 25 Jun 2015 12:10:09 -0400 Subject: [PATCH 66/79] Underscore typings. --- .../fourslash/{underscoreTypings1.ts => underscoreTypings01.ts} | 0 .../fourslash/{underscoreTyping1.ts => underscoreTypings02.ts} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tests/cases/fourslash/{underscoreTypings1.ts => underscoreTypings01.ts} (100%) rename tests/cases/fourslash/{underscoreTyping1.ts => underscoreTypings02.ts} (100%) diff --git a/tests/cases/fourslash/underscoreTypings1.ts b/tests/cases/fourslash/underscoreTypings01.ts similarity index 100% rename from tests/cases/fourslash/underscoreTypings1.ts rename to tests/cases/fourslash/underscoreTypings01.ts diff --git a/tests/cases/fourslash/underscoreTyping1.ts b/tests/cases/fourslash/underscoreTypings02.ts similarity index 100% rename from tests/cases/fourslash/underscoreTyping1.ts rename to tests/cases/fourslash/underscoreTypings02.ts From 926c25e38b3f77c3b0a558e3ade537ef6ad35f88 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 25 Jun 2015 12:14:59 -0400 Subject: [PATCH 67/79] No more 'scriptLexicalStructure'. --- ...ureBindingPatterns.ts => navigationBarItemsBindingPatterns.ts} | 0 ...uctor.ts => navigationBarItemsBindingPatternsInConstructor.ts} | 0 ...mptyConstructors.ts => navigationBarItemsEmptyConstructors.ts} | 0 ...iptLexicalStructureExports.ts => navigationBarItemsExports.ts} | 0 ...exicalStructureFunctions.ts => navigationBarItemsFunctions.ts} | 0 ...ureFunctionsBroken.ts => navigationBarItemsFunctionsBroken.ts} | 0 ...eFunctionsBroken2.ts => navigationBarItemsFunctionsBroken2.ts} | 0 ...iptLexicalStructureImports.ts => navigationBarItemsImports.ts} | 0 ...{scriptLexicalStructureItems.ts => navigationBarItemsItems.ts} | 0 ...criptLexicalStructureItems2.ts => navigationBarItemsItems2.ts} | 0 ....ts => navigationBarItemsItemsContainsNoAnonymousFunctions.ts} | 0 ...ternalModules.ts => navigationBarItemsItemsExternalModules.ts} | 0 ...rnalModules2.ts => navigationBarItemsItemsExternalModules2.ts} | 0 ...rnalModules3.ts => navigationBarItemsItemsExternalModules3.ts} | 0 ...duleVariables.ts => navigationBarItemsItemsModuleVariables.ts} | 0 ...StructureMissingName1.ts => navigationBarItemsMissingName1.ts} | 0 ...StructureMissingName2.ts => navigationBarItemsMissingName2.ts} | 0 ...iptLexicalStructureModules.ts => navigationBarItemsModules.ts} | 0 ...tifiers.ts => navigationBarItemsMultilineStringIdentifiers.ts} | 0 ...rs.ts => navigationBarItemsPropertiesDefinedInConstructors.ts} | 0 ...tLexicalStructureSymbols1.ts => navigationBarItemsSymbols1.ts} | 0 ...tLexicalStructureSymbols2.ts => navigationBarItemsSymbols2.ts} | 0 ...tLexicalStructureSymbols3.ts => navigationBarItemsSymbols3.ts} | 0 23 files changed, 0 insertions(+), 0 deletions(-) rename tests/cases/fourslash/{scriptLexicalStructureBindingPatterns.ts => navigationBarItemsBindingPatterns.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureBindingPatternsInConstructor.ts => navigationBarItemsBindingPatternsInConstructor.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureEmptyConstructors.ts => navigationBarItemsEmptyConstructors.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureExports.ts => navigationBarItemsExports.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureFunctions.ts => navigationBarItemsFunctions.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureFunctionsBroken.ts => navigationBarItemsFunctionsBroken.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureFunctionsBroken2.ts => navigationBarItemsFunctionsBroken2.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureImports.ts => navigationBarItemsImports.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItems.ts => navigationBarItemsItems.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItems2.ts => navigationBarItemsItems2.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItemsContainsNoAnonymousFunctions.ts => navigationBarItemsItemsContainsNoAnonymousFunctions.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItemsExternalModules.ts => navigationBarItemsItemsExternalModules.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItemsExternalModules2.ts => navigationBarItemsItemsExternalModules2.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItemsExternalModules3.ts => navigationBarItemsItemsExternalModules3.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureItemsModuleVariables.ts => navigationBarItemsItemsModuleVariables.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureMissingName1.ts => navigationBarItemsMissingName1.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureMissingName2.ts => navigationBarItemsMissingName2.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureModules.ts => navigationBarItemsModules.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureMultilineStringIdentifiers.ts => navigationBarItemsMultilineStringIdentifiers.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructurePropertiesDefinedInConstructors.ts => navigationBarItemsPropertiesDefinedInConstructors.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureSymbols1.ts => navigationBarItemsSymbols1.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureSymbols2.ts => navigationBarItemsSymbols2.ts} (100%) rename tests/cases/fourslash/{scriptLexicalStructureSymbols3.ts => navigationBarItemsSymbols3.ts} (100%) diff --git a/tests/cases/fourslash/scriptLexicalStructureBindingPatterns.ts b/tests/cases/fourslash/navigationBarItemsBindingPatterns.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureBindingPatterns.ts rename to tests/cases/fourslash/navigationBarItemsBindingPatterns.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureBindingPatternsInConstructor.ts b/tests/cases/fourslash/navigationBarItemsBindingPatternsInConstructor.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureBindingPatternsInConstructor.ts rename to tests/cases/fourslash/navigationBarItemsBindingPatternsInConstructor.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureEmptyConstructors.ts b/tests/cases/fourslash/navigationBarItemsEmptyConstructors.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureEmptyConstructors.ts rename to tests/cases/fourslash/navigationBarItemsEmptyConstructors.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureExports.ts b/tests/cases/fourslash/navigationBarItemsExports.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureExports.ts rename to tests/cases/fourslash/navigationBarItemsExports.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureFunctions.ts b/tests/cases/fourslash/navigationBarItemsFunctions.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureFunctions.ts rename to tests/cases/fourslash/navigationBarItemsFunctions.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureFunctionsBroken.ts b/tests/cases/fourslash/navigationBarItemsFunctionsBroken.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureFunctionsBroken.ts rename to tests/cases/fourslash/navigationBarItemsFunctionsBroken.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureFunctionsBroken2.ts b/tests/cases/fourslash/navigationBarItemsFunctionsBroken2.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureFunctionsBroken2.ts rename to tests/cases/fourslash/navigationBarItemsFunctionsBroken2.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureImports.ts b/tests/cases/fourslash/navigationBarItemsImports.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureImports.ts rename to tests/cases/fourslash/navigationBarItemsImports.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItems.ts b/tests/cases/fourslash/navigationBarItemsItems.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItems.ts rename to tests/cases/fourslash/navigationBarItemsItems.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItems2.ts b/tests/cases/fourslash/navigationBarItemsItems2.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItems2.ts rename to tests/cases/fourslash/navigationBarItemsItems2.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItemsContainsNoAnonymousFunctions.ts b/tests/cases/fourslash/navigationBarItemsItemsContainsNoAnonymousFunctions.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItemsContainsNoAnonymousFunctions.ts rename to tests/cases/fourslash/navigationBarItemsItemsContainsNoAnonymousFunctions.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItemsExternalModules.ts b/tests/cases/fourslash/navigationBarItemsItemsExternalModules.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItemsExternalModules.ts rename to tests/cases/fourslash/navigationBarItemsItemsExternalModules.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItemsExternalModules2.ts b/tests/cases/fourslash/navigationBarItemsItemsExternalModules2.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItemsExternalModules2.ts rename to tests/cases/fourslash/navigationBarItemsItemsExternalModules2.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItemsExternalModules3.ts b/tests/cases/fourslash/navigationBarItemsItemsExternalModules3.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItemsExternalModules3.ts rename to tests/cases/fourslash/navigationBarItemsItemsExternalModules3.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureItemsModuleVariables.ts b/tests/cases/fourslash/navigationBarItemsItemsModuleVariables.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureItemsModuleVariables.ts rename to tests/cases/fourslash/navigationBarItemsItemsModuleVariables.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureMissingName1.ts b/tests/cases/fourslash/navigationBarItemsMissingName1.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureMissingName1.ts rename to tests/cases/fourslash/navigationBarItemsMissingName1.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureMissingName2.ts b/tests/cases/fourslash/navigationBarItemsMissingName2.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureMissingName2.ts rename to tests/cases/fourslash/navigationBarItemsMissingName2.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureModules.ts b/tests/cases/fourslash/navigationBarItemsModules.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureModules.ts rename to tests/cases/fourslash/navigationBarItemsModules.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureMultilineStringIdentifiers.ts b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureMultilineStringIdentifiers.ts rename to tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts diff --git a/tests/cases/fourslash/scriptLexicalStructurePropertiesDefinedInConstructors.ts b/tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructurePropertiesDefinedInConstructors.ts rename to tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureSymbols1.ts b/tests/cases/fourslash/navigationBarItemsSymbols1.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureSymbols1.ts rename to tests/cases/fourslash/navigationBarItemsSymbols1.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureSymbols2.ts b/tests/cases/fourslash/navigationBarItemsSymbols2.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureSymbols2.ts rename to tests/cases/fourslash/navigationBarItemsSymbols2.ts diff --git a/tests/cases/fourslash/scriptLexicalStructureSymbols3.ts b/tests/cases/fourslash/navigationBarItemsSymbols3.ts similarity index 100% rename from tests/cases/fourslash/scriptLexicalStructureSymbols3.ts rename to tests/cases/fourslash/navigationBarItemsSymbols3.ts From c04bc692d45f43ec6f428a2477122d98aae2efb7 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 25 Jun 2015 13:21:58 -0400 Subject: [PATCH 68/79] Fixed coment. --- tests/cases/compiler/numLit.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cases/compiler/numLit.ts b/tests/cases/compiler/numLit.ts index abe3505703d..23cd2ba45f8 100644 --- a/tests/cases/compiler/numLit.ts +++ b/tests/cases/compiler/numLit.ts @@ -6,7 +6,7 @@ // Preserve whitespace where important for JS compatibility var i: number = 1; var test1 = i.toString(); -var test2 = 2.toString(); // emitted as 2 .toString() +var test2 = 2.toString(); var test3 = 3 .toString(); var test4 = 3 .toString(); var test5 = 3 .toString(); From eda3956fa25d25444de843c83df46e9e143bec8f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 25 Jun 2015 13:34:31 -0400 Subject: [PATCH 69/79] Accepted baselines. --- tests/baselines/reference/numLit.errors.txt | 2 +- tests/baselines/reference/numLit.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/baselines/reference/numLit.errors.txt b/tests/baselines/reference/numLit.errors.txt index 17392011fa6..603f655fe84 100644 --- a/tests/baselines/reference/numLit.errors.txt +++ b/tests/baselines/reference/numLit.errors.txt @@ -15,7 +15,7 @@ tests/cases/compiler/numLit.ts(9,24): error TS1109: Expression expected. // Preserve whitespace where important for JS compatibility var i: number = 1; var test1 = i.toString(); - var test2 = 2.toString(); // emitted as 2 .toString() + var test2 = 2.toString(); ~~~~~~~~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/numLit.js b/tests/baselines/reference/numLit.js index c68d6925faa..add93ed0a6a 100644 --- a/tests/baselines/reference/numLit.js +++ b/tests/baselines/reference/numLit.js @@ -7,7 +7,7 @@ // Preserve whitespace where important for JS compatibility var i: number = 1; var test1 = i.toString(); -var test2 = 2.toString(); // emitted as 2 .toString() +var test2 = 2.toString(); var test3 = 3 .toString(); var test4 = 3 .toString(); var test5 = 3 .toString(); @@ -27,7 +27,7 @@ toString(); // Preserve whitespace where important for JS compatibility var i = 1; var test1 = i.toString(); -var test2 = 2., toString = (); // emitted as 2 .toString() +var test2 = 2., toString = (); var test3 = 3 .toString(); var test4 = 3 .toString(); var test5 = 3 .toString(); From ec2d5f3a0d9785d415bae02ba88ab1bb09e9ebf3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 25 Jun 2015 13:38:42 -0400 Subject: [PATCH 70/79] Renamed test. --- ...ericLiteralsWithTrailingDecimalPoints01.errors.txt} | 10 +++++----- ...s => numericLiteralsWithTrailingDecimalPoints01.js} | 4 ++-- ...s => numericLiteralsWithTrailingDecimalPoints01.ts} | 0 3 files changed, 7 insertions(+), 7 deletions(-) rename tests/baselines/reference/{numLit.errors.txt => numericLiteralsWithTrailingDecimalPoints01.errors.txt} (56%) rename tests/baselines/reference/{numLit.js => numericLiteralsWithTrailingDecimalPoints01.js} (86%) rename tests/cases/compiler/{numLit.ts => numericLiteralsWithTrailingDecimalPoints01.ts} (100%) diff --git a/tests/baselines/reference/numLit.errors.txt b/tests/baselines/reference/numericLiteralsWithTrailingDecimalPoints01.errors.txt similarity index 56% rename from tests/baselines/reference/numLit.errors.txt rename to tests/baselines/reference/numericLiteralsWithTrailingDecimalPoints01.errors.txt index 603f655fe84..f08750ff0a6 100644 --- a/tests/baselines/reference/numLit.errors.txt +++ b/tests/baselines/reference/numericLiteralsWithTrailingDecimalPoints01.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/numLit.ts(3,3): error TS1005: ';' expected. -tests/cases/compiler/numLit.ts(9,15): error TS1005: ',' expected. -tests/cases/compiler/numLit.ts(9,23): error TS1005: '=' expected. -tests/cases/compiler/numLit.ts(9,24): error TS1109: Expression expected. +tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts(3,3): error TS1005: ';' expected. +tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts(9,15): error TS1005: ',' expected. +tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts(9,23): error TS1005: '=' expected. +tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts(9,24): error TS1109: Expression expected. -==== tests/cases/compiler/numLit.ts (4 errors) ==== +==== tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts (4 errors) ==== 1..toString(); 1.0.toString(); 1.toString(); diff --git a/tests/baselines/reference/numLit.js b/tests/baselines/reference/numericLiteralsWithTrailingDecimalPoints01.js similarity index 86% rename from tests/baselines/reference/numLit.js rename to tests/baselines/reference/numericLiteralsWithTrailingDecimalPoints01.js index add93ed0a6a..0b1ce1f0736 100644 --- a/tests/baselines/reference/numLit.js +++ b/tests/baselines/reference/numericLiteralsWithTrailingDecimalPoints01.js @@ -1,4 +1,4 @@ -//// [numLit.ts] +//// [numericLiteralsWithTrailingDecimalPoints01.ts] 1..toString(); 1.0.toString(); 1.toString(); @@ -18,7 +18,7 @@ var test8 = new Number(4).toString(); var test9 = 3. + 3. -//// [numLit.js] +//// [numericLiteralsWithTrailingDecimalPoints01.js] 1..toString(); 1.0.toString(); 1.; diff --git a/tests/cases/compiler/numLit.ts b/tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts similarity index 100% rename from tests/cases/compiler/numLit.ts rename to tests/cases/compiler/numericLiteralsWithTrailingDecimalPoints01.ts From 627ebc86eb497691109cca25e19b58c47ffe265f Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Thu, 25 Jun 2015 20:47:40 +0200 Subject: [PATCH 71/79] Fixed formatting spaces on default keyword --- src/services/formatting/rules.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 9897453e575..84d79be5c6e 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -318,7 +318,7 @@ namespace ts.formatting { this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space)); + this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space)); this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { From de2d532b1f94a4c6980f8cded31516a028be5848 Mon Sep 17 00:00:00 2001 From: Dick van den Brink Date: Thu, 25 Jun 2015 20:49:25 +0200 Subject: [PATCH 72/79] Added test for formatting on default keyword --- tests/cases/fourslash/formattingOfExportDefault.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 tests/cases/fourslash/formattingOfExportDefault.ts diff --git a/tests/cases/fourslash/formattingOfExportDefault.ts b/tests/cases/fourslash/formattingOfExportDefault.ts new file mode 100644 index 00000000000..ff69440b861 --- /dev/null +++ b/tests/cases/fourslash/formattingOfExportDefault.ts @@ -0,0 +1,12 @@ +/// + +////module Foo { +/////*1*/ export default class Test { } +////} +/////*2*/export default function bar() { } + +format.document(); +goTo.marker("1"); +verify.currentLineContentIs(" export default class Test { }") +goTo.marker("2"); +verify.currentLineContentIs("export default function bar() { }") From 408538fd43a72976f96a4af3d9c7affb30792eb8 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Thu, 25 Jun 2015 13:31:14 -0700 Subject: [PATCH 73/79] Remove unreferenced errors --- .../diagnosticInformationMap.generated.ts | 14 ----- src/compiler/diagnosticMessages.json | 56 ------------------- 2 files changed, 70 deletions(-) diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 8ccc9d890e2..5ca747e4b62 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -20,22 +20,16 @@ module ts { An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation." }, An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." }, An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." }, - A_class_or_interface_declaration_can_only_have_one_extends_clause: { code: 1024, category: DiagnosticCategory.Error, key: "A class or interface declaration can only have one 'extends' clause." }, - An_extends_clause_must_precede_an_implements_clause: { code: 1025, category: DiagnosticCategory.Error, key: "An 'extends' clause must precede an 'implements' clause." }, - A_class_can_only_extend_a_single_class: { code: 1026, category: DiagnosticCategory.Error, key: "A class can only extend a single class." }, - A_class_declaration_can_only_have_one_implements_clause: { code: 1027, category: DiagnosticCategory.Error, key: "A class declaration can only have one 'implements' clause." }, Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen." }, _0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." }, _0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen." }, _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." }, - An_interface_declaration_cannot_have_an_implements_clause: { code: 1032, category: DiagnosticCategory.Error, key: "An interface declaration cannot have an 'implements' clause." }, super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." }, Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." }, Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." }, A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used in an already ambient context." }, Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: DiagnosticCategory.Error, key: "Initializers are not allowed in ambient contexts." }, _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a module element." }, - A_declare_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: DiagnosticCategory.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: DiagnosticCategory.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: DiagnosticCategory.Error, key: "A rest parameter cannot be optional." }, A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: DiagnosticCategory.Error, key: "A rest parameter cannot have an initializer." }, @@ -94,7 +88,6 @@ module ts { case_or_default_expected: { code: 1130, category: DiagnosticCategory.Error, key: "'case' or 'default' expected." }, Property_or_signature_expected: { code: 1131, category: DiagnosticCategory.Error, key: "Property or signature expected." }, Enum_member_expected: { code: 1132, category: DiagnosticCategory.Error, key: "Enum member expected." }, - Type_reference_expected: { code: 1133, category: DiagnosticCategory.Error, key: "Type reference expected." }, Variable_declaration_expected: { code: 1134, category: DiagnosticCategory.Error, key: "Variable declaration expected." }, Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected." }, Property_assignment_expected: { code: 1136, category: DiagnosticCategory.Error, key: "Property assignment expected." }, @@ -111,9 +104,6 @@ module ts { Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile modules unless the '--module' flag is provided." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - var_let_or_const_expected: { code: 1152, category: DiagnosticCategory.Error, key: "'var', 'let' or 'const' expected." }, - let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1153, category: DiagnosticCategory.Error, key: "'let' declarations are only available when targeting ECMAScript 6 and higher." }, - const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1154, category: DiagnosticCategory.Error, key: "'const' declarations are only available when targeting ECMAScript 6 and higher." }, const_declarations_must_be_initialized: { code: 1155, category: DiagnosticCategory.Error, key: "'const' declarations must be initialized" }, const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block." }, let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block." }, @@ -124,7 +114,6 @@ module ts { Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in enums." }, A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: DiagnosticCategory.Error, key: "A computed property name in an ambient context must directly refer to a built-in symbol." }, A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: DiagnosticCategory.Error, key: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1167, category: DiagnosticCategory.Error, key: "Computed property names are only available when targeting ECMAScript 6 and higher." }, A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: DiagnosticCategory.Error, key: "A computed property name in a method overload must directly refer to a built-in symbol." }, A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: DiagnosticCategory.Error, key: "A computed property name in an interface must directly refer to a built-in symbol." }, A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: DiagnosticCategory.Error, key: "A computed property name in a type literal must directly refer to a built-in symbol." }, @@ -140,7 +129,6 @@ module ts { Property_destructuring_pattern_expected: { code: 1180, category: DiagnosticCategory.Error, key: "Property destructuring pattern expected." }, Array_element_destructuring_pattern_expected: { code: 1181, category: DiagnosticCategory.Error, key: "Array element destructuring pattern expected." }, A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer." }, - Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts." }, An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts." }, Modifiers_cannot_appear_here: { code: 1184, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." }, @@ -187,7 +175,6 @@ module ts { Module_0_has_no_exported_member_1: { code: 2305, category: DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: DiagnosticCategory.Error, key: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: DiagnosticCategory.Error, key: "Cannot find module '{0}'." }, - A_module_cannot_have_more_than_one_export_assignment: { code: 2308, category: DiagnosticCategory.Error, key: "A module cannot have more than one export assignment." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: DiagnosticCategory.Error, key: "A class may only extend another class." }, @@ -508,7 +495,6 @@ module ts { File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: DiagnosticCategory.Error, key: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: DiagnosticCategory.Message, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: DiagnosticCategory.Message, key: "Do not emit declarations for code that has an '@internal' annotation." }, - Preserve_new_lines_when_emitting_code: { code: 6057, category: DiagnosticCategory.Message, key: "Preserve new-lines when emitting code." }, Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: DiagnosticCategory.Message, key: "Specifies the root directory of input files. Use to control the output directory structure with --outDir." }, File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: DiagnosticCategory.Error, key: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index fb246955f73..4610f699a16 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -67,22 +67,6 @@ "category": "Error", "code": 1023 }, - "A class or interface declaration can only have one 'extends' clause.": { - "category": "Error", - "code": 1024 - }, - "An 'extends' clause must precede an 'implements' clause.": { - "category": "Error", - "code": 1025 - }, - "A class can only extend a single class.": { - "category": "Error", - "code": 1026 - }, - "A class declaration can only have one 'implements' clause.": { - "category": "Error", - "code": 1027 - }, "Accessibility modifier already seen.": { "category": "Error", "code": 1028 @@ -99,10 +83,6 @@ "category": "Error", "code": 1031 }, - "An interface declaration cannot have an 'implements' clause.": { - "category": "Error", - "code": 1032 - }, "'super' must be followed by an argument list or member access.": { "category": "Error", "code": 1034 @@ -127,10 +107,6 @@ "category": "Error", "code": 1044 }, - "A 'declare' modifier cannot be used with an interface declaration.": { - "category": "Error", - "code": 1045 - }, "A 'declare' modifier is required for a top level declaration in a .d.ts file.": { "category": "Error", "code": 1046 @@ -363,10 +339,6 @@ "category": "Error", "code": 1132 }, - "Type reference expected.": { - "category": "Error", - "code": 1133 - }, "Variable declaration expected.": { "category": "Error", "code": 1134 @@ -431,18 +403,6 @@ "category": "Error", "code": 1150 }, - "'var', 'let' or 'const' expected.": { - "category": "Error", - "code": 1152 - }, - "'let' declarations are only available when targeting ECMAScript 6 and higher.": { - "category": "Error", - "code": 1153 - }, - "'const' declarations are only available when targeting ECMAScript 6 and higher.": { - "category": "Error", - "code": 1154 - }, "'const' declarations must be initialized": { "category": "Error", "code": 1155 @@ -483,10 +443,6 @@ "category": "Error", "code": 1166 }, - "Computed property names are only available when targeting ECMAScript 6 and higher.": { - "category": "Error", - "code": 1167 - }, "A computed property name in a method overload must directly refer to a built-in symbol.": { "category": "Error", "code": 1168 @@ -547,10 +503,6 @@ "category": "Error", "code": 1182 }, - "Destructuring declarations are not allowed in ambient contexts.": { - "category": "Error", - "code": 1183 - }, "An implementation cannot be declared in ambient contexts.": { "category": "Error", "code": 1184 @@ -736,10 +688,6 @@ "category": "Error", "code": 2307 }, - "A module cannot have more than one export assignment.": { - "category": "Error", - "code": 2308 - }, "An export assignment cannot be used in a module with other exported elements.": { "category": "Error", "code": 2309 @@ -2022,10 +1970,6 @@ "category": "Message", "code": 6056 }, - "Preserve new-lines when emitting code.": { - "category": "Message", - "code": 6057 - }, "Specifies the root directory of input files. Use to control the output directory structure with --outDir.": { "category": "Message", "code": 6058 From b4b2a41bc079c9b25ae833d77102e747206a7dcc Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Thu, 25 Jun 2015 13:34:42 -0700 Subject: [PATCH 74/79] Error check script --- scripts/errorCheck.ts | 83 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 scripts/errorCheck.ts diff --git a/scripts/errorCheck.ts b/scripts/errorCheck.ts new file mode 100644 index 00000000000..d2eb5a9632e --- /dev/null +++ b/scripts/errorCheck.ts @@ -0,0 +1,83 @@ +declare var require: any; +let fs = require('fs'); +let async = require('async'); +let glob = require('glob'); + +fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { + let messages = JSON.parse(data); + if (err) throw err; + let keys = Object.keys(messages); + console.log('Loaded ' + keys.length + ' errors'); + + for(let k of keys) { + messages[k]['seen'] = false; + } + + let errRegex = /\(\d+,\d+\): error TS([^:]+):/g; + + let baseDir = 'tests/baselines/reference/'; + fs.readdir(baseDir, (err, files) => { + files = files.filter(f => f.indexOf('.errors.txt') > 0); + console.log('Read ' + files.length + ' baselines'); + let tasks: Array<(callback: () => void) => void> = []; + files.forEach(f => tasks.push(done => { + fs.readFile(baseDir + f, 'utf-8', (err, baseline) => { + if (err) throw err; + + let g: string[]; + while(g = errRegex.exec(baseline)) { + var errCode = +g[1]; + let msg = keys.filter(k => messages[k].code === errCode)[0]; + messages[msg]['seen'] = true; + } + + done(); + }); + })); + + async.parallelLimit(tasks, 25, done => { + console.log('== List of errors not present in baselines =='); + let count = 0; + for(let k of keys) { + if(messages[k]['seen'] !== true) { + console.log(k); + count++; + } + } + console.log(count + ' of ' + keys.length + ' errors are not in baselines'); + }); + }); +}); + +fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, data) => { + let errorRegexp = /\s(\w+): \{ code/g; + let errorNames: string[] = []; + let errMatch: string[]; + while(errMatch = errorRegexp.exec(data)) { + errorNames.push(errMatch[1]); + } + + let allSrc: string = ''; + glob('./src/**/*.ts', {}, (err, files) => { + console.log('Reading ' + files.length + ' source files'); + files.forEach(file => { + if (file.indexOf('diagnosticInformationMap.generated.ts') > 0) return; + + let src = fs.readFileSync(file, 'utf-8'); + allSrc = allSrc + src; + }); + + console.log('Consumed ' + allSrc.length + ' characters of source'); + + let count = 0; + console.log('== List of errors not used in source ==') + errorNames.forEach(errName => { + if(allSrc.indexOf(errName) < 0) { + console.log(errName); + count++; + } + }); + console.log(count + ' of ' + errorNames.length + ' errors are not used in source'); + }); +}); + From aa59753fe4103778ea5514da48f89cf84336eed1 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Thu, 25 Jun 2015 14:02:30 -0700 Subject: [PATCH 75/79] CR feedback --- scripts/errorCheck.ts | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/scripts/errorCheck.ts b/scripts/errorCheck.ts index d2eb5a9632e..77892cb8f0c 100644 --- a/scripts/errorCheck.ts +++ b/scripts/errorCheck.ts @@ -4,12 +4,15 @@ let async = require('async'); let glob = require('glob'); fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { - let messages = JSON.parse(data); - if (err) throw err; + if (err) { + throw err; + } + + let messages = JSON.parse(data); let keys = Object.keys(messages); console.log('Loaded ' + keys.length + ' errors'); - for(let k of keys) { + for (let k of keys) { messages[k]['seen'] = false; } @@ -18,14 +21,13 @@ fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { let baseDir = 'tests/baselines/reference/'; fs.readdir(baseDir, (err, files) => { files = files.filter(f => f.indexOf('.errors.txt') > 0); - console.log('Read ' + files.length + ' baselines'); let tasks: Array<(callback: () => void) => void> = []; files.forEach(f => tasks.push(done => { fs.readFile(baseDir + f, 'utf-8', (err, baseline) => { if (err) throw err; let g: string[]; - while(g = errRegex.exec(baseline)) { + while (g = errRegex.exec(baseline)) { var errCode = +g[1]; let msg = keys.filter(k => messages[k].code === errCode)[0]; messages[msg]['seen'] = true; @@ -38,8 +40,8 @@ fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => { async.parallelLimit(tasks, 25, done => { console.log('== List of errors not present in baselines =='); let count = 0; - for(let k of keys) { - if(messages[k]['seen'] !== true) { + for (let k of keys) { + if (messages[k]['seen'] !== true) { console.log(k); count++; } @@ -53,30 +55,32 @@ fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, let errorRegexp = /\s(\w+): \{ code/g; let errorNames: string[] = []; let errMatch: string[]; - while(errMatch = errorRegexp.exec(data)) { + while (errMatch = errorRegexp.exec(data)) { errorNames.push(errMatch[1]); } let allSrc: string = ''; glob('./src/**/*.ts', {}, (err, files) => { console.log('Reading ' + files.length + ' source files'); - files.forEach(file => { - if (file.indexOf('diagnosticInformationMap.generated.ts') > 0) return; + for(let file of files) { + if (file.indexOf('diagnosticInformationMap.generated.ts') > 0) { + continue; + } let src = fs.readFileSync(file, 'utf-8'); allSrc = allSrc + src; - }); + } console.log('Consumed ' + allSrc.length + ' characters of source'); let count = 0; console.log('== List of errors not used in source ==') - errorNames.forEach(errName => { - if(allSrc.indexOf(errName) < 0) { + for(let errName of errorNames) { + if (allSrc.indexOf(errName) < 0) { console.log(errName); count++; } - }); + } console.log(count + ' of ' + errorNames.length + ' errors are not used in source'); }); }); From c3af662e324e34d29794f30a81d7e12b8b0a645d Mon Sep 17 00:00:00 2001 From: Yui T Date: Thu, 25 Jun 2015 18:39:29 -0700 Subject: [PATCH 76/79] Change var -> let and use destructuring --- src/services/services.ts | 46 ++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index e11fb32c73b..e3d9480e062 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1797,7 +1797,7 @@ namespace ts { let outputText: string; // Create a compilerHost object to allow the compiler to read and write files - var compilerHost: CompilerHost = { + let compilerHost: CompilerHost = { getSourceFile: (fileName, target) => fileName === inputFileName ? sourceFile : undefined, writeFile: (name, text, writeByteOrderMark) => { Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); @@ -1810,7 +1810,7 @@ namespace ts { getNewLine: () => newLine }; - var program = createProgram([inputFileName], options, compilerHost); + let program = createProgram([inputFileName], options, compilerHost); addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); @@ -3084,7 +3084,7 @@ namespace ts { * accurately aggregate locals from the closest containing scope. */ function getScopeNode(initialToken: Node, position: number, sourceFile: SourceFile) { - var scope = initialToken; + let scope = initialToken; while (scope && !positionBelongsToNode(scope, position, sourceFile)) { scope = scope.parent; } @@ -3485,10 +3485,10 @@ namespace ts { function getCompletionEntriesFromSymbols(symbols: Symbol[]): CompletionEntry[] { let start = new Date().getTime(); - var entries: CompletionEntry[] = []; + let entries: CompletionEntry[] = []; if (symbols) { - var nameToSymbol: Map = {}; + let nameToSymbol: Map = {}; for (let symbol of symbols) { let entry = createCompletionEntry(symbol, location); if (entry) { @@ -3522,13 +3522,13 @@ namespace ts { let symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false) === entryName ? s : undefined); if (symbol) { - let displayPartsDocumentationsAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, location, SemanticMeaning.All); + let { displayParts, documentation, symbolKind } = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, location, SemanticMeaning.All); return { name: entryName, - kind: displayPartsDocumentationsAndSymbolKind.symbolKind, kindModifiers: getSymbolModifiers(symbol), - displayParts: displayPartsDocumentationsAndSymbolKind.displayParts, - documentation: displayPartsDocumentationsAndSymbolKind.documentation + kind: symbolKind, + displayParts, + documentation }; } } @@ -4203,7 +4203,7 @@ namespace ts { } if (type.flags & TypeFlags.Union) { - var result: DefinitionInfo[] = []; + let result: DefinitionInfo[] = []; forEach((type).types, t => { if (t.symbol) { addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node)); @@ -4303,7 +4303,7 @@ namespace ts { function getSyntacticDocumentHighlights(node: Node): DocumentHighlights[] { let fileName = sourceFile.fileName; - var highlightSpans = getHighlightSpans(node); + let highlightSpans = getHighlightSpans(node); if (!highlightSpans || highlightSpans.length === 0) { return undefined; } @@ -4881,17 +4881,17 @@ namespace ts { } function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] { - var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); + let referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); return convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + let referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); return convertReferences(referencedSymbols); } function findReferences(fileName: string, position: number): ReferencedSymbol[]{ - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + let referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); // Only include referenced symbols that have a valid definition. return filter(referencedSymbols, rs => !!rs.definition); @@ -5190,7 +5190,7 @@ namespace ts { } }); - var definition: DefinitionInfo = { + let definition: DefinitionInfo = { containerKind: "", containerName: "", fileName: targetLabel.getSourceFile().fileName, @@ -5286,10 +5286,10 @@ namespace ts { if (referenceSymbol) { let referenceSymbolDeclaration = referenceSymbol.valueDeclaration; let shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); - var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); + let relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); if (relatedSymbol) { - var referencedSymbol = getReferencedSymbol(relatedSymbol); + let referencedSymbol = getReferencedSymbol(relatedSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation)); } /* Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment @@ -5299,7 +5299,7 @@ namespace ts { * position of property accessing, the referenceEntry of such position will be handled in the first case. */ else if (!(referenceSymbol.flags & SymbolFlags.Transient) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) { - var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); + let referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } } @@ -5309,8 +5309,8 @@ namespace ts { return; function getReferencedSymbol(symbol: Symbol): ReferencedSymbol { - var symbolId = getSymbolId(symbol); - var index = symbolToIndex[symbolId]; + let symbolId = getSymbolId(symbol); + let index = symbolToIndex[symbolId]; if (index === undefined) { index = result.length; symbolToIndex[symbolId] = index; @@ -5397,7 +5397,7 @@ namespace ts { } }); - var definition = getDefinition(searchSpaceNode.symbol); + let definition = getDefinition(searchSpaceNode.symbol); return [{ definition, references }]; } @@ -5592,7 +5592,7 @@ namespace ts { // If the reference symbol is an alias, check if what it is aliasing is one of the search // symbols. if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { - var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); + let aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } @@ -6908,7 +6908,7 @@ namespace ts { } function convertClassifications(classifications: Classifications, text: string): ClassificationResult { - var entries: ClassificationInfo[] = []; + let entries: ClassificationInfo[] = []; let dense = classifications.spans; let lastEnd = 0; From 133a86a3773868178d0aa6c53981f8b68087d7a1 Mon Sep 17 00:00:00 2001 From: mihailik Date: Fri, 26 Jun 2015 09:22:55 +0100 Subject: [PATCH 77/79] Conflict with Object.prototype.watch in FireFox/Gecko In Gecko engine `commandLine.options.watch` evaluates to a truthy value (a function). Adding an extra check to work around. [Definition of CompilerOptions.watch in compiler/types](https://github.com/Microsoft/TypeScript/blob/master/src/compiler/types.ts#L1860) ``` typescript export interface CompilerOptions { // . . . watch?: boolean; ``` [Object.prototype.watch on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch) > Warning: Generally you should avoid using watch() and unwatch() when possible. These two methods are > implemented only in Gecko, and they're intended primarily for debugging use. In addition, using watchpoints > has a serious negative impact on performance, which is especially true when used on global objects, such > as window. You can usually use setters and getters or proxies instead. See Browser compatibility for details. > Also, do not confuse Object.watch with Object.observe. --- src/compiler/tsc.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 2903c3a31f4..eada189d642 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -191,7 +191,7 @@ namespace ts { return sys.exit(ExitStatus.Success); } - if (commandLine.options.watch) { + if (commandLine.options.watch && commandLine.options.hasOwnProperty('watch')) { // FireFox has Object.prototype.watch if (!sys.watchFile) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); From e7e020e958bb4e9ec7942227be32092624a4ee99 Mon Sep 17 00:00:00 2001 From: mihailik Date: Fri, 26 Jun 2015 14:38:25 +0100 Subject: [PATCH 78/79] PR feedback - comments and whitespace adjustments --- src/compiler/tsc.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index eada189d642..1851e516abd 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -191,7 +191,8 @@ namespace ts { return sys.exit(ExitStatus.Success); } - if (commandLine.options.watch && commandLine.options.hasOwnProperty('watch')) { // FireFox has Object.prototype.watch + // Firefox has Object.prototype.watch + if (commandLine.options.watch && commandLine.options.hasOwnProperty('watch')) { if (!sys.watchFile) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); From 72050073bc9d6448dc4c7114b53c4e7fcb9b6ed5 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Fri, 26 Jun 2015 10:25:58 -0700 Subject: [PATCH 79/79] use double quotes --- src/compiler/tsc.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 1851e516abd..2a01774fbca 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -192,7 +192,7 @@ namespace ts { } // Firefox has Object.prototype.watch - if (commandLine.options.watch && commandLine.options.hasOwnProperty('watch')) { + if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) { if (!sys.watchFile) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);